// Account management toosl
#include "clog.h"
#include "cgi.h"
#include "input.h"
#include "wrenchboard_api.h"
#include "coupons.h"
#include "email.h"
#include "safestring.h"
#include <string>
#include "pgsql.h"
#include "pgsql_wrapper.h"
#include "cfg.h"
#include <curl/curl.h>
#include "smoney.h"
#include "account_mngt.h"
#include "creditcards.h"
#include "payments.h"
#include "reco_engine.h"

/*
#define WRENCHBOARD_COUPON_START           85000

#define WRENCHBOARD_COUPON_CREATE          85010
#define WRENCHBOARD_COUPON_ACTIVATE        85015
#define WRENCHBOARD_COUPON_REDEEM          85020

#define WRENCHBOARD_COUPON_MEMLIST         85025
#define WRENCHBOARD_COUPON_PENDLIST        85030

#define WRENCHBOARD_COUPON_END            85999
****** */
long MemberCouponList( CVars in, CVars &out );


long coupons_calls(CVars in, CVars &out){
logfmt(logINFO, "coupons_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);


    switch (action) {
        case WRENCHBOARD_COUPON_CREATE:
             return CreateCoupon(in, out);
        break;

        case WRENCHBOARD_COUPON_ACTIVATE:
               return AssignCoupon(in, out);
        break;

        case WRENCHBOARD_COUPON_REDEEM:
               return RedeemCoupon(in, out);
        break;

        case WRENCHBOARD_COUPON_MEMLIST: // member list
             in["mode"] = 100; in["mode"].set_valid( true );
             return MemberCouponList(in, out);
        break;

        case WRENCHBOARD_COUPON_PENDLIST: // member list
             in["mode"] = 200; in["mode"].set_valid( true );
             return MemberCouponList(in, out);
        break;

    }
    logfmt(logINFO, "/coupons_calls()");
    return ret;
}

long RedeemCoupon( CVars in, CVars &out ){
    logfmt(logINFO, "long RedeemCoupon( CVars in, CVars &out )()");
    long ret = PHP_API_BAD_PARAM;

    const PGresult *res;

    try{
        REQ_STRING(in, "code", 5, 49, "(.*)");
        REQ_LONG(in, "member_id", 1, -1);
        REQ_LONG(in, "code_id", 1, -1);    
        const char * loc = getenv("REMOTE_ADDR");

        long payment_id = 0;
        payment_id =  WrenchMemberCouponPayment( in, out );
        if( payment_id > 0 ){
             out["payment_id"] = payment_id;
             out["status"] = "COMPLETED";
             out["status_text"] = "The coupon was redeemed successfully.";
             ret = PHP_API_OK;
        }
        else{
        out["status_text"] = "Unable to redeem the coupon.";
        }
    
    } catch (bad_parameter) {
    out["status_text"] = "Unable to redeem the coupon.";
    ret = PHP_API_BAD_PARAM;
    }

return ret;
}

// for coupon table
#define COUPON_ALLOC_STARTED   100
#define COUPON_ALLOC_ALLOCATED 200


// for allocation table
#define COUPON_ACTIVE   500


long AssignCoupon( CVars in, CVars &out ){
    long ret = 0;
    const char * loc = getenv("REMOTE_ADDR");
    const PGresult *res;

    try{

        REQ_STRING(in, "code", 5, 49, "(.*)");
        REQ_LONG(in, "member_id", 1, -1);
        long coupon_id = 0;

                res = pgsql_query("SELECT * FROM coupons WHERE  code='%s' AND status = 0", in["code"].c_str());
                if (res != NULL && pgsql_num_rows(res) > 0) {
                    map<const char*, const char*>f = pgsql_fetch_assoc(res, 0);
                    CVars rec;
                    map_to_cvars(f, rec);
                    pgsql_exec("UPDATE coupons SET status=%lu WHERE code='%s' AND status=%lu",COUPON_ALLOC_ALLOCATED,in["code"].c_str(),COUPON_ALLOC_STARTED);
                     // Now We start 
/*
CREATE TABLE coupons_allocation (
	id SERIAL,
	code VARCHAR(15) UNIQUE REFERENCES coupons( code )  NOT NULL,
	amount INT DEFAULT 0,
	member_id INT REFERENCES members(id) NOT NULL,
	added timestamp without time zone DEFAULT now(),
    active timestamp DEFAULT NULL,
	loc INET,
	status INT DEFAULT 0
	);

    wrenchboard=> SELECT substring(ca.code,0,4)||'XXXXXXXX' as code, ca.amount,m.email,m.firstname FROM coupons_allocation ca LEFT JOIN members m ON m.id=ca.member_id;
    code     | amount |        email         | firstname
-------------+--------+----------------------+-----------
 1M5XXXXXXXX |      0 | ses66181+1@gmail.com | Olusesan
*/
                    CVars xx;
                    xx["member_id"] = in["member_id"];  xx["member_id"].set_valid(true);
                    xx["code"]      = rec["code"];      xx["code"].set_valid(true);
                    xx["amount"]    = rec["amount"];    xx["amount"].set_valid(true);
                    xx["status"]    = COUPON_ACTIVE;    xx["status"].set_valid(true);

                    coupon_id = insert_db_record(DBS_VALID, "coupons_allocation", "coupons_allocation_id_seq", xx);
                    if (coupon_id >  0 ){
                        CVars inx;
                        inx["member_id"] = xx["member_id"];  inx["member_id"].set_valid(true);
                        inx["coupon_id"] = coupon_id;        inx["coupon_id"].set_valid(true);
                        // mark status on coupon  
                        pgsql_exec("UPDATE coupons SET active=now(), status=%lu WHERE code='%s'  AND status=0",COUPON_ALLOC_STARTED,in["code"].c_str());
                        // send allocation email
                        coupon_email(WRENCHBOARD_COUPON_ACTIVATE,  inx, out);
                        recommendation_engine(RECOMMEND_COUPON , inx, out); // trigger the card interaction in apps

                        CVars xy;
                        if ( load_db_record(xy, "SELECT id AS member_id, uid AS member_uid, 'message.svg' AS icon  "
                                                " FROM members WHERE id = %lu ",in["member_id"].Long()) > 0 ){
                                     xy["msg"] = "You have received a free coupon !!!";
                                     xy["msg"].set_valid(true);
                                     plan_notification(xy, out);
                         }

                    }


                }
                else{
                    CVars xx;
                  //  xx["member_id"] = in["member_id"]; xx["member_id"].set_valid(true);
                  //  xx["pref_id"]   = in["pref_id"];   xx["pref_id"].set_valid(true);
                  //  xx["status"]    = in["status"];    xx["status"].set_valid(true);
                   // insert_db_record(DBS_VALID, "members_settings", "members_settings_id_seq", xx);
                }
                ret = PHP_API_OK;


    } catch (bad_parameter) {
    ret = PHP_API_BAD_PARAM;
    }

return ret;
}


long MemberCouponList( CVars in, CVars &out ){
  logfmt(logINFO, "MemberCouponList()");
    char vname[30];
    long ret = PHP_API_BAD_PARAM;

    try {
         REQ_LONG(in, "member_id", 1, -1);
         long mode = REQ_LONG(in, "mode", 1, -1);
       
             in["active_q"] = "ca.active IS NOT NULL";
            if ( mode == 200 ){
                in["active_q"] = "ca.active IS NULL";
            }
                in["active_q"].set_valid( true );

         out["total_record"] = "0";
        const PGresult *res;
        
        res = pgsql_query(" SELECT id AS coupon_id, ca.code, ca.amount, ca.added::date,ca.status,ca.active,ca.uid AS allocation_uid   "
                          " FROM coupons_allocation ca WHERE ca.member_id = %lu  "
                          " AND %s ORDER BY ca.id DESC", in["member_id"].Long(),in["active_q"].c_str());

        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), "coupon_id_%05d", i);
                out[vname] = rec["coupon_id"];
                
                snprintf(vname, sizeof (vname), "code_%05d", i);
                out[vname] = rec["code"];

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

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

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

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

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


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

long CreateCoupon( CVars in, CVars &out ){
 long ret = 0;
            logfmt(logINFO, "CreateCoupon()");
            REQ_STRING(in, "code", 5, 49, "(.*)");
            REQ_LONG(in, "amount", 1, -1);
            CVars x;
            x["code"] = in["code"];
            x["code"].set_valid(true);
            x["amount"] = in["amount"];
            x["amount"].set_valid(true);
            x["description"]  = in["description"];
            x["description"].set_valid(true);

            ret = insert_db_record(DBS_VALID, "coupons", "coupons_id_seq", x);
            if (ret > 0) {
                x["coupon_id"] = ret;
                x["coupon_id"].set_valid(true);

               // account_email(ACCOUNT_CONTACT_ALERT, x, out);
            }


return 0;
}