// Topup management toosl
#include "clog.h"
#include "cgi.h"
#include "input.h"
#include "jubabox_api.h"
#include "safestring.h"
#include <string>
#include "pgsql.h"
#include "pgsql_wrapper.h"
#include <curl/curl.h>
/* -- */
#include "function_members.h"
#include "creditcards.h"
#include "stripe_charge.h"

/*****************************************************************************/
long save_creditcard(CVars in, CVars &out) {
    logfmt(FLOG_MAX, "long save_creditcard(CVars in, CVars &out)" );
    long card_id = 0;


    try {
        CVars v;

	REQ_LONG(in,   "member_id", 1, -1); // Does not make any sence without member persitence
        REQ_STRING(in, "cardnumber", 12, 16, "(.*)"); //4111111111111111"
        REQ_STRING(in, "cvc", 3, 4, "(.*)"); //234"
        REQ_LONG(in,   "paymenttype", 0, -1);
        REQ_STRING(in, "exp_month", 2, 2, "(.*)");
        REQ_STRING(in, "exp_year", 4, 4, "(.*)");

	if ( load_db_record( v, "SELECT b.member_id,a.firstname,a.lastname,b.street1,b.street2,b.city,b.zipcode AS postal,b.state,b.country FROM members a, members_profile b WHERE a.id=%lu AND b.member_id=a.id", in["member_id"].Long()) > 0) {

            logfmt(logDEBUG, "Loaded member %s %s", v["firstname"].c_str(), v["lastname"].c_str());

            v["member_id"].set_valid(true);
            v["firstname"].set_valid(true);
            v["lastname"].set_valid(true);
            v["street1"].set_valid(true);
            v["street2"].set_valid(true);
            v["city"].set_valid(true);
            v["state"].set_valid(true);
            v["postal"].set_valid(true);
            v["country"].set_valid(true);

            v["type"] = in["paymenttype"];
            v["type"].set_valid(true);

            v["card"] = in["cardnumber"]; /* could be dirty */
            v["cvv2"] = in["cvc"];       /* we are not saving it */

            v["digits"] = in["cardnumber"].substr(in["cardnumber"].length() - 4, 4);
            v["digits"].set_valid(true);

            v["description"] = in["description"];
            v["description"].set_valid(true);

            v["expiration_month"] = in["exp_month"];
            v["expiration_month"].set_valid(true);
            v["expiration_year"] = in["exp_year"];
            v["expiration_year"].set_valid(true);

            logfmt(logDEBUG, "About to call stripe: ");
            card_id = stripe_save_card(v, out);
            
            if (card_id > 0 )
            {
                pgsql_exec("UPDATE members SET def_card=%lu WHERE id=%lu", card_id, in["member_id"].Long() );   
            }
            logfmt(logDEBUG, "...stripe call complete!");
        } else {
            logfmt(FLOG_MAX, "No member data loaded!" );
            throw bad_parameter( in, "member_id" );
        }
    } catch (bad_parameter) {
        card_id = PHP_API_BAD_PARAM;
    }
    logfmt(FLOG_MAX, "/long save_creditcard(CVars in, CVars &out)" );
    return card_id;
}

