
// History Listing
#include "clog.h"
#include "cgi.h"
#include "input.h"
#include "wrenchboard_api.h"
#include "history.h"
#include "market.h"
#include "email.h"
#include "payments.h"
#include "safestring.h"
#include <string>
#include "pgsql.h"
#include "pgsql_wrapper.h"
#include "cfg.h"
#include "jobs.h"
#include <curl/curl.h>

long WrenchMarketImport(CVars in, CVars &out);
long WrenchPromoLoad(CVars in, CVars &out);
long WrenchPromoAdminLogin(CVars in, CVars &out);
long WrenchPromoAddList(CVars in, CVars &out);
long  WrenchPromoGetList( CVars in, CVars &out );
long  WrenchPromoGetMember( CVars in, CVars &out );
long  WrenchPromoAssignTask( CVars in, CVars &out );
long  WrenchPromoActionList( CVars in, CVars &out );

long market_calls(CVars in, CVars &out) {
    logfmt(logINFO, "market_calls()");
    long ret = PHP_API_BAD_PARAM;
    char vname[700];
    char file_section[50];
        try {
        long action = REQ_LONG( in, "action", 1, -1 );
            switch(action){
                case WRENCHBOARD_MARKET_PLAN01_START:
                    return  WrenchMarketImport(in, out);
                break;

                case WRENCHBOARD_MARKET_PLAN01_NEXT1:
                     return  WrenchPromoLoad(in, out);
                break;

                case WRENCHBOARD_PROMOADMIN_LOGIN:
                    return  WrenchPromoAdminLogin(in, out);
                break;
                //const  WRENCHBOARD_PROMOADMIN_ADDLIST   =   220015;
                case WRENCHBOARD_PROMOADMIN_ADDLIST:
                    return  WrenchPromoAddList(in, out);
                break;
                //#define WRENCHBOARD_PROMOADMIN_GETLIST    220014
                case WRENCHBOARD_PROMOADMIN_GETLIST:
                    return  WrenchPromoGetList(in, out);
                break;
                //#define  220016
                case WRENCHBOARD_PROMOADMIN_ACTIONLIST:
                    return  WrenchPromoActionList(in, out);
                break;
                case WRENCHBOARD_PROMOADMIN_GETMEMBER:
                    return  WrenchPromoGetMember(in, out);
                break;
                case WRENCHBOARD_PROMOADMIN_ASSIGNTASK:
                    return  WrenchPromoAssignTask(in, out);
                break;
            }

    } catch (bad_parameter) {
        logfmt(logINFO, "ERROR CALL long market_calls(CVars in, CVars &out)");
    }
    logfmt(logINFO, "/market_calls()");
    return ret;
}

long  WrenchPromoActionList( CVars in, CVars &out )
{
    char vname[30];
    long ret = PHP_API_BAD_PARAM;

    logfmt( logINFO, "WrenchPromoActionList()" );
    out["result"] = "Yes i go to this back end";

    try {
            long admin_id = REQ_LONG(in, "promo_admin_id", 1, -1);
            REQ_STRING (in, "admin_uid",   5, 120, "(.*)");
            OPTIONAL( in, "loc" ) REQ_STRING (in, "loc",   3, 15, "(.*)");
            long limit = REQ_LONG(in, "limit", 1, -1);
            long offset = REQ_LONG(in, "offset", 1, -1);


        const PGresult *res;
        res = pgsql_query("SELECT count(id) FROM promo_actions WHERE admin_id = %lu", admin_id);
        out["sum_total_record"] = pgsql_num_rows(res);

         res = pgsql_query("SELECT * FROM promo_actions"
                            " WHERE admin_id = %lu ORDER BY id DESC LIMIT %lu OFFSET %lu ",admin_id,limit,offset);

        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), "updated_%05d", i);
                out[vname] = rec["updated"];

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

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

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

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

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

    logfmt( logINFO, "/WrenchPromoActionList()" );
	return 0;
}

