// Twillo management toosl
#include "clog.h"
#include "cgi.h"
#include "input.h"
#include "wrenchboard_api.h"
#include "cards.h"
#include "email.h"
#include "safestring.h"
#include <string>
#include "pgsql.h"
#include "pgsql_wrapper.h"
#include <curl/curl.h>
#include "account.h"
#include "reco_engine.h"

#include "twilo.h"

long createMembercard(CVars in, CVars &out);
long card_calls(CVars in, CVars &out) {
    logfmt(logINFO, "card_calls()");
    out["result"] = "YES I GET TO BACK END";
    long action = REQ_LONG(in, "action", 0, -1);
    CVars x;
    long ret = 0;
    const char * loc = getenv("REMOTE_ADDR");
    const PGresult *res;
    logfmt(logINFO, "action = %ld", action);
   //test();

    switch (action) {
        case WRENCHBOARD_CARDS_GETCARDLIST:
            return getMembercards(in, out);
            break;
        case WRENCHBOARD_CARDS_CREATECARD:
            return createMembercard(in, out);
            break;
        case WRENCHBOARD_CARDS_UPDATECARD:
            return 0; //CompleteMobileAccountCreation(in, out);
            break;
    }
    logfmt(logINFO, "/card_calls()");
    return ret;
}
/*
CREATE TABLE members_cards (
	id SERIAL,
	card_type VARCHAR(15)  REFERENCES card_type( code )  NOT NULL,
	card_style VARCHAR(15)  REFERENCES card_style( style )  NOT NULL,
	card_icon VARCHAR(15)  REFERENCES card_icon( icon )  NOT NULL,
	member_id INT REFERENCES members(id) NOT NULL,
	title VARCHAR(35) NOT NULL,
	description VARCHAR(55) NOT NULL,
	blog_id INT DEFAULT 0,
	added timestamp without time zone DEFAULT now(),
	expire timestamp without time zone DEFAULT now(),
    active timestamp DEFAULT NULL,
	loc INET,
	status INT DEFAULT 0
	);
*/
long createMembercard(CVars in, CVars &out){
    CVars y;
    long card_id = PHP_API_BAD_PARAM;
    try {
         long member_id = REQ_LONG(in, "member_id", 1, -1);
         REQ_STRING(in, "card_type", 5, 14, "(.*)");
         REQ_STRING(in, "card_style", 2, 14, "(.*)");
         REQ_STRING(in, "card_icon", 2, 14, "(.*)");
         REQ_STRING(in, "title", 5, 34, "(.*)");
         REQ_STRING(in, "description", 5, 54, "(.*)");
         OPTIONAL(in, "blog_id")  REQ_LONG(in, "blog_id", 1, -1);
         OPTIONAL(in, "offer_id")  REQ_LONG(in, "offer_id", 1, -1);
         const char * loc = getenv("REMOTE_ADDR");

         bool continue_insert = false;
         //const PGresult *res = pgsql_query("SELECT id FROM members_cards WHERE member_id=%lu AND card_type = '%s'", in["member_id"].Long(), in["card_type"].c_str());
            if (load_db_record(y, "SELECT * FROM members_cards WHERE member_id=%lu AND card_type = '%s' LIMIT 1", in["member_id"].Long(), in["card_type"].c_str()) > 0) {
                card_id = y["id"].Long();
                pgsql_exec("UPDATE members_cards SET active=NOW(),status =1,expire = now()+'2 days' WHERE member_id=%lu AND card_type = '%s' AND id = %lu", member_id,in["card_type"].c_str(),card_id);
            }
            else
            {
             continue_insert= true;
            }

            if(continue_insert){
                CVars x;
                x["member_id"] = member_id;
                x["member_id"].set_valid(true);
                x["card_type"] = in["card_type"];
                x["card_type"].set_valid(true);
                x["card_style"] = in["card_style"];
                x["card_style"].set_valid(true);
                x["card_icon"] = in["card_icon"];
                x["card_icon"].set_valid(true);
                x["title"] = in["title"];
                x["title"].set_valid(true);
                x["description"] = in["description"];
                x["description"].set_valid(true);
                x["blog_id"] = in["blog_id"];
                x["blog_id"].set_valid(true);
                x["offer_id"] = in["offer_id"];
                x["offer_id"].set_valid(true);
                x["loc"] = loc;
                x["loc"].set_valid(true);
                x["status"] = "1";
                x["status"].set_valid(true);

                card_id = insert_db_record(DBS_VALID, "members_cards", "members_cards_id_seq", x);
                pgsql_exec("UPDATE members_cards SET active = now(),expire = now()+'2 days' WHERE id = %lu",card_id);
             //   pgsql_exec("UPDATE members_cards SET expire = now()+'2 days' WHERE id = %lu",card_id);
            }




     } catch (bad_parameter) {
        logfmt(logINFO, "ERROR CALL long createMembercard");
    }
    logfmt(logINFO, "/createMembercard()");
    return card_id;
}
long getMembercards(CVars in, CVars &out){
    char vname[30];
    long ret = PHP_API_BAD_PARAM;

    try {
         REQ_LONG(in, "member_id", 1, -1);
         out["total_record"] = "0";
        const PGresult *res;
        res = pgsql_query("SELECT * FROM members_cards  WHERE member_id =%lu AND expire > now() AND status =  1 ORDER BY added DESC", 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), "assign_id_%05d", i);
                out[vname] = rec["id"];

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

                // amount  | id | code  | description | symbol |  action_type  | lorder | current_balance
                snprintf(vname, sizeof (vname), "description_%05d", i);
                out[vname] = rec["description"];

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

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

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

            }
        }
        ret = PHP_API_OK;
        out["status"] = "OK";
    } catch (bad_parameter) {
        logfmt(logINFO, "ERROR CALL long getMembercards(CVars in, CVars &out)");
    }
    logfmt(logINFO, "/getMembercards()");
    return ret;
}

/*
     ['title'=>'This is your coupon',
                    'description'=>'This is the description of the description',
                    'card_type'=>'COUPON',
                    'card_style' =>'card1',
                    'card_icon' =>'icon1',
                    'assign_id'=> 0,
                    'Nigeria'],
                ['title'=>'A Recommended S
                */
