// Topup management toosl
#include "clog.h"
#include "cgi.h"
#include "input.h"
#include "wrenchboard_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"

/*

wrenchboard=> SELECT type,digits,firstname,lastname,description,uid,added_dt::date,status,active FROM creditcard WHERE active = 1 AND member_id =1;
 type | digits | firstname | lastname | description |                 uid                  |  added_dt  | status | active
------+--------+-----------+----------+-------------+--------------------------------------+------------+--------+--------
  100 | 4242   | Olusesan  | Last11   | Visa        | 8d646ac6-afb8-4371-9e78-265a195971cc | 2023-06-18 |      3 |      1
  100 | 4242   | Olusesan  | Last11   | Visa        | b36d494a-0b25-4066-b0e7-e33db889f9ed | 2023-06-18 |      3 |      1
  100 | 4242   | Olusesan  | Last11   | Visa        | 12bf0b82-b20d-4358-8373-74f0133c5001 | 2023-06-18 |      3 |      1
  100 | 4242   | Olusesan  | Last11   | Visa        | a1ea56d1-ba2d-4125-a6ad-306874a672dc | 2023-06-18 |      3 |      1
  100 | 4242   | Olusesan  | Last11   | Visa        | 97e6a9ac-cbae-4ec4-baaa-c03abd5a01d2 | 2023-06-19 |      3 |      1
  100 | 4242   | Olusesan  | Last11   | Visa        | 55aa3bfe-4bf0-4dee-8133-8f3114c32207 | 2023-06-19 |      3 |      1
(6 rows)


*/
long WrenchUsersCCardList(CVars in, CVars &out) {
    logfmt(FLOG_MAX, "long WrenchUsersCCardList(CVars in, CVars &out)" );
        char vname[30];
        long ret = PHP_API_BAD_PARAM;

        try {
            REQ_LONG(in,   "member_id", 1, -1);
            REQ_STRING(in, "uid", 3, 55, "(.*)"); //234"

             out["total_record"] = "0";
            const PGresult *res;
            res = pgsql_query("SELECT type,digits,firstname,lastname,description,uid,added_dt::date,status,active "
                              " FROM creditcard WHERE active = 1 "
                              " AND length(stripe_card_id)> 0 AND member_id = %lu", in["member_id"].Long());

            if (res != NULL && pgsql_num_rows(res) > 0) {
                out["total_record"] = pgsql_num_rows(res);

                for (int i = 0, n = pgsql_num_rows(res); i < n; i++) {
                    map<const char*, const char*>f = pgsql_fetch_assoc(res, i);
                    if (f.empty()) continue;
                    CVars rec;
                    map_to_cvars(f, rec);

                    snprintf(vname, sizeof (vname), "type_%05d", i);
                    out[vname] = rec["type"];

                    snprintf(vname, sizeof (vname), "digits_%05d", i);
                    out[vname] = rec["digits"];

                    snprintf(vname, sizeof (vname), "firstname_%05d", i);
                    out[vname] = rec["firstname"];

                    snprintf(vname, sizeof (vname), "lastname_%05d", i);
                    out[vname] = rec["lastname"];

                    snprintf(vname, sizeof (vname), "description_%05d", i);
                    out[vname] = rec["description"];

                    snprintf(vname, sizeof (vname), "added_%05d", i);
                    out[vname] = rec["added_dt"];

                    snprintf(vname, sizeof (vname), "card_uid_%05d", i);
                    out[vname] = rec["uid"];

                    snprintf(vname, sizeof (vname), "active_%05d", i);
                    out[vname] = rec["active"];
                }
            }
            ret = PHP_API_OK;
            out["status"] = "OK";
        } catch (bad_parameter) {
            logfmt(logINFO, "ERROR CALL long WrenchUsersCCardList(CVars in, CVars &out)");
        }

    logfmt(FLOG_MAX, "/long save_creditcard(CVars in, CVars &out)" );
    return 0;
}

/*****************************************************************************/
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 a.id AS member_id,a.firstname,a.lastname,'' AS street1,'' AS street2,a.city,zip_code AS postal,a.state,a.country FROM members a WHERE a.id=%lu", 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);
            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;
}