long  WrenchPromoAssignTask( CVars in, CVars &out )
{
    long ret = PHP_API_BAD_PARAM;
    CVars outX;
    CVars inj;
    CVars p;
    const PGresult *res;
    long member_id = 0;

    logfmt( logINFO, "WrenchPromoAssignTask()" );
    try {
        long admin_id = REQ_LONG(in, "promo_admin_id", 1, -1);
        REQ_STRING (in, "admin_uid",   5, 120, "(.*)");
        REQ_STRING (in, "member_uid",   5, 120, "(.*)");
        OPTIONAL( in, "loc" ) REQ_STRING (in, "loc",   3, 15, "(.*)");

         res = pgsql_query("SELECT * FROM promo_member"
                            " WHERE admin_id = %lu AND uid  = '%s' ",admin_id,in["member_uid"].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);
            out = rec;

            long retF = load_db_record( outX, "SELECT *,id AS member_id "
                                         "FROM members WHERE  (username)=LOWER('%s') ", out["email"].c_str() );
            if (retF && outX["promo_admin_id"].Long() > 0) {
                out["status_message"] = "Good Already Signup";
                member_id =  outX["member_id"].Long();
            }else{
                ret = PHP_API_OK;
                 out["status"] = "OK";
                 out["task_result"] = "User yet to complete signup";
                return ret;
            }

            if ( member_id == 0 ){
                 out["status"] = "OK";
                 out["task_result"] = "Cannot find user to assign to";
            return ret;
            }

            if ( load_db_record(p, "SELECT count(id) AS offer_count FROM members_jobs_offer WHERE client_id = %lu AND status IN (1,2) ", member_id)> 0){
               if (p["offer_count"].Long() > 0){
                    out["status"] = "OK";
                    out["task_result"] = "There is offer in place already";
                    return ret;
               }
            }

            if ( load_db_record(p, "SELECT count(id) AS contract_count FROM members_jobs_contract WHERE client_id = %lu ", member_id)> 0){
               if (p["offer_count"].Long() > 0){
                   out["status"] = "OK";
                   out["task_result"] = "Previous job found";
                   return ret;
               }
            }

            if ( load_db_record(p, "SELECT  * FROM promo_admin  WHERE uid::text ='%s' ", in["admin_uid"].c_str())> 0){

                    if ( load_db_record(inj, "SELECT j.member_id, j.uid AS job_uid, j.id AS job_id, j.title,j.description,j.country, m.uid,j.job_detail "
                                             " FROM members_jobs j LEFT JOIN members m ON m.id = j.member_id WHERE j.uid::text ='%s'",p["first_job"].c_str())> 0){
                        inj["promo"] = in["promo"];  inj["promo"].set_valid( true );
                        inj["strict_timeline"] = "10";  inj["strict_timeline"].set_valid( true );
                        inj["email"] = out["email"];  inj["email"].set_valid( true );  // email
                        inj["job_description"] = inj["job_detail"];  inj["job_description"].set_valid( true );
                        inj["action"] = WRENCHBOARD_JOB_OFFER_SYSTEM;  inj["action"].set_valid( true );
                        inj["assign_mode"] = ASSIGN_MODE_EMAIL;  inj["assign_mode"].set_valid( true );
                        out["assign_id"] =  WrenchJobOfferSystems(inj, outX);
                    }
            }

            ret = PHP_API_OK;
            out["status"] = "OK";
        }

    } catch (bad_parameter) {
        out["status"] = "ERROR";
        logfmt(logINFO, "ERROR CALL long WrenchPromoAssignTask(CVars in, CVars &out)");
    }

    out["status"] = "OK";
    out["task_result"] = "Backend Not Ready";
 return ret;
}

long  WrenchPromoGetMember( CVars in, CVars &out )
{
    char vname[30];
    long ret = PHP_API_BAD_PARAM;

    logfmt( logINFO, "WrenchPromoGetList()" );
    out["result"] = "Yes i go to this back end";

    try {
        long admin_id = REQ_LONG(in, "promo_admin_id", 1, -1);
        REQ_STRING (in, "admin_uid",   5, 120, "(.*)");
        REQ_STRING (in, "member_uid",   5, 120, "(.*)");
        OPTIONAL( in, "loc" ) REQ_STRING (in, "loc",   3, 15, "(.*)");



        const PGresult *res;
//        res = pgsql_query("SELECT count(id) FROM promo_member WHERE admin_id = %lu", admin_id);
//        out["sum_total_record"] = pgsql_num_rows(res);

         res = pgsql_query("SELECT * FROM promo_member"
                            " WHERE admin_id = %lu AND uid  = '%s' ",admin_id,in["member_uid"].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);
            out = rec;
            ret = PHP_API_OK;
            out["status"] = "OK";
        }

    } catch (bad_parameter) {
        out["status"] = "ERROR";
        logfmt(logINFO, "ERROR CALL long WrenchPromoGetMember(CVars in, CVars &out)");
    }

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


long  WrenchPromoGetList( CVars in, CVars &out )
{
    char vname[30];
    long ret = PHP_API_BAD_PARAM;

    logfmt( logINFO, "WrenchPromoGetList()" );
    out["result"] = "Yes i go to this back end";

    try {
            long admin_id = REQ_LONG(in, "promo_admin_id", 1, -1);
            REQ_STRING (in, "admin_uid",   5, 120, "(.*)");
            OPTIONAL( in, "loc" ) REQ_STRING (in, "loc",   3, 15, "(.*)");
            long limit = REQ_LONG(in, "limit", 1, -1);
            long offset = REQ_LONG(in, "offset", 1, -1);


        const PGresult *res;
        res = pgsql_query("SELECT count(id) FROM promo_member WHERE admin_id = %lu", admin_id);
        out["sum_total_record"] = pgsql_num_rows(res);

         res = pgsql_query("SELECT * FROM promo_member"
                            " WHERE admin_id = %lu ORDER BY id DESC LIMIT %lu OFFSET %lu ",admin_id,limit,offset);

        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), "updated_%05d", i);
                out[vname] = rec["updated"];

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

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

                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), "email_%05d", i);
                out[vname] = rec["email"];

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

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

    logfmt( logINFO, "/WrenchPromoGetList()" );
	return 0;
}

long WrenchPromoAddList(CVars in, CVars &out){
logfmt(logINFO, "WrenchPromoAdminLogin()");
    char vname[30];
    long ret = PHP_API_BAD_PARAM;
    long retF = -1;
    CVars outX;

    CVars x;

    try {
            REQ_STRING (in, "email",   5, 49, "(.*)");
            REQ_STRING (in, "firstname",   2, 25, "(.*)");
            REQ_STRING (in, "lastname",   2, 25, "(.*)");
            long admin_id = REQ_LONG(in, "promo_admin_id", 1, -1);
            REQ_STRING (in, "admin_uid",   5, 120, "(.*)");
            OPTIONAL( in, "loc" ) REQ_STRING (in, "loc",   3, 15, "(.*)");

            ret = load_db_record( out, "SELECT *,id AS promo_admin_id FROM promo_admin WHERE status=1 AND id=%lu AND uid::text='%s'", admin_id, in["admin_uid"].c_str() );
            if (ret && out["promo_admin_id"].Long() > 0) {

            retF = load_db_record( outX, "SELECT *,id AS promo_admin_id "
                                         "FROM promo_member WHERE (email)=LOWER('%s') AND admin_id= %lu", in["email"].c_str(), admin_id );
            if (retF && outX["promo_admin_id"].Long() > 0) {
                out["status_message"] = "Error Duplicate Found";
                ret = PHP_API_OK;
                out["status"] = "OK";
                return 0;
            }

            retF = load_db_record( outX, "SELECT *,id AS promo_admin_id "
                                         "FROM members_pending WHERE status =1 AND (username)=LOWER('%s') ", in["email"].c_str() );
            if (retF && outX["promo_admin_id"].Long() > 0) {
                out["status_message"] = "Error Already Started Signup";
                ret = PHP_API_OK;
                out["status"] = "OK";
                return 0;
            }


            retF = load_db_record( outX, "SELECT *,id AS promo_admin_id "
                                         "FROM members WHERE  (username)=LOWER('%s') ", in["email"].c_str() );
            if (retF && outX["promo_admin_id"].Long() > 0) {
                out["status_message"] = "Error Already Signup";
                ret = PHP_API_OK;
                out["status"] = "OK";
                return 0;
            }

            x["admin_id"] = admin_id; x["admin_id"].set_valid(true);
            x["email"] =  in["email"]; x["email"].set_valid(true);
            x["firstname"] =  in["firstname"]; x["firstname"].set_valid(true);
            x["lastname"] =  in["lastname"]; x["lastname"].set_valid(true);
            x["loc"] =  in["loc"]; x["loc"].set_valid(true);
            long sid = insert_db_record(DBS_VALID, "promo_member", "promo_member_id_seq", x);
            if (sid > 0 ){
              out["status_message"] = "New Entry Added";
            }


//            long retF = load_db_record( outX, "SELECT *,id AS promo_admin_id "
//                                              "FROM member WHERE (email)=LOWER('%s') AND admin_id= %lu", in["email"].c_str(), admin_id );
//            if (retF && retF["promo_admin_id"].Long() > 0) {
//                out["status_message"] = "Error Duplicate Found";
//                ret = PHP_API_OK;
//                out["status"] = "OK";
//                return 0;
//            }


                // there will be promo action

                // pgsql_query("UPDATE  promo_admin SET updated=now() WHERE id=%lu", out["promo_admin_id"].Long());
                ret = PHP_API_OK;
                out["status"] = "OK";
            }

    } catch (bad_parameter) {
        logfmt(logINFO, "ERROR CALL long WrenchMarketImport(CVars in, CVars &out)");
    }
    logfmt(logINFO, "/WrenchPromoAdminLogin()");
    return ret;
}

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

    try {
            REQ_STRING (in, "username",   5, 49, "(.*)");
            REQ_STRING (in, "password",   5, 49, "(.*)");
            OPTIONAL( in, "loc" ) REQ_STRING (in, "loc",   3, 15, "(.*)");
            ret = load_db_record( out, "SELECT *,id AS promo_admin_id, md5( now()::text )||''||md5( (now() + '1 hr')::text ) AS sessionid FROM promo_admin WHERE status=1 AND LOWER(username)=LOWER('%s') AND password= md5('%s')", in["username"].c_str(), in["password"].c_str() );
            if (ret && out["promo_admin_id"].Long() > 0) {
                pgsql_query("UPDATE  promo_admin SET updated=now() WHERE id=%lu", out["promo_admin_id"].Long());
                ret = PHP_API_OK;
                out["status"] = "OK";
            }

    } catch (bad_parameter) {
        logfmt(logINFO, "ERROR CALL long WrenchMarketImport(CVars in, CVars &out)");
    }
    logfmt(logINFO, "/WrenchPromoAdminLogin()");
    return ret;
}

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

    try {
         out["total_record"] = "0";
        const PGresult *res;
        res = pgsql_query("SELECT id AS  import_id,* FROM market_import WHERE status = 1 AND completed IS NULL ORDER BY ecount ASC LIMIT 10");

        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);
                market_email(WRENCHBOARD_MARKET_PLAN01_START, rec, rec);
                pgsql_query("UPDATE  market_import SET ecount=ecount+1 WHERE uid::text='%s'", rec["uid"].c_str());
                if ( rec["ecount"].Long() > 2 ){
                    pgsql_query("UPDATE  market_import SET completed=now() WHERE uid::text='%s'", rec["uid"].c_str());
                }
            }
        }
        ret = PHP_API_OK;
        out["status"] = "OK";
    } catch (bad_parameter) {
        logfmt(logINFO, "ERROR CALL long WrenchMarketImport(CVars in, CVars &out)");
    }
    logfmt(logINFO, "/WrenchMarketImport()");

    return ret;
}

long WrenchPromoLoad(CVars in, CVars &out) {
     logfmt(logINFO, "WrenchPromoLoad()");
      long ret = PHP_API_BAD_PARAM;
        try {
            REQ_STRING(in, "promo_owner", 2, 149, "(.*)");
            REQ_STRING(in, "promo", 2, 49, "(.*)");

            load_db_record(out, "SELECT to_char(now(), 'yyyy') AS YYYY");

            if ( load_db_record(out, "SELECT uid AS promo_owner, firstname , lastname , middlename , status,email FROM market_import  WHERE uid::text ='%s' AND status = 1", in["promo_owner"].c_str())> 0){
                if ( load_db_record(out, "SELECT  id FROM members   WHERE LOWER(username)  = LOWER('%s')", out["email"].c_str())> 0){
                  pgsql_query("UPDATE  market_import SET status = 4 WHERE uid::text = '%s' AND status = 1 ", out["promo_owner"].c_str());
                  out["status_message"] = "VALID_LINK_NOT_FOUND";
                }
                else
                {
                   out["status_message"] = "VALID_LINK_FOUND";
                }
            }
            else{
            out["status_message"] = "VALID_LINK_NOT_FOUND";
            }

            if ( load_db_record(out, "SELECT  * FROM market_promo  WHERE promo::text ='%s' ", in["promo"].c_str())> 0){

            }
            ret = PHP_API_OK;
            out["status"] = "OK";
        } catch (bad_parameter) {
             logfmt(logINFO, "ERROR CALL long WrenchPromoLoad(CVars in, CVars &out)");
        }
    logfmt(logINFO, "/WrenchPromoLoad()");
    return ret ;
}
/*
#define WRENCHBOARD_MARKET_PLAN01_START   220001
#define WRENCHBOARD_MARKET_PLAN01_NEXT1   220003
*/