#include "email.h"
#include "cron_email.h"
#include "clog.h"
#include "cgi.h"
#include "input.h"
#include "wrenchboard_api.h"
#include "safestring.h"
#include "cfg.h"
#include <string>
#include "pgsql_wrapper.h"
#include "pgsql.h"

void vars2form(CVars &v, C_CGI_Form &form);

extern int mailsend(CVars in, CVars &out);

long getContractMemberClientEmail(long contract_id, CVars &out);

long plan_notification(CVars in, CVars &out){
//wrenchboard=> SELECT id AS member_id, uid AS member_uid, 'alert.svg' AS icon  FROM members WHERE username = 'ses66181+1@gmail.com';
// member_id |              member_uid              |   icon
//-----------+--------------------------------------+-----------
//         1 | 3119b744-42ad-4834-bb83-b737588754ca | alert.svg
//(1 row)
/*
CREATE TABLE members_notification (
		id SERIAL,
		uid uuid DEFAULT  uuid_generate_v4(),
		member_id INT REFERENCES members(id) NOT NULL,
		member_uid VARCHAR(150) NOT NULL,
		icon VARCHAR(25) DEFAULT 'alert.svg',
		msg VARCHAR(350) NOT NULL,
		status INT DEFAULT 1,
		added timestamp without time zone DEFAULT now(),
		send timestamp without time zone,
		send_result VARCHAR(15)
	);
*/
  long ret = PHP_API_BAD_PARAM;
    try{
        REQ_LONG(in, "member_id", 1, -1);
        REQ_STRING(in, "member_uid", 20, 120, "(.*)");
        REQ_STRING(in, "msg", 2, 300, "(.*)");
                   CVars x;

                    x["member_id"] = in["member_id"];
                    x["member_id"].set_valid(true);
                    x["member_uid"] = in["member_uid"];
                    x["member_uid"].set_valid(true);

                    x["msg"] = in["msg"];
                    x["msg"].set_valid(true);

                    if ( in["icon"] != ""){
                     x["icon"] = in["icon"];
                     x["icon"].set_valid(true);
                    }

                    ret = insert_db_record(DBS_VALID, "members_notification", "members_notification_id_seq", x);

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

long promo_email(long mailtype, CVars in, CVars &out){
    logfmt(logINFO, "alert_email()");
    CVars x, y, z;
    C_CGI_Form form("", "");
    out["alertemail"] = CfgReadChar("transnotif.contact");
    out["signupreport"] = CfgReadChar("transnotif.signupreport");

    CVars yr;
    load_db_record(yr, "SELECT to_char(now(), 'yyyy') AS YYYY, TO_CHAR(NOW(), 'Day Mon dd, yyyy hh:mm AM') AS report_date");
    vars2form(yr, form);

    //char * server_name = getenv("SERVER_NAME");
    //form.LetStr("server_name", server_name);
    //form.LetStr("site_name", "WrenchBoard");
    form.LetStr("site_trade_name", "Connecting Opportunities");

    out["server_name"] =  CfgReadChar("system.server_name");
    form.LetStr("server_name",  out["server_name"].c_str());
    //form.LetStr("site_name", "WrenchBoard");
    //form.LetStr("site_trade_name", "Connecting Opportunities");

    switch (mailtype) {

        case WRB_CRONJOB_PROCESS_PROMO:
            vars2form(in, form);
            form.LetStr("email", in["email"]);
            form.Email("PROMO/promo_alert.mailfile");
            break;

            case WRENCHBOARD_PROMOADMIN_ADDLIST:
                vars2form(in, form);
                form.LetStr("email", in["email"]);
                form.Email("PROMO/member_referpromo_individual.mailfile");
                break;
    }
    return 0;
}

long alert_email(long mailtype, CVars in, CVars &out) {
    logfmt(logINFO, "alert_email()");
    CVars x, y, z;
    C_CGI_Form form("", "");
    out["alertemail"] = CfgReadChar("transnotif.contact");
    out["signupreport"] = CfgReadChar("transnotif.signupreport");

    CVars yr;
    load_db_record(yr, "SELECT to_char(now(), 'yyyy') AS YYYY");
    vars2form(yr, form);

    char * server_name = getenv("SERVER_NAME");
    form.LetStr("server_name", server_name);
    form.LetStr("site_name", "WrenchBoard");
    form.LetStr("site_trade_name", "Connecting Opportunities");
    switch (mailtype) {

        case WRB_CRONJOB_SIGNUP_ALERT:
            vars2form(in, form);
            form.LetStr("email", out["signupreport"]);
            form.Email("ALERT/alert_daily_stats.mailfile");
            break;

        case WRB_CRONJOB_PENDINGSM:
            vars2form(in, form);
            form.LetStr("email", out["signupreport"]);
            form.Email("ALERT/alert_smpening.mailfile");
        break;

    }
    return 0;
}

long SendmarketMessage(CVars in, CVars &out) {
    logfmt(logINFO, "SendmarketMessage()");
    CVars x, y, z;
    C_CGI_Form form("", "");


    CGIList * inv_list = new CGIList(&form, "inv_items");
    char listing_items[1024];
    const PGresult *res;

    //out["alertemail"] = CfgReadChar("transnotif.contact");
    //out["signupreport"] = CfgReadChar("transnotif.signupreport");

    char * server_name = getenv("SERVER_NAME");
    // form.LetStr("server_name", server_name);
    form.LetStr("site_name", "WrenchBoard");
    form.LetStr("site_trade_name", "Connecting Opportunities");
    vars2form(in, form);

	in["server_name"] = CfgReadChar("system.server_name");
    form.LetStr("server_name",  in["server_name"].c_str());
	
   // in["server_name"] = "https://dashboard.wrenchboard.com";
    
    int c = 0;



    res = pgsql_query("SELECT o.offer_code,o.*,j.title,j.description,j.timeline_days,j.price,j FROM members_jobs_offer o LEFT JOIN members_jobs j ON j.id =o.job_id WHERE o.public_view =1 AND o.expire> now() AND o.status=1 ORDER BY o.id DESC LIMIT 5");

    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++) {
            in["color"] = "FFFFFF";
            if (c > 0) {
                in["color"] = "ebfaeb";
            }

            c++;
            map<const char*, const char*>f = pgsql_fetch_assoc(res, i);
            if (f.empty()) continue;
            CVars rec;
            map_to_cvars(f, rec);

            sprintf(listing_items, "<TR><td style='background-color:#%s'><h3><a href='%s/plb/viewjob/%s'>%s</a></h3>%s<br><b>Duration:</b>%s Day(s)</td></TR>", in["color"].c_str(), in["server_name"].c_str(), rec["offer_code"].c_str(), rec["title"].c_str(), rec["description"].c_str(), rec["timeline_days"].c_str());
            inv_list->LetStr("pin", listing_items);
            inv_list->CloseElement();
            //<hr size=1 color=#FF0000>
            if (c > 1) {
                c = 0;
            }
        }
    }

    res = pgsql_query("SELECT * , id AS promo_id FROM promotion WHERE promo='%s' AND status=1 AND sent IS NULL LIMIT %lu", in["promo"].c_str(), in["limit"].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);

            vars2form(rec, form);
            form.LetStr("server_name", in["server_name"].c_str() );
            form.LetStr("subject", "WrenchBoard - Some tasks that someone you know may like");
            form.LetStr("email", rec["email"]);
            form.Email("PROMO/promotion1.mailfile");

            pgsql_query("UPDATE promotion SET status = 5,sent=now() WHERE id =%lu", rec["promo_id"].Long());

        }
    }





    return 0;
}

long cron_email(long mailtype, CVars in, CVars &out) {
    /*
     * member_id needed
     * case WRB_CRONJOB_PASTDUE_ALERT
     SELECT  '<b>Project ID:</b>'||mc.contract||'<br><b>Title:</b>'||mc.title AS Project,m.firstname||' '||m.lastname AS Client, '<b>Timeline:</b> '||mc.timeline_days||' day(s)<br><b>Price:</b>'||mc.price*0.01 ,mc.description, (CASE WHEN mc.status = 1 AND mc.delivery_date > now() THEN 'Active' WHEN mc.status = 1 AND mc.delivery_date <now() THEN 'Past Due'  WHEN mc.status = 4 THEN 'Review' ELSE 'Not Set' END) AS status  FROM members_jobs_contract mc LEFT JOIN members m ON m.id=mc.client_id  WHERE mc.member_id = 1 AND mc.status IN (1,2)   AND delivery_date < now()
     */

    /*
     pending send money 
     */
    
       //REQ_LONG( in, "member_id", 1, -1 );
    CVars x;
    C_CGI_Form form("", "");

    CGIList * inv_list = new CGIList(&form, "inv_items");
    char listing_items[1024];
    char late_subject[120];
    const PGresult *res;

   // char * server_name = getenv("SERVER_NAME");
   // form.LetStr("server_name", server_name);
	
	in["server_name"] = CfgReadChar("system.server_name");
    form.LetStr("server_name",  in["server_name"].c_str());
	
	
    form.LetStr("site_name", "WrenchBoard");
    form.LetStr("site_trade_name", "Connecting Opportunities");

    try {

        CVars yr;
        load_db_record(yr, "SELECT to_char(now(), 'yyyy') AS YYYY");
        vars2form(yr, form);

        switch (mailtype) {
   
       

            case WRB_CRONJOB_PASTDUE_ALERT:
                REQ_LONG(in, "member_id", 1, -1);
                if (load_db_record(x, "SELECT *,email as email2,to_char(last_login, 'Day Mon dd, yyyy HH:MI AM') AS last_login2 FROM members WHERE id = %lu ", in["member_id"].Long())) {
                  

                   // in["server_name"] = "https://dashboard.wrenchboard.com";

                    int c = 0;

                    x["job_list_head"] = "";

                    res = pgsql_query("     SELECT  '<b>Project ID:</b>'||mc.contract||'<br><b>Title:</b>'||mc.title AS project,mc.delivery_date::date delivery_date,"
                            "m.firstname||' '||m.lastname AS Client, '<b>Timeline:</b> '||mc.timeline_days||' day(s)<br><b>Reward:</b>'||mc.price*0.01||' '||cc.description AS detail ,mc.description, "
                            "(CASE WHEN mc.status = 1 AND mc.delivery_date > now() THEN 'Active' WHEN mc.status = 1 AND mc.delivery_date <now() THEN 'Past Due'  WHEN mc.status = 4 THEN 'Review' ELSE 'Not Set' END) AS status  "
                            " FROM members_jobs_contract mc "
                            " LEFT JOIN members_jobs mj ON mj.id = mc.job_id "
                            " LEFT JOIN currency cc ON cc.country = mj.country "
                            " LEFT JOIN members m ON m.id=mc.client_id  "
                            "WHERE mc.member_id = %lu AND mc.status IN (1,2)  "
                            " AND mc.delivery_date < now() ORDER BY mc.delivery_date DESC LIMIT 8", in["member_id"].Long());
                    
                    
                    if (res != NULL && pgsql_num_rows(res) > 0) {
                        in["job_list_head"] = "Recently added job(s)";
                        
                        out["total_record"] = pgsql_num_rows(res);
                        
                        sprintf(late_subject, "You have %lu Past Due Task(s)", out["total_record"].Long());
                        form.LetStr("subject", late_subject);


                        for (int i = 0, n = pgsql_num_rows(res); i < n; i++) {
                            in["color"] = "FFFFFF";
                            if (c > 0) {
                                in["color"] = "ebfaeb";
                            }
                            in["color"].set_valid( true );

                            map<const char*, const char*>f = pgsql_fetch_assoc(res, i);
                            if (f.empty()) continue;
                            CVars rec;
                            map_to_cvars(f, rec);
                            sprintf(listing_items, "<TR style='background-color:#%s'><td >%s</td><td>%s</td><td><b>%s</b><br>%s</td></TR>", in["color"].c_str(), rec["project"].c_str(), rec["detail"].c_str(), rec["status"].c_str(), rec["delivery_date"].c_str());
                            inv_list->LetStr("pin", listing_items);
                            inv_list->CloseElement();
                            //<hr size=1 color=#FF0000>
                            c++;
                            if (c > 1) {
                                c = 0;
                            }
                        }
                    }


                    vars2form(x, form);
                    form.LetStr("email", x["email2"].c_str());
                  //  form.LetStr("email", "ses66181+pastdue@gmail.com");
                    form.Email("JOB/job_pastdue_m.mailfile");
                }
                break;

                case WRB_CRONJOB_PENDOFFER_ALERT:
                    vars2form(x, form); // need to remove
                    vars2form(in, form);
                    form.LetStr("email", in["email"].c_str());
                    form.Email("REMINDER/offer_pending_reminder.mailfile");
                break;

                case WRB_CRONJOB_HOLIDAY_BROADCAST:
                    vars2form(x, form); // need to remove
                    vars2form(in, form);
                    form.LetStr("email", in["email"].c_str());
                    form.Email("HOLIDAY/independence_ng_2025.mailfile");
                break;
        }

    } catch (bad_parameter) {

    }
    return  0;
}

long coupon_email(long mailtype, CVars in, CVars &out) {

   //REQ_LONG( in, "member_id", 1, -1 );
    CVars x;
    C_CGI_Form form("", "");

    CGIList * inv_list = new CGIList(&form, "inv_items");
    char listing_items[1024];
    const PGresult *res;
    bool exclude_email = true;
   // char * server_name = getenv("SERVER_NAME");
   // form.LetStr("server_name",  "https://dashboard.wrenchboard.com");
	
	in["server_name"] = CfgReadChar("system.server_name");
    form.LetStr("server_name",  in["server_name"].c_str());
	
    form.LetStr("site_name", "WrenchBoard");
    form.LetStr("site_trade_name", "Connecting Opportunities");

 try {
        CVars yr;
        load_db_record(yr, "SELECT to_char(now(), 'yyyy') AS YYYY");
        vars2form(yr, form);

        switch (mailtype) {
            case WRENCHBOARD_COUPON_ACTIVATE:
                REQ_LONG(in, "coupon_id", 1, -1);
                if (load_db_record(x, "SELECT substring(ca.code,0,4)||'XXXXXXXX' as code, ca.amount*0.01 AS coupon_amount,m.email,m.firstname FROM coupons_allocation ca LEFT JOIN members m ON m.id=ca.member_id WHERE ca.id  = %lu ", in["coupon_id"].Long())) {
                    vars2form(x, form);
                    form.LetStr("email", x["email"].c_str());
                     form.LetStr("currency", "Naira");
                    form.Email("COUPON/member_coupon_allocated.mailfile");
                }
                break;
        }

    } catch (bad_parameter) {

    }

    return 0;
}

long market_email(long mailtype, CVars in, CVars &out) {

   //REQ_LONG( in, "member_id", 1, -1 );
    CVars x;
    C_CGI_Form form("", "");

    CGIList * inv_list = new CGIList(&form, "inv_items");
    char listing_items[1024];
    const PGresult *res;
    bool exclude_email = true;
   // char * server_name = getenv("SERVER_NAME");
   // form.LetStr("server_name",  "https://dashboard.wrenchboard.com");

	in["server_name"] = CfgReadChar("system.server_name");
    form.LetStr("server_name",  in["server_name"].c_str());

    in["promo_server_name"] = CfgReadChar("system.promo_server_name");
    form.LetStr("promo_server_name",  in["promo_server_name"].c_str());

    form.LetStr("site_name", "WrenchBoard");
    form.LetStr("site_trade_name", "Connecting Opportunities");

 try {

        CVars yr;
        load_db_record(yr, "SELECT to_char(now(), 'yyyy') AS YYYY");
        vars2form(yr, form);


        switch (mailtype) {

            case WRENCHBOARD_BKO_MARKETING_MSG:
               	REQ_STRING (in, "uid",   5, 149, "(.*)");
                     if (load_db_record(x, "SELECT *, uid AS promo_uid FROM market_import WHERE id = %lu", in["import_id"].Long())) {
                    vars2form(x, form);
//                    form.LetStr("subject", "WrenchBoard - Connect with Rewards.");
//                    form.LetStr("email", x["market_email"].c_str());
//                    form.Email("PROMO/promotion1.mailfile");

                   // form.Email("PROMO/promotion2.mailfile");
                  //  form.Email("PROMO/promotion_a.mailfile");

                      vars2form(x, form);
                      form.LetStr("subject", "View opportunities at");
                      form.LetStr("email", x["email"].c_str());
                      //form.LetStr("email", "ameye@chiefsoft.com");
                      form.Email("MARKET/market_invite_step1.mailfile");

                }
                break;

            case WRENCHBOARD_MARKET_PLAN01_START:
                if (load_db_record(x, "SELECT *, uid AS promo_uid FROM market_import WHERE id = %lu", in["import_id"].Long())) {
                    vars2form(x, form);
                    form.LetStr("subject", "View opportunities at");
                    form.LetStr("email", x["email"].c_str());
                    //form.LetStr("email", "ameye@chiefsoft.com");
                    form.Email("MARKET/market_invite_step1.mailfile");
                }
                break;

                case WRENCHBOARD_MARKET_PLAN01_NEXT1:
                if (load_db_record(x, "SELECT *, uid AS promo_uid  FROM market_import WHERE id = %lu", in["import_id"].Long())) {
                    vars2form(x, form);
                    form.LetStr("subject", "View opportunities at");
                    form.LetStr("email", x["email"].c_str());
                    //form.LetStr("email", "ameye@chiefsoft.com");
                    form.Email("MARKET/market_invite_step1.mailfile");
                }
                break;
        }

    } catch (bad_parameter) {

    }

    return 0;
}

long family_email(long mailtype, CVars in, CVars &out) {

   //REQ_LONG( in, "member_id", 1, -1 );
    CVars x;
    CVars y;
    C_CGI_Form form("", "");

    CGIList * inv_list = new CGIList(&form, "inv_items");
    char listing_items[1024];
    const PGresult *res;
    bool exclude_email = true;
   // char * server_name = getenv("SERVER_NAME");
   // form.LetStr("server_name",  "https://dashboard.wrenchboard.com");

	in["server_name"] = CfgReadChar("system.server_name");
    form.LetStr("server_name",  in["server_name"].c_str());

    form.LetStr("site_name", "WrenchBoard");
    form.LetStr("site_trade_name", "Connecting Opportunities");

 try {

        switch (mailtype) {

            case WRENCHBOARD_FAMILY_SGGESTTASKS:
                REQ_LONG(in, "suggest_id", 1, -1);
                if (load_db_record(x, "SELECT s.*,m.email AS parent_email,f.firstname AS family_firstname FROM members_family_suggesttask s "
                                      " LEFT JOIN members_family f ON f.family_member_id = s.member_id "
                                      " LEFT JOIN members m ON m.id=f.member_id WHERE s.id = %lu", in["suggest_id"].Long())) {
                    vars2form(x, form);
                    form.LetStr("subject", "You have received a task suggestion from");
                    form.LetStr("email", x["parent_email"].c_str());
                    form.Email("FAMILY/family_suggest_task.mailfile");
                }
                break;

                case WRENCHBOARD_RELATIVES_REMINDER:
                    load_db_record(x, "SELECT * FROM members_family_relative WHERE id = %lu  ",out["relative_id"].Long());
                    load_db_record(y, "SELECT firstname AS inv_firstname, lastname AS inv_lastname  FROM members WHERE id  = %lu ",x["member_id"].Long());
                    vars2form(x, form);
                    vars2form(y, form);
                    form.LetStr("subject", "Invitation to Join Our Family Platform on WrenchBoard");
                    form.LetStr("email", x["email"].c_str());
                    form.Email("FAMILY/family_relative_invite.mailfile");
                break;

        }

    } catch (bad_parameter) {

    }

    return 0;
}


long account_email(long mailtype, CVars in, CVars &out) {

    CVars x, ml;
    C_CGI_Form form("", "");

    CGIList * inv_list = new CGIList(&form, "inv_items");
    char listing_items[1024];
    const PGresult *res;
    bool exclude_email = true;
    char * server_name = getenv("SERVER_NAME");
	
	out["server_name"] =  CfgReadChar("system.server_name");
    form.LetStr("server_name",  out["server_name"].c_str());
    form.LetStr("site_name", "WrenchBoard");
    form.LetStr("site_trade_name", "Connecting Opportunities");

    CVars yr;
    load_db_record(yr, "SELECT to_char(now(), 'yyyy') AS YYYY");
    vars2form(yr, form);


    try {

        switch (mailtype) {
            case ACCOUNT_RESEND_PENDING:
                return AccountPendingMail(in);
                break;

            case ACCOUNT_SEND_REFEREMAIL:
                REQ_LONG(in, "refer_id", 1, -1);
                ml["action"] = ACCOUNT_SEND_REFEREMAIL; ml["action"].set_valid( true );
                ml["topic"] = "ACCOUNT_SEND_REFEREMAIL";  ml["topic"].set_valid( true );
                ml["refer_id"] =  in["refer_id"];  ml["refer_id"].set_valid( true );
                //ml["interest_id"] =  in["interest_id"];  ml["interest_id"].set_valid( true );
                submit_cron_email(ml);

//
//                if (load_db_record(x, "SELECT r.*,m.firstname AS send_firstname,m.lastname AS send_lastname,date_part('year',now()) AS yyyy FROM members_refer_friend r LEFT JOIN members m ON m.id = r.member_id WHERE r.id  = %lu ", in["refer_id"].Long())) {
//                    vars2form(x, form);
//                    form.LetStr("email", x["email"].c_str());
//                    form.Email("ACCOUNT/member_refer_individual.mailfile");
//                }
                break;

            case ACCOUNT_CREATED_MAIL:

                break;

            case ACCOUNT_SENDMONEY_ALERT:

                break;

            case ACCOUNT_START_SENDMONEY:

                break;

            case ACCOUNT_COMPLETE_SENDMONEY:


                break;

            case ACCOUNT_LOGIN_ALERT:
                REQ_LONG(in, "member_id", 1, -1);

                 // testing exclusion first
                 res = pgsql_query("SELECT * FROM members_settings WHERE member_id = %lu AND pref_id='S0001' AND status=100", in["member_id"].Long());
                 if (res != NULL && pgsql_num_rows(res) > 0) {
                  exclude_email = false;
                  }

                  if (!exclude_email && load_db_record(x, "SELECT *,email as email2,to_char(last_login, 'Day Mon dd, yyyy HH:MI AM') AS last_login2 FROM members WHERE id = %lu ", in["member_id"].Long())) {
                  

                    //in["server_name"] = "https://dashboard.wrenchboard.com";

                    int c = 0;

                    x["job_list_head"] = "";

                    res = pgsql_query("SELECT o.offer_code,o.*,j.title,j.description,j.timeline_days,j.price,j FROM members_jobs_offer o "
                            " LEFT JOIN members_jobs j ON j.id =o.job_id "
                            " WHERE o.public_view =1 AND o.expire> now() "
                            " AND o.status=1 ORDER BY o.id DESC LIMIT 2");

                    if (res != NULL && pgsql_num_rows(res) > 0) {
                        in["job_list_head"] = "Recently added job(s)";
                        ;
                        out["total_record"] = pgsql_num_rows(res);

                        for (int i = 0, n = pgsql_num_rows(res); i < n; i++) {
                            x["color"] = "FFFFFF";
                            if (c > 0) {
                                in["color"] = "ebfaeb";
                            }

                            c++;
                            map<const char*, const char*>f = pgsql_fetch_assoc(res, i);
                            if (f.empty()) continue;
                            CVars rec;
                            map_to_cvars(f, rec);

                            sprintf(listing_items, "<TR><td style='background-color:#%s; font-size:12px;'><a href='%s/plb/viewjob/%s'>%s</a> - %s<br><b>Duration:</b>%s Day(s)</td></TR>", in["color"].c_str(), out["server_name"].c_str(), rec["offer_code"].c_str(), rec["title"].c_str(), rec["description"].c_str(), rec["timeline_days"].c_str());
                            inv_list->LetStr("pin", listing_items);
                            inv_list->CloseElement();
                            //<hr size=1 color=#FF0000>
                            if (c > 1) {
                                c = 0;
                            }
                        }
                    }


                    vars2form(x, form);
                    form.LetStr("email", x["email2"].c_str());
                    form.Email("ACCOUNT/member_login.mailfile");
                }
                break;

            case ACCOUNT_PASSWORD_RESET:
                 
                REQ_LONG(in, "password_reset_id", 1, -1);
                if (load_db_record(x, "select p.*,m.firstname,m.lastname,m.email, "
                        " TO_CHAR(expired :: TIMESTAMP, 'Day Mon dd, yyyy HH:MI AM') AS long_expired , "
                        " TO_CHAR(created :: TIMESTAMP, 'Day Mon dd, yyyy HH:MI AM') AS long_created "
                        " FROM password_reset p "
                        " LEFT JOIN members m ON m.id =p.member_id  WHERE p.id = %lu ", in["password_reset_id"].Long())) {
                    vars2form(x, form);
                      form.LetStr("server_name",  out["server_name"].c_str());
                      //form.LetStr("server_name",  "http://localhost:9082");
                    form.Email("ACCOUNT/member_resetpass.mailfile");
                }
                break;

            case ACCOUNT_PASSWORD_COMPLT:
                REQ_LONG(in, "reset_id", 1, -1);
                if (load_db_record(x, "SELECT p.created,m.*, "
                        " TO_CHAR(expired :: TIMESTAMP, 'Day Mon dd, yyyy HH:MI AM') AS long_expired , "
                        " TO_CHAR(created :: TIMESTAMP, 'Day Mon dd, yyyy HH:MI AM') AS long_created "
                        " FROM password_reset p LEFT JOIN members m ON m.id=p.member_id WHERE p.status = 5 AND p.id = %lu ", in["reset_id"].Long())) {
                    vars2form(x, form);
                    form.Email("ACCOUNT/member_completepass.mailfile");
                }
                break;

            case ACCOUNT_CONTACT_ALERT:
                REQ_LONG(in, "contact_id", 1, -1);
                out["alertemail"] = CfgReadChar("transnotif.contact");
                //char * server_name = getenv( "SERVER_NAME" );		
                //form.LetStr( "server_name",  server_name );
                //form.LetStr( "site_name",  "WrenchBoard" );
                form.LetStr("subject", "WrenchBoard Contact Us Alert");
                if (load_db_record(x, "SELECT member_id,firstname,lastname,substring(your_message,1,100) AS your_message,loc,created,email as email2,created FROM contacts WHERE id = %lu ", in["contact_id"].Long())) {
                    vars2form(x, form);
                    form.LetStr("email", out["alertemail"].c_str());
                    form.Email("ALERT/alert_contact.mailfile");
                }
                break;

                case WRENCHBOARD_VIRTUAL_CARDADD:
                       ml["action"] = WRENCHBOARD_VIRTUAL_CARDADD;    ml["action"].set_valid( true );
                       ml["topic"] = "WRENCHBOARD_VIRTUAL_CARDADD";   ml["topic"].set_valid( true );
                       ml["offer_id"] =  in["offer_id"];              ml["offer_id"].set_valid( true );
                       ml["interest_id"] =  in["interest_id"];        ml["interest_id"].set_valid( true );
                       submit_cron_email(ml);
                break;
        }

    } catch (bad_parameter) {

    }



    return 0;
}

long job_email(long mailtype, CVars in, CVars &out) {
    logfmt(logINFO, "job_email()");
    CVars x, y, z, ml;
    C_CGI_Form form("", "");
    int c=0;
    CGIList * inv_list = new CGIList(&form, "inv_items");
    char listing_items[1024];
    const PGresult *res;

   // char * server_name; // = getenv("SERVER_NAME");
    out["server_name"] = CfgReadChar("system.server_name");
	//sprintf(server_name, "%s", out["server_name"].c_str());
    form.LetStr("server_name",  out["server_name"].c_str());
	
    form.LetStr("site_name", "WrenchBoard");
    form.LetStr("site_trade_name", "Connecting Opportunities");

    CVars yr;
    load_db_record(yr, "SELECT to_char(now(), 'yyyy') AS YYYY");
    vars2form(yr, form);

    switch (mailtype) {

        case WRENCHBOARD_JOB_REPLY_QUESTION:

            if (load_db_record(y, "SELECT ms.*,m.email,m.firstname FROM members_messages ms LEFT JOIN members m ON m.id=ms.member_id WHERE ms.id=%lu", in["reply_id"].Long())) {
                vars2form(y, form);
                 vars2form(yr, form);
                form.LetStr("email", y["email"].c_str());
                //we need previous message			
                load_db_record(x, "SELECT msg AS prev_message FROM members_messages ms LEFT JOIN members m ON m.id=ms.member_id WHERE ms.memo = '%s' AND ms.id<>%lu ORDER BY ms.id DESC LIMIT 1", in["memo"].c_str(), in["reply_id"].Long());
                vars2form(x, form);

                form.LetStr("subject", "Reply Message");
                form.Email("JOB/job_reply_message.mailfile");
            }
            break;

        case WRENCHBOARD_JOB_MRKTINT_QUEST:

            if (load_db_record(x, "SELECT o.*,to_char(o.expire, 'Day Mon dd, yyyy HH:MI AM') AS expire2,j.title AS job_title,j.description,j.timeline_days,j.price FROM members_jobs_offer o LEFT JOIN members_jobs j ON j.id =o.job_id WHERE o.id  = %lu", in["offer_id"].Long())) {
                vars2form(x, form);
                 vars2form(yr, form);
                form.LetStr("job_title", x["job_title"].c_str());
                //form.LetStr( "job_title",  "Job title"   );
                form.LetStr("subject", "Job Interest Message");

                if (load_db_record(y, "SELECT ms.*,m.email,m.firstname FROM members_messages ms LEFT JOIN members m ON m.id=ms.member_id WHERE ms.id=%lu", in["msg_id"].Long())) {
                    vars2form(y, form);
                    form.LetStr("email", y["email"].c_str());
                    form.Email("JOB/job_interest_message.mailfile");
                }
            }
            break;

        case JOBS_PAYMENT_DUE_MAIL:
            if (load_db_record(y, "SELECT email,firstname FROM members WHERE id  = %lu", in["member_id"].Long())) {
                vars2form(y, form);
                 vars2form(yr, form);
                // FOR CRON JOBS SET SERVER NAME
                form.LetStr("preview_count", in["preview_count"].c_str());
                form.LetStr("server_name", out["server_name"].c_str());
                vars2form(x, form);
                form.LetStr("subject", "Completed Task Processing Past Due");
                form.LetStr("email", y["email"].c_str());
                //form.LetStr( "email",  "ameye@chiefsoft.com"   );
                form.Email("JOB/job_due_reviewreminder.mailfile");
            }

            break;

        case JOBS_DUE_APPROACH_MAIL:

            if (load_db_record(x, " SELECT m.firstname,m.email,mj.title,c.* ,cc.description AS currency ,mj.description AS job_description , "
                                  " to_char(c.delivery_date, 'Day Mon dd, yyyy HH:MI AM') AS due_date"
                                  " FROM members_jobs_contract c "
                                  " LEFT JOIN members m ON m.id=c.client_id  "
                                  " LEFT JOIN members_jobs mj ON mj.id = c.job_id "
                                  " LEFT JOIN currency cc ON cc.country = mj.country "
                                  " WHERE c.id=%lu AND c.due_remind IS NULL", in["contract_id"].Long())) {
                // FOR CRON JOBS SET SERVER NAME
                form.LetStr("server_name", out["server_name"].c_str());
                vars2form(x, form);
                 vars2form(yr, form);
                form.LetStr("subject", "Due Date Approaching");
                form.LetStr("email", x["email"].c_str());
                //form.LetStr( "email",  "ameye@chiefsoft.com"   );
                form.Email("JOB/job_duereminder.mailfile");
            }
            break;

        case JOBS_OFFER_ACCEPT_MAIL:

            if (load_db_record(x, "SELECT o.*,to_char(o.delivery_date, 'Day Mon dd, yyyy HH:MI AM') AS delivery_date2 ,cc.description AS currency ,j.description AS job_description"
                                " FROM members_jobs_contract o "
                                " LEFT JOIN members_jobs j ON j.id =o.job_id "
                                " LEFT JOIN currency cc ON cc.country = j.country "
                                  " WHERE o.id  = %lu", in["contract_id"].Long())) {
                if (load_db_record(y, "SELECT email FROM members WHERE id  = %lu", x["client_id"].Long())) {
                    vars2form(x, form);
                     vars2form(yr, form);
                    form.LetStr("subject", "You have started working on the task - ");
                    form.LetStr("email", y["email"].c_str());
                    form.Email("JOB/job_offer_accepted_client.mailfile");
                }

                if (load_db_record(z, "SELECT email FROM members WHERE id  = %lu", x["member_id"].Long())) {
                    vars2form(x, form);
                     vars2form(yr, form);
                    form.LetStr("subject", "Your task was accepted");
                    form.LetStr("email", z["email"].c_str());  //job_offer_accepted_owner.mailfile
                    form.Email("JOB/job_offer_accepted_owner.mailfile");
                }
            }

            break;
        case JOBS_OFFER_REJECT_MAIL:

            if (load_db_record(x, "SELECT o.*,to_char(o.expire, 'Day Mon dd, yyyy HH:MI AM') AS expire2, "
                                  " j.title,j.description,j.timeline_days,j.price, m.email AS owner_email,m.firstname AS owner_name "
                                  " FROM members_jobs_offer o "
                                  " LEFT JOIN members_jobs j ON j.id =o.job_id "
                                  " LEFT JOIN members m ON m.id = o.member_id "
                                  " WHERE o.id  = %lu AND o.status = 3", in["offer_id"].Long())>0) {
                 vars2form(x, form);
                 vars2form(yr, form);
                form.LetStr("subject", "Job Offer Rejected");
               // load_db_record(y, "SELECT email FROM members WHERE id = %lu",x["member_id"].Long());
                form.LetStr("email", x["email"].c_str());
                form.Email("JOB/job_offer_rejected.mailfile");

                form.LetStr("subject", "Offer Rejected");
                form.LetStr("cleint_email", x["email"].c_str());
                form.LetStr("email", x["owner_email"].c_str());
                form.Email("JOB/job_offer_rejected_owner.mailfile");
            }

            // form.LetStr( "email",  "ses66181+rej@gmail.com"   );
            // form.Email( "JOB/job_offer_rejected.mailfile" );			
            break;

        case JOBS_OFFER_SENDTOME_MAIL:

            if (load_db_record(x, "SELECT o.*,to_char(o.expire, 'Day Mon dd, yyyy HH:MI AM') AS expire2,j.title,"
                    " j.description,j.timeline_days,j.price,o.member_id,j.title, "
					" (CASE WHEN o.email IS NULL THEN 'Public View' ELSE o.email END) AS job_email,  "
					" o.offer_code,to_char(now(), 'yyyy') AS YYYY  "
                    " FROM members_jobs_offer o "
                    " LEFT JOIN members_jobs j ON j.id =o.job_id WHERE o.offer_code  = '%s'", in["offer_code"].c_str())) {
                vars2form(x, form);
                load_db_record(y, "SELECT email,'Job by '||firstname||' @ WrenchBoard' AS ltitle,firstname,lastname FROM members WHERE id = %lu",x["member_id"].Long());
                vars2form(y, form);
                 vars2form(yr, form);
                form.LetStr("subject", y["ltitle"].c_str());
                form.LetStr("email", y["email"].c_str());
                form.Email("JOB/job_offer_sendtome.mailfile");
            }
            break;

        case JOBS_OFFER_INTEREST_MAIL:

            ml["action"] = JOBS_OFFER_INTEREST_MAIL; ml["action"].set_valid( true );
            ml["topic"] = "JOBS_OFFER_INTEREST_MAIL";  ml["topic"].set_valid( true );
            ml["offer_id"] =  in["offer_id"];  ml["offer_id"].set_valid( true );
            ml["interest_id"] =  in["interest_id"];  ml["interest_id"].set_valid( true );
            submit_cron_email(ml);


//            if (load_db_record(x, "SELECT o.*,to_char(o.expire, 'Day Mon dd, yyyy HH:MI AM') AS expire2,j.title,j.description,j.timeline_days,j.price FROM members_jobs_offer o LEFT JOIN members_jobs j ON j.id =o.job_id WHERE o.id  = %lu AND o.status = 1", in["offer_id"].Long())) {
//                vars2form(x, form);
//                if (load_db_record(y, "SELECT email,balance,firstname FROM members WHERE id = %lu", x["member_id"].Long())) {
//                    vars2form(y, form);
//                     vars2form(yr, form);
//                    form.LetStr("subject", "Job Interest Recieved");
//                    form.LetStr("email", y["email"].c_str());
//                    form.Email("JOB/job_interest_member.mailfile");
//                }
//
//                if (load_db_record(z, "SELECT mi.*,m.firstname,m.lastname,m.email from members_offer_interest mi LEFT JOIN members m ON m.id = mi.member_id WHERE mi.id = %lu", in["interest_id"].Long())) {
//                    vars2form(z, form);
//                    vars2form(yr, form);
//                    form.LetStr("subject", "Job Interest Sent");
//                    form.LetStr("email", z["email"].c_str());
//                    form.Email("JOB/job_interest_client.mailfile");
//                }
//
//            }

            break;

        case JOBS_OFFER_CANCEL_MAIL:

            if (load_db_record(x, "SELECT o.*,to_char(o.expire, 'Day Mon dd, yyyy HH:MI AM') AS expire2,j.title,j.description,"
                                  " j.description AS job_description,j.timeline_days,j.price "
                                  " FROM members_jobs_offer o "
                                  " LEFT JOIN members_jobs j ON j.id =o.job_id WHERE o.id  = %lu ", in["offer_id"].Long())) {
                vars2form(x, form);
                 vars2form(yr, form);
                form.LetStr("subject", "Job Offer Canceled");
                form.LetStr("email", x["email"].c_str());
                form.Email("JOB/job_offer_cancel.mailfile");

            }

            break;

        case JOBS_INDIVIDUAL_OFFER_MAIL:
            logfmt(logINFO, "JOBS_INDIVIDUAL_OFFER_MAIL");
            if (load_db_record(x, "SELECT o.*,to_char(o.expire, 'Day Mon dd, yyyy HH:MI AM') AS expire2,j.title,j.description, "
                                  " j.description AS job_description, j.timeline_days,j.price,cc.description AS currency  "
                                  " FROM members_jobs_offer o "
                                  " LEFT JOIN members_jobs j ON j.id =o.job_id "
                                  " LEFT JOIN currency cc ON cc.country = j.country "
                                  " WHERE o.id  = %lu", in["offer_id"].Long())) {
                vars2form(x, form);
                 vars2form(yr, form);
               // form.LetStr("subject", "New Job Offer Received");
               // form.LetStr("email", x["email"].c_str());
               // form.Email("JOB/job_offer_invidual.mailfile");

                ml["action"] = JOBS_INDIVIDUAL_OFFER_MAIL; ml["action"].set_valid( true );
                ml["topic"] = "JOBS_INDIVIDUAL_OFFER_MAIL";  ml["topic"].set_valid( true );
                ml["offer_id"] =  in["offer_id"];  ml["offer_id"].set_valid( true );
                submit_cron_email(ml);
            }
            break;

        case JOBS_GROUP_OFFER_MAIL:
            logfmt(logINFO, "JOBS_GROUP_OFFER_MAIL");
            if (load_db_record(x, "SELECT o.*,j.title,j.description,j.timeline_days,j.price FROM members_jobs_offer o LEFT JOIN members_jobs j ON j.id =o.job_id WHERE o.id  = %lu", in["offer_id"].Long())) {
                const PGresult *res = pgsql_query("SELECT email FROM members_job_groupmember WHERE group_id=%lu AND status=1", x["group_id"].Long());
                if (res != NULL && pgsql_num_rows(res) > 0) {
                    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);
                        vars2form(x, form);
                         vars2form(yr, form);
                        form.LetStr("subject", "Job Offer Received");
                        form.LetStr("email", rec["email"].c_str());
                        form.Email("JOB/job_offer_group.mailfile");
                    }
                }
            }
            break;

        case JOBS_GROUP_OFFER_PUBLIC:
            logfmt(logINFO, "JOBS_GROUP_OFFER_PUBLIC");
            if (load_db_record(x, "SELECT o.*,j.title,j.description,j.timeline_days,j.price,cc.description AS currency "
                                  " FROM members_jobs_offer o "
                                  " LEFT JOIN members_jobs j ON j.id =o.job_id "
                                  " LEFT JOIN currency cc ON cc.country = j.country "
                                  " WHERE o.id  = %lu", in["offer_id"].Long())) {
                vars2form(x, form);
                if (load_db_record(y, "SELECT email,balance,firstname FROM members WHERE id = %lu", x["member_id"].Long())) {
                    vars2form(y, form);
                    // vars2form( x, form );
//                    form.LetStr("subject", "Job Offer Posted to the Public");
//                    form.LetStr("email", y["email"].c_str());
//                    form.Email("JOB/job_offer_public.mailfile");
                    ml["action"] = JOBS_GROUP_OFFER_PUBLIC; ml["action"].set_valid( true );
                    ml["topic"] = "JOBS_GROUP_OFFER_PUBLIC";  ml["topic"].set_valid( true );
                    ml["offer_id"] =  in["offer_id"];  ml["offer_id"].set_valid( true );
                    submit_cron_email(ml);
                }
            }
            break;

        case JOBS_MESSAGE_ADDED:
            logfmt(logINFO, "JOBS_MESSAGE_ADDED");

                ml["action"] = JOBS_MESSAGE_ADDED; ml["action"].set_valid( true );
                ml["topic"] = "JOBS_MESSAGE_ADDED";  ml["topic"].set_valid( true );
                ml["contract"] =  in["contract"];  ml["contract"].set_valid( true );
                submit_cron_email(ml);


//            res = pgsql_query("SELECT m.firstname,mj.title,c.member_id,c.client_id,j.contract,j.msg_type,substring(j.message,0,550) AS message,"
//                    " to_char(j.created, 'Day Mon dd, yyyy HH:MI AM') AS added , c.id AS contract_id "
//                    " FROM jobs_contract_message j "
//                    " LEFT JOIN members_jobs_contract c ON c.contract = j.contract "
//                    " LEFT JOIN members m ON m.id=j.member_id  LEFT JOIN members_jobs mj ON mj.id = c.job_id "
//                    " WHERE j.contract='%s'  ORDER BY j.id desc LIMIT 4", in["contract"].c_str());
// CVars rec;
//            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++) {
//                    in["color"] = "FFFFFF";
//                    if (c > 0) {
//                        in["color"] = "ebfaeb";
//                    }
//
//                    c++;
//                    map<const char*, const char*>f = pgsql_fetch_assoc(res, i);
//                    if (f.empty()) continue;
//
//                    map_to_cvars(f, rec);
//
//                    sprintf(listing_items, "<TR><td style='background-color:#%s'>%s<hr size='1'></td></TR>", in["color"].c_str(), rec["message"].c_str());
//                    inv_list->LetStr("pin", listing_items);
//                    inv_list->CloseElement();
//                    //<hr size=1 color=#FF0000>
//                    if (c > 1) {
//                        c = 0;
//                    }
//                }
//
//
//                vars2form(rec, form);
//                if (load_db_record(y, "SELECT email FROM members WHERE id = %lu", rec["member_id"].Long())) {
//                    vars2form(x, form);
//                    form.LetStr("subject", "Activity Message Sent");
//                    form.LetStr("email", y["email"].c_str());
//                    form.Email("JOB/job_message_m.mailfile");
//                }
//
//                vars2form(x, form); // not sure if I have to rebind again
//                if (load_db_record(z, "SELECT email FROM members WHERE id = %lu", rec["client_id"].Long())) {
//                    vars2form(x, form);
//                    form.LetStr("subject", "Activity Message Received");
//                    form.LetStr("email", z["email"].c_str());
//                    form.Email("JOB/job_message.mailfile");
//                }
//
//
//
//            }
            
            /*
            if (load_db_record(x, "SELECT m.firstname,mj.title,c.member_id,c.client_id,j.contract,j.msg_type,substring(j.message,0,550) AS message,"
                    " to_char(j.created, 'Day Mon dd, yyyy HH:MI AM') AS added  "
                    " FROM jobs_contract_message j "
                    " LEFT JOIN members_jobs_contract c ON c.contract = j.contract "
                    " LEFT JOIN members m ON m.id=j.member_id  LEFT JOIN members_jobs mj ON mj.id = c.job_id "
                    " WHERE j.contract='%s'  ORDER BY j.id desc LIMIT 1", in["contract"].c_str())> 0) {
                
                
                vars2form(x, form);
                if (load_db_record(y, "SELECT email FROM members WHERE id = %lu", x["member_id"].Long())) {
                    vars2form(x, form);
                    form.LetStr("subject", "Activity Message Sent");
                    form.LetStr("email", y["email"].c_str());
                    form.Email("JOB/job_message_m.mailfile");
                }

                vars2form(x, form); // not sure if I have to rebind again 
                if (load_db_record(z, "SELECT email FROM members WHERE id = %lu", x["client_id"].Long())) {
                    vars2form(x, form);
                    form.LetStr("subject", "Activity Message Received");
                    form.LetStr("email", z["email"].c_str());
                    form.Email("JOB/job_message.mailfile");
                }

            }
             */
            break;

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

long sendmoney_email(long mailtype, CVars in, CVars &out) {

    logfmt(logINFO, "sendmoney_email()");
    CVars x, y, z;
    C_CGI_Form form("", "");

    form.LetStr("main_site_url",  "https://www.wrenchboard.com/");

    //char * server_name; // = getenv("SERVER_NAME");
    out["server_name"] = CfgReadChar("system.server_name");
	//sprintf(server_name, "%s", out["server_name"].c_str());
    form.LetStr("server_name",  out["server_name"].c_str());
	
    form.LetStr("site_name", "WrenchBoard");
    form.LetStr("site_trade_name", "Connecting Opportunities");

    long sendmoney_id = REQ_LONG(in, "sendmoney_id", 1, -1);
    logfmt(logINFO, "sendmoney_email() sendmoney_id = %lu", sendmoney_id);

    load_db_record(out, "SELECT mm.username,mm.email AS email,mm.firstname AS sender_firstname, m.*,m.terminatingamount AS amount,mp.confirmation,r.firstname||' '||r.lastname  AS recipient,r.account_no,b.name AS bank_name  FROM money_transfer m LEFT JOIN members_payments mp ON mp.what_sendmoney = m.id LEFT JOIN sendmoney_recipient r ON r.id = m.recipientid LEFT JOIN members mm ON mm.id=m.member_id LEFT JOIN bank_entity_codes b ON b.code = r.bank_code WHERE m.id=%lu", in["sendmoney_id"].Long());

    out["alertemail"] = CfgReadChar("transnotif.contact");

    CVars yr;
    load_db_record(yr, "SELECT to_char(now(), 'yyyy') AS YYYY");
    vars2form(yr, form);

    switch (mailtype) {
        case SM_PENDING:
            vars2form(out, form);
            form.LetStr("subject", "Account Withdraw Pending");
            form.LetStr("sendmoney_message", "Estimated delivery time is 2 to 4 Hours.");
            form.LetStr("email", out["email"].c_str());
            form.Email("SENDMONEY/sm_pending.mailfile");

            vars2form(out, form);
            form.LetStr("subject", "Account Withdraw Pending Alert");
            form.LetStr("sendmoney_message", "Estimated delivery time is 2 to 4 Hours.");
            form.LetStr("email", out["alertemail"].c_str());
            form.Email("SENDMONEY/sm_pending_alert.mailfile");

            break;
        case SM_CANCEL:
            vars2form(out, form);
            form.LetStr("email", out["email"].c_str());
            form.Email("SENDMONEY/sm_cancel.mailfile");
            break;
        case SM_FAILED:
            vars2form(out, form);
            form.LetStr("email", out["email"].c_str());
            form.Email("SENDMONEY/sm_failed.mailfile");
            break;
        case SM_COMPLETED:
            vars2form(out, form);
            form.LetStr("subject", "Account Withdraw Completed");
            form.LetStr("email", out["email"].c_str());
            form.Email("SENDMONEY/sm_completed.mailfile");

            vars2form(out, form);
            form.LetStr("subject", "Account Withdraw Completed");
            form.LetStr("email", out["alertemail"].c_str());
            form.Email("SENDMONEY/sm_completed_alert.mailfile");
            break;
    }

    return 0;
}

long project_email(long mailtype, CVars in, CVars &out) {

    long contract_id = REQ_LONG(in, "contract_id", 1, -1);
    logfmt(logINFO, "project_email() contract_id = %lu", contract_id);

    CVars x, y, z;
    C_CGI_Form form("", "");

   // char * server_name = getenv("SERVER_NAME");
	out["server_name"] = CfgReadChar("system.server_name");
    form.LetStr("server_name", out["server_name"].c_str());
    form.LetStr("site_name", "WrenchBoard");
    form.LetStr("site_trade_name", "Connecting Opportunities");


    load_db_record(out, "SELECT ms.firstname AS member_firstaname,ms.email AS member_email, "
                        "  j.*,js.title,js.description,js.price AS amount, c.description AS currency, js.banner "
                        " FROM members_jobs_contract j "
                        " LEFT JOIN members_jobs js ON js.id=j.job_id "
                        " LEFT JOIN members ms ON ms.id=j.member_id "
                        " LEFT JOIN currency c ON c.country = js.country "
                        " WHERE j.id=%lu", contract_id);

    load_db_record(out, "SELECT CASE WHEN account_type='FULL' THEN email ELSE 'support+child@wrenchboard.com' END AS client_email,"
                         " firstname AS client_firstname,account_type"
                         " FROM members WHERE id = %lu", out["client_id"].Long());
    out["alertemail"] = CfgReadChar("transnotif.contact");

    CVars yr;
    load_db_record(yr, "SELECT to_char(now(), 'yyyy') AS YYYY");
    vars2form(yr, form);

    switch (mailtype) {
        case CONTRACT_NOTIFY_COMPLETE:

            vars2form(out, form);
            form.LetStr("subject", "Task Review Requested");
            form.LetStr("email", out["member_email"].c_str());
            form.Email("PROJ/contract_notifycomplete_m.mailfile");

            vars2form(out, form);
            form.LetStr("subject", "Review Requested");
            form.LetStr("email", out["client_email"].c_str());
            form.Email("PROJ/contract_notifycomplete_c.mailfile");

            break;
        case CONTRACT_REQUEST_CANCEL:

            vars2form(out, form);
            form.LetStr("subject", "Notification of Task Cancellation Request");
            form.LetStr("email", out["member_email"].c_str());
            form.Email("PROJ/contract_requestcancel_m.mailfile");

            vars2form(out, form);
            form.LetStr("subject", "Notification of Task Cancellation Request");
            form.LetStr("email", out["client_email"].c_str());
            form.Email("PROJ/contract_requestcancel_c.mailfile");

            /*
            -rw-r--r--. 1 oameye dev 9374 May 19 20:07 contract_requestcancel_c.mailfile
            -rw-r--r--. 1 oameye dev 9374 May 19 20:07 contract_requestcancel_m.mailfile
             */

            break;
        case CONTRACT_ACCEPT_COMPLETE:

            vars2form(out, form);
            form.LetStr("subject", "Completion Approval");
            form.LetStr("email", out["member_email"].c_str());
            form.Email("PROJ/contract_acceptcomplete_m.mailfile");

            vars2form(out, form);
            form.LetStr("subject", "Completion Approved");
            form.LetStr("email", out["client_email"].c_str());
            form.Email("PROJ/contract_acceptcomplete_c.mailfile");


            /*
            -rw-r--r--. 1 oameye dev 9374 May 19 20:07 contract_acceptcomplete_c.mailfile
            -rw-r--r--. 1 oameye dev 9374 May 19 20:07 contract_acceptcomplete_m.mailfile
             */
            break;

        case CONTRACT_REQUEST_TIMELINE:

            vars2form(out, form);
            form.LetStr("subject", "Due Date Extension Requsted");
            form.LetStr("email", out["member_email"].c_str());
            form.Email("PROJ/contract_extension_request_m.mailfile");

            vars2form(out, form);
            form.LetStr("subject", "Due Date Extension Request Sent");
            form.LetStr("email", out["client_email"].c_str());
            form.Email("PROJ/contract_extension_request_c.mailfile");
            break;

        case CONTRACT_REJECT_COMPLETE:

            vars2form(out, form);
            form.LetStr("subject", "Task Completion Rejection");
            form.LetStr("email", out["member_email"].c_str());
            form.Email("PROJ/contract_rejectcomplete_m.mailfile");

            vars2form(out, form);
            form.LetStr("subject", "Your Task Completion was Rejected");
            form.LetStr("email", out["client_email"].c_str());
            form.Email("PROJ/contract_rejectcomplete_c.mailfile");

            /*
            -rw-r--r--. 1 oameye dev 9374 May 19 20:07 contract_rejectcomplete_c.mailfile
            -rw-r--r--. 1 oameye dev 9374 May 19 20:07 contract_rejectcomplete_m.mailfile
             */


            break;
    }

    return 0;
}

long getContractMemberClientEmail(long contract_id, CVars &out) {
    CVars x;
    logfmt(logINFO, "getContractMemberClientEmail()");
    if (load_db_record(x, "SELECT c.member_id,c.client_id FROM members_jobs_contract c WHERE c.id=%lu", contract_id)) {

        if (load_db_record(out, "SELECT email AS member_email FROM members WHERE id = %lu", x["member_id"].Long())) {

        }

        if (load_db_record(out, "SELECT email AS client_email FROM members WHERE id = %lu", x["client_id"].Long())) {

        }
    }

    return 0;
}

long test_email(CVars in, CVars &out) {
    CVars x,y,z;
    C_CGI_Form form("", "");

    out["server_name"] = CfgReadChar("system.server_name");
    form.LetStr("server_name", out["server_name"].c_str());
    form.LetStr("site_name", "WrenchBoard");
    form.LetStr("site_trade_name", "Connecting Opportunities");
/*
    if (load_db_record(x, "select p.*,m.firstname,m.lastname,m.email from password_reset p LEFT JOIN members m ON m.id =p.member_id  WHERE p.id = 8 ")) {
        vars2form(x, form);
    }
    form.LetStr("subject", "This is Test Email");
    form.LetStr("email", in["email"].c_str());
    form.Email("ALERT/template.mailfile");

            if (load_db_record(x, "SELECT o.*,to_char(o.expire, 'Day Mon dd, yyyy HH:MI AM') AS expire2,j.title,j.description,j.timeline_days,j.price FROM members_jobs_offer o LEFT JOIN members_jobs j ON j.id =o.job_id WHERE o.id  = %lu AND o.status >0", in["offer_id"].Long())) {
                vars2form(x, form);
                if (load_db_record(y, "SELECT email,balance,firstname FROM members WHERE id = %lu", x["member_id"].Long())) {
                    vars2form(y, form);
                    form.LetStr("subject", "Job Interest Recieved");
                    form.LetStr("email", "ameye+member@chiefsoft.com");
                    form.Email("JOB/job_interest_member.mailfile");
                }

                if (load_db_record(z, "SELECT mi.*,m.firstname,m.lastname,m.email from members_offer_interest mi LEFT JOIN members m ON m.id = mi.member_id WHERE mi.id = %lu", in["interest_id"].Long())) {
                    vars2form(z, form);
                    form.LetStr("subject", "Job Interest Sent");
                    form.LetStr("email", "ameye+client@chiefsoft.com");
                    form.Email("JOB/job_interest_client.mailfile");
                }

            }
			,to_char(now(), 'yyyy') AS YYYY
	*/		
			logfmt(logINFO, "JOBS_INDIVIDUAL_OFFER_MAIL");
            if (load_db_record(x, "SELECT o.*,to_char(o.expire, 'Day Mon dd, yyyy HH:MI AM') AS expire2,j.title,j.description,j.timeline_days,j.price,to_char(now(), 'yyyy') AS YYYY FROM members_jobs_offer o LEFT JOIN members_jobs j ON j.id =o.job_id WHERE o.id  = %lu", in["offer_id"].Long())) {
                vars2form(x, form);
                form.LetStr("subject", "Job Offer Received");
                form.LetStr("email", x["email"].c_str());
                form.Email("JOB/job_offer_invidual.mailfile");
            }
			
    return 0;
}

long LocationAccountLoginMail(CVars in) {
    REQ_LONG(in, "member_id", 1, -1);
    CVars x;
    CVars out;
    CVars ml;
    C_CGI_Form form("", "");
    form.LetStr("main_site_url",  "https://www.wrenchboard.com/");
	out["server_name"] = CfgReadChar("system.server_name");
    form.LetStr("server_name", out["server_name"].c_str());
    form.LetStr("site_name", "WrenchBoard");

    if (load_db_record(x, "SELECT * FROM members WHERE id = %lu ", in["member_id"].Long())) {
//        vars2form(x, form);
//        form.LetStr("email", x["email"].c_str());
//        form.Email("ACCOUNT/member_welcome.mailfile");
       // CVars ml;
        ml["action"] = WRENCHBOARD_ACCOUNT_LOGIN; ml["action"].set_valid( true );
        ml["topic"] = "WRENCHBOARD_ACCOUNT_LOGIN";  ml["topic"].set_valid( true );
        ml["member_id"] =  in["member_id"];  ml["member_id"].set_valid( true );
        submit_cron_email(ml);
    }
    return 0;
}

long ContactMessage(CVars in) {
    REQ_LONG(in, "contact_id", 1, -1);
    CVars x;
    CVars out;
    C_CGI_Form form("", "");
    out["alertemail"] = CfgReadChar("transnotif.contact");

	out["server_name"] = CfgReadChar("system.server_name");
    form.LetStr("server_name", out["server_name"].c_str());
    form.LetStr("site_name", "WrenchBoard");
    form.LetStr("subject", "WrenchBoard Contact Us Alert");

    if (load_db_record(x, "SELECT member_id,firstname,lastname,your_message,loc,created,email as email2 FROM contacts WHERE id = %lu ", in["contact_id"].Long())) {
        vars2form(x, form);
        form.LetStr("email", out["alertemail"].c_str());
        form.Email("ALERT/alert_contact.mailfile");
    }
    return 0;
}

long SignupPendingAlertMailfile(CVars in) {
    REQ_LONG(in, "pending_id", 1, -1);
    CVars x, ml;
    CVars out;
    C_CGI_Form form("", "");

        try{
            out["alertemail"] = CfgReadChar("transnotif.contact");

            out["server_name"] = CfgReadChar("system.server_name");
            form.LetStr("server_name", out["server_name"].c_str());
            form.LetStr("site_name", "WrenchBoard");
            form.LetStr("subject", "WrenchBoard Contact Us Alert");

            if (load_db_record(x, "SELECT *,email as email2,to_char(expire, 'Day Mon dd, yyyy HH:MI AM') AS expire,to_char(added, 'Day Mon dd, yyyy HH:MI AM') AS added FROM members_pending WHERE id = %lu ", in["pending_id"].Long())) {
//                vars2form(x, form);
//                form.LetStr("email", out["alertemail"].c_str());
//                form.Email("ALERT/alert_signup.mailfile");
                ml["action"] = WRENCHBOARD_ACCOUNT_PENDING; ml["action"].set_valid( true );
                ml["topic"] = "WRENCHBOARD_ALERT";  ml["topic"].set_valid( true );
                ml["member_id"] =  in["pending_id"];  ml["member_id"].set_valid( true );
                submit_cron_email(ml);
            }
        } catch (bad_parameter) {
            out["status"] = "ERROR";
        }

    return 0;
}

long SignupCompletedAlertMailfile(CVars in) {
    REQ_LONG(in, "member_id", 1, -1);
    CVars x, ml;
    CVars out;
    C_CGI_Form form("", "");
    out["alertemail"] = CfgReadChar("transnotif.contact");

	out["server_name"] = CfgReadChar("system.server_name");
    form.LetStr("server_name", out["server_name"].c_str());
    form.LetStr("site_name", "WrenchBoard");
    form.LetStr("subject", "WrenchBoard Contact Us Alert");

    if (load_db_record(x, "SELECT *,email as email2 FROM members WHERE id = %lu ", in["member_id"].Long())) {
//        vars2form(x, form);
//        form.LetStr("email", out["alertemail"].c_str());
//        form.Email("ALERT/alert_signupcompleted.mailfile");

        ml["action"] = WRENCHBOARD_ACCOUNT_LOGIN; ml["action"].set_valid( true );
        ml["topic"] = "WRENCHBOARD_ALERT";  ml["topic"].set_valid( true );
        ml["member_id"] =  in["member_id"];  ml["member_id"].set_valid( true );
        submit_cron_email(ml);
    }
    return 0;
}

long AlertActions(CVars in) {
    //REQ_LONG( in, "contact_id", 1, -1 );
    CVars x;
    CVars out;
    C_CGI_Form form("", "");
    out["alertemail"] = CfgReadChar("transnotif.contact");

	out["server_name"] = CfgReadChar("system.server_name");
    form.LetStr("server_name", out["server_name"].c_str());
    form.LetStr("site_name", "WrenchBoard");

    vars2form(in, form);
    form.LetStr("email", out["alertemail"].c_str());
    form.Email("ALERT/alert_general.mailfile");

    return 0;
}

long ManagerAccountLoginMail(CVars in) {
    REQ_LONG(in, "member_id", 1, -1);
    CVars x;
    CVars ml;
    CVars out;
    C_CGI_Form form("", "");
    form.LetStr("main_site_url",  "https://www.wrenchboard.com/");
	out["server_name"] = CfgReadChar("system.server_name");
    form.LetStr("server_name", out["server_name"].c_str());
    form.LetStr("site_name", "WrenchBoard");

    if (load_db_record(x, "SELECT * FROM members WHERE id = %lu ", in["member_id"].Long())) {
//        vars2form(x, form);
//        form.LetStr("email", x["email"].c_str());
//        form.Email("ACCOUNT/member_welcome.mailfile");
               // CVars ml;
        ml["action"] = WRENCHBOARD_ACCOUNT_LOGIN; ml["action"].set_valid( true );
        ml["topic"] = "WRENCHBOARD_ACCOUNT_LOGIN";  ml["topic"].set_valid( true );
        ml["member_id"] =  in["member_id"];  ml["member_id"].set_valid( true );
        submit_cron_email(ml);
    }
    return 0;
}

long AccountPendingMail(CVars in) //TESTED
{
    REQ_LONG(in, "pending_id", 1, -1);
    CVars x,ml;
    CVars out;
    C_CGI_Form form("", "");
    try{
        form.LetStr("main_site_url",  "https://www.wrenchboard.com/");
    	out["server_name"] =  CfgReadChar("system.server_name");
        form.LetStr("server_name", out["server_name"].c_str());
        form.LetStr("site_name", "WrenchBoard");
        form.LetStr("site_trade_name", "Connecting Opportunities");

        if (load_db_record(x, "SELECT *,to_char(expire, 'Day Mon dd, yyyy HH:MI AM') AS expire,to_char(now(), 'yyyy') AS YYYY FROM members_pending WHERE id = %lu ", in["pending_id"].Long())) {
            vars2form(x, form);
            form.LetStr("email", x["email"].c_str());
            if (x["signup_random"] != "" && x["signup_random"].Long() > 0  &&  in["mobile_email"].Long() == 100) {
                    ml["action"] = WRENCHBOARD_ACCOUNT_PENDING; ml["action"].set_valid( true );
                    ml["topic"] = "WRENCHBOARD_ACCOUNT_PENDING";  ml["topic"].set_valid( true );
                    ml["member_id"] =  in["pending_id"];  ml["member_id"].set_valid( true );
                    submit_cron_email(ml);
               // form.Email("ACCOUNT/member_pending_mobile.mailfile");

            } else {
                    ml["action"] = WRENCHBOARD_ACCOUNT_PENDING; ml["action"].set_valid( true );
                    ml["topic"] = "WRENCHBOARD_ACCOUNT_PENDING";  ml["topic"].set_valid( true );
                    ml["member_id"] =  in["pending_id"];  ml["member_id"].set_valid( true );
                    submit_cron_email(ml);
                //form.Email("ACCOUNT/member_pending_mobile.mailfile");
            }
        }

        in["title"] = "Account Pending Created";
        in["message"] = "Account Pending";
        in["title"].set_valid(true);
        in["message"].set_valid(true);
    } catch (bad_parameter) {
        out["status"] = "ERROR";
    }

    return 0;
}

long WelcomeAccountMail(CVars in) // TESTED
{
    REQ_LONG(in, "member_id", 1, -1);
    CVars x;
    CVars out;
    CVars ml;
    C_CGI_Form form("", "");
    form.LetStr("main_site_url",  "https://www.wrenchboard.com/");
	out["server_name"] = CfgReadChar("system.server_name");
    form.LetStr("server_name", out["server_name"].c_str());
    form.LetStr("site_name", "WrenchBoard");

    if (load_db_record(x, "SELECT *,to_char(now(), 'yyyy') AS YYYY FROM members WHERE id = %lu ", in["member_id"].Long())) {
//        vars2form(x, form);
//        form.LetStr("email", x["email"].c_str());
//        form.Email("ACCOUNT/member_welcome.mailfile");
        // CVars ml;
        ml["action"] = WRENCHBOARD_ACCOUNT_LOGIN; ml["action"].set_valid( true );
        ml["topic"] = "WRENCHBOARD_ACCOUNT_LOGIN";  ml["topic"].set_valid( true );
        ml["member_id"] =  in["member_id"];  ml["member_id"].set_valid( true );
        submit_cron_email(ml);
        }

    in["title"] = "Account Creation Completed";
    in["message"] = "Account Creation Completed";
    in["title"].set_valid(true);
    in["message"].set_valid(true);
    //AlertActions(in);
    return 0;
}

long JobAddedMail(CVars in) //TESTED
{



    REQ_LONG(in, "member_id", 1, -1);
    REQ_LONG(in, "job_id", 1, -1);
    CVars x;
    CVars out;
    C_CGI_Form form("", "");
    const PGresult *res;
    form.LetStr("main_site_url",  "https://www.wrenchboard.com/");
	out["server_name"] = CfgReadChar("system.server_name");
    form.LetStr("server_name", out["server_name"].c_str());
    form.LetStr("site_name", "WrenchBoard");

    // testing exclusion first
     res = pgsql_query("SELECT * FROM members_settings WHERE member_id = %lu AND pref_id='S0008' AND status=100", in["member_id"].Long());
     if (res != NULL && pgsql_num_rows(res) > 0) {

      }
      else{
      return 0;
      }


    if (load_db_record(x, "SELECT j.*,j.title as title2,m.email,m.firstname FROM members_jobs j LEFT JOIN members m ON m.id = j.member_id WHERE j.id = %lu AND j.member_id = %lu", in["job_id"].Long(), in["member_id"].Long())) {
        vars2form(x, form);
        form.LetStr("email", x["email"].c_str());
        form.Email("ACCOUNT/member_jobs.mailfile");
        // NOW LET US DO ALERTS

        C_CGI_Form form2("", "");
        vars2form(x, form2);
        out["alertemail"] = CfgReadChar("transnotif.contact");
        char * server_name = getenv("SERVER_NAME");
        form2.LetStr("server_name", "https://www.wrenchboard.com");
        form2.LetStr("site_name", "WrenchBoard");
        in["title"] = "Job Added Alert";
        in["message"] = "Job Added Alert";
        form2.LetStr("subject", "Job Added Alert");
        vars2form(in, form2);
        form2.LetStr("email", out["alertemail"].c_str());
        form2.Email("ALERT/alert_jobs_created.mailfile");


    }
    //AlertActions(in);

    return 0;
}

long CreateWrenchBoardGroupMail(CVars in) {
    REQ_LONG(in, "group_id", 1, -1);
    CVars x;
    CVars out;
    C_CGI_Form form("", "");
    form.LetStr("main_site_url",  "https://www.wrenchboard.com/");
	out["server_name"] = CfgReadChar("system.server_name");
    form.LetStr("server_name", out["server_name"].c_str());
    form.LetStr("site_name", "WrenchBoard");

    if (load_db_record(x, "select g.*,m.email,m.firstname,m.lastname from members_groups g LEFT JOIN members m ON m.id = g.member_id WHERE g.id = %lu ", in["group_id"].Long())) {
        vars2form(x, form);
        form.LetStr("email", x["email"].c_str());
        form.Email("GROUP/group_added.mailfile");
    }
    return 0;
}

long GroupCreateMemberMail(CVars in) {
    REQ_LONG(in, "group_id", 1, -1);
    REQ_LONG(in, "group_member_id", 1, -1);
    CVars x;
    CVars out;
    C_CGI_Form form("", "");

	out["server_name"] = CfgReadChar("system.server_name");
    form.LetStr("server_name", out["server_name"].c_str());
    form.LetStr("site_name", "WrenchBoard");

    if (load_db_record(x, "SELECT gm.*,m.*,e.email FROM group_members gm LEFT JOIN members_groups m ON m.id=gm.group_id LEFT JOIN members e ON e.id=gm.member_id WHERE gm.id = %lu", in["group_member_id"].Long())) {
        vars2form(x, form);
        form.LetStr("email", x["email"].c_str());
        form.Email("GROUP/group_member_added.mailfile");
    }
    return 0;
    return 0;
}
//==============================================================================================================

long send_email(CVars in, CVars &out) {
    logfmt(logINFO, "send_email()");
    long ret = PHP_API_BAD_PARAM;
    try {
        REQ_LONG(in, "whattodo", 1, -1);
        switch (in["whattodo"].Long()) {
            default: logfmt(logINFO, "Not implemented");
        }
    } catch (bad_parameter) {
        out["status"] = "Unknow action supplied";
    }
    logfmt(logINFO, "/send_email()");
    return ret;
}

long EmailCustBalUpdt(CVars in) {
    REQ_LONG(in, "balance_update_id", 1, -1);
    C_CGI_Form form("", "");
	CVars out;
   	out["server_name"] = CfgReadChar("system.server_name");
    form.LetStr("server_name", out["server_name"].c_str());
    CVars x;

    vars2form(x, form);
    //form.LetStr("server_name", "https://dashboard.wrenchboard.com");
    form.Email("test.mailfile");
    return 0;
}

long SendPromoEmail(CVars in) {
    long pmode = REQ_LONG(in, "pmode", 1, -1);
    CVars x;
    CVars out;
    C_CGI_Form form("", "");

    vars2form(in, form);
    form.LetStr("email", in["email"].c_str());

    switch (pmode) {
        case 1:
            form.Email("promo/promotion1.mailfile");
            break;

        case 2:
            form.Email("promo/promotion2.mailfile");
            break;

    }



    return 0;
}

long SendBalanceRequestAlert(CVars in) {
    REQ_LONG(in, "request_id", 1, -1);
    CVars x;
    CVars out;
    C_CGI_Form form("", "");
    out["topupemail"] = CfgReadChar("transnotif.topupemail");

    if (load_db_record(x, "SELECT a.*,a.amount*0.01 AS req_amount,c.*,a.ip AS ip_loc,u.name FROM customer_addbalance a LEFT JOIN customer c ON c.id=a.customer_id  LEFT JOIN bko_users u ON u.id=a.csr_id WHERE a.id = '%lu' ", in["request_id"].Long())) {

        vars2form(x, form);
        form.LetStr("email", out["topupemail"].c_str());
        form.Email("alerts/balancereq.mailfile");

    }
    return 0;
}

long SendBalanceCompleteAlert(CVars in) {
    REQ_LONG(in, "request_id", 1, -1);
    CVars x;
    CVars out;
    C_CGI_Form form("", "");
    out["topupemail"] = CfgReadChar("transnotif.topupemail");

    if (load_db_record(x, "SELECT a.*,a.amount*0.01 AS req_amount,c.*,a.ip2 AS ip_loc,u.name,a.cur_balance*0.01  AS cur2, a.fin_balance*0.01 AS fin2  FROM customer_addbalance a LEFT JOIN customer c ON c.id=a.customer_id  LEFT JOIN bko_users u ON u.id=a.csr_id WHERE a.id = '%lu' ", in["request_id"].Long())) {
        vars2form(x, form);
        form.LetStr("email", out["topupemail"].c_str());
        form.Email("alerts/balancecomplete.mailfile");

    }
    return 0;
}

long SystemStatus() {
    logfmt(logINFO, "SystemStatus()*************~************");

    C_CGI_Form form("", "");
    const char * server_name = getenv("SERVER_NAME");
    CVars x;

    vars2form(x, form);
    form.LetStr("site", server_name);

    form.LetStr("message", server_name);
    form.LetStr("email", "ses66181@gmail.com");
    // form.LetStr( "email",  "acidumirae@gmail.com" );

    form.Email("test.mailfile");
    return 0l;
}

long StartPassResetEmail(CVars in) {
    //customer_id
    // reset_id 
    C_CGI_Form form("", "");
    const char * server_name = getenv("SERVER_NAME");
    CVars out;
    CVars x;
    load_db_record(x, "SELECT * FROM customer WHERE id = %lu", in["customer_id"].Long());
    vars2form(x, form);


   	out["server_name"] = CfgReadChar("system.server_name");
   //	out["server_name"] = "http://localhost:9082";
    form.LetStr("server_name", out["server_name"].c_str());
	
    /*
    CREATE TABLE lostpass (
     id serial NOT NULL,
     customer_id INT REFERENCES customer(id),
     added TIMESTAMP DEFAULT NOW(),
     updated TIMESTAMP DEFAULT NOW(),
     loc INET,
     reset_link VARCHAR(200) NOT NULL,
     expire TIMESTAMP ,
     status integer DEFAULT 1  
    );
     */
    load_db_record(out, "SELECT added AS lost_added,* FROM lostpass WHERE id = %lu", in["reset_id"].Long());
    vars2form(out, form);


    form.LetStr("email", x["email"].c_str());
    form.Email("start_losspass.mailfile"); //customer notification


    return 0;
    //start_losspass.mailfile
}

long CompletePassResetEmail(CVars in) {
    //customer_id
    // reset_id 
    C_CGI_Form form("", "");
    const char * server_name = getenv("SERVER_NAME");
    CVars out;
    CVars x;
    load_db_record(x, "SELECT * FROM members WHERE id = %lu", in["member_id"].Long());
    vars2form(x, form);
    out["server_name"] = CfgReadChar("system.server_name");
    form.LetStr("server_name", out["server_name"].c_str());
    form.LetStr("email", x["email"].c_str());
    form.Email("complete_losspass.mailfile"); //customer notification
    return 0;
    //start_losspass.mailfile
}

long CustomerAirSalePayment(CVars in) {
    /*
    payquic_test=> select t.*,c.* from trans_notification t LEFT JOIN customer c ON c.id = t.customer_id  limit 1;
     id | customer_id |  orderid   | description | amount | txnref | payref | retref | status |           added            | resp | recipient_no | completed | appramt | rspcode | id |      username      | firstname | lastname |       email        |               pass
                   | status |           added            | balance 
    ----+-------------+------------+-------------+--------+--------+--------+--------+--------+----------------------------+------+--------------+-----------+---------+---------+----+--------------------+-----------+----------+--------------------+-------------------
    ---------------+--------+----------------------------+---------
      2 |           1 | 1452581056 | 08174596143 |   1000 |        |        |        |      1 | 2014-09-15 21:00:39.921535 |      | 08174596144  |           |       0 |         |  1 | ses66181@gmail.com | Olu       | Amey     | ses66181@gmail.com | d0fbea2563b377ea70
    74bced45c88dcb |      1 | 2014-07-09 13:52:02.478932 |  189700
    (1 row)

     */
    CVars out;
    out["topupemail"] = CfgReadChar("transnotif.topupemail");

    logfmt(logINFO, "SystemStatus()*************~************");

    C_CGI_Form form("", "");
    const char * server_name = getenv("SERVER_NAME");
    CVars x, y;
    load_db_record(x, "select t.*,c.*,c.loc AS loc_c,c.balance*0.01 AS balance2,t.amount AS amount2,c.email AS email2,t.added AS trans_date from trans_notification t LEFT JOIN customer c ON c.id = t.customer_id WHERE t.orderid='%s'", in["orderid"].c_str());
    vars2form(x, form);

    load_db_record(y, "SELECT country_code,country_name,continent_code,continent_name FROM ipligence2 WHERE ip_from <= ip2int('%s') AND ip_to>=ip2int('%s') LIMIT 1", x["loc_c"].c_str(), x["loc_c"].c_str());
    /*
    country_code | country_name  | continent_code | continent_name
    --------------+---------------+----------------+----------------
    US           | UNITED STATES | NA             | NORTH AMERICA
     */
    vars2form(y, form);


    if (in["pmode"].Long() == PAY_MODE_BALANCE) // paying with balance
    {
        form.LetStr("paymode", "Payment with balance");
    } else {
        form.LetStr("paymode", "Payment with card");
    }

    form.LetStr("server_name", "https://www.wrenchboard.com");
    form.LetStr("site", server_name);
    form.LetStr("email", x["email2"].c_str());
    form.Email("topup_payment.mailfile"); //customer notification



    form.LetStr("email", out["topupemail"].c_str());
    form.Email("topup_payment_alert.mailfile"); //customer notification


    return 0l;


}

long CustomerAirBonus(CVars in) {

    CVars out;
    out["topupemail"] = CfgReadChar("transnotif.topupemail");

    logfmt(logINFO, "SystemStatus()*************~************");

    C_CGI_Form form("", "");
    const char * server_name = getenv("SERVER_NAME");
    CVars x;
    load_db_record(x, "select t.*,c.*,c.balance*0.01 AS balance2,t.amount AS amount2,c.email AS email2,t.added AS trans_date from trans_notification t LEFT JOIN customer c ON c.id = t.customer_id WHERE t.orderid='%s'", in["orderid"].c_str());
    vars2form(x, form);


    if (in["pmode"].Long() == PAY_MODE_BALANCE) // paying with balance
    {
        form.LetStr("paymode", "Payment with balance");
    } else {
        form.LetStr("paymode", "Payment with card");
    }


    form.LetStr("site", server_name);
    form.LetStr("email", x["email2"].c_str());
    form.Email("topup_bonus_completed.mailfile"); //customer notification
    return 0l;


}

long CustomerAirSale(CVars in) {
    /*
    payquic_test=> select t.*,c.* from trans_notification t LEFT JOIN customer c ON c.id = t.customer_id  limit 1;
     id | customer_id |  orderid   | description | amount | txnref | payref | retref | status |           added            | resp | recipient_no | completed | appramt | rspcode | id |      username      | firstname | lastname |       email        |               pass
                   | status |           added            | balance 
    ----+-------------+------------+-------------+--------+--------+--------+--------+--------+----------------------------+------+--------------+-----------+---------+---------+----+--------------------+-----------+----------+--------------------+-------------------
    ---------------+--------+----------------------------+---------
      2 |           1 | 1452581056 | 08174596143 |   1000 |        |        |        |      1 | 2014-09-15 21:00:39.921535 |      | 08174596144  |           |       0 |         |  1 | ses66181@gmail.com | Olu       | Amey     | ses66181@gmail.com | d0fbea2563b377ea70
    74bced45c88dcb |      1 | 2014-07-09 13:52:02.478932 |  189700
    (1 row)

     */
    CVars out;
    out["topupemail"] = CfgReadChar("transnotif.topupemail");

    logfmt(logINFO, "SystemStatus()*************~************");

    C_CGI_Form form("", "");
    const char * server_name = getenv("SERVER_NAME");
    CVars x, y;
    load_db_record(x, "select t.*,c.*,c.loc AS loc_c,c.balance*0.01 AS balance2,t.amount AS amount2,c.email AS email2,t.added AS trans_date from trans_notification t LEFT JOIN customer c ON c.id = t.customer_id WHERE t.orderid='%s'", in["orderid"].c_str());
    vars2form(x, form);

    load_db_record(y, "SELECT country_code,country_name,continent_code,continent_name FROM ipligence2 WHERE ip_from <= ip2int('%s') AND ip_to>=ip2int('%s') LIMIT 1", x["loc_c"].c_str(), x["loc_c"].c_str());
    /*
    country_code | country_name  | continent_code | continent_name
    --------------+---------------+----------------+----------------
    US           | UNITED STATES | NA             | NORTH AMERICA
     */
    vars2form(y, form);


    if (in["pmode"].Long() == PAY_MODE_BALANCE) // paying with balance
    {
        form.LetStr("paymode", "Payment with balance");
    } else {
        form.LetStr("paymode", "Payment with card");
    }


    form.LetStr("site", server_name);
    form.LetStr("email", x["email2"].c_str());
    form.Email("topup_completed.mailfile"); //customer notification
    return 0l;


}

long VirtualAirSaleCustomer(CVars in) {

    CVars out;
    out["topupemail"] = CfgReadChar("transnotif.topupemail");

    logfmt(logINFO, "SystemStatus()*************~************");

    C_CGI_Form form("", "");
    const char * server_name = getenv("SERVER_NAME");
    CVars x, y;
    load_db_record(x, "select t.*,c.*,c.loc AS loc_c,c.balance*0.01 AS balance2,t.amount AS amount2,c.email AS email2,t.added AS trans_date from trans_notification t LEFT JOIN customer c ON c.id = t.customer_id WHERE t.orderid='%s'", in["orderid"].c_str());
    vars2form(x, form);

    load_db_record(y, "SELECT country_code,country_name,continent_code,continent_name FROM ipligence2 WHERE ip_from <= ip2int('%s') AND ip_to>=ip2int('%s') LIMIT 1", x["loc_c"].c_str(), x["loc_c"].c_str());
    /*
    country_code | country_name  | continent_code | continent_name
    --------------+---------------+----------------+----------------
    US           | UNITED STATES | NA             | NORTH AMERICA
     */
    vars2form(y, form);

    CVars z;
    load_db_record(z, "SELECT t.paymentcode,i.responsecode,i.transactionref FROM interswitch_bill_payment_advice t LEFT JOIN interswitch_transaction i ON i.detail_id=t.id WHERE t.order_id ='%s'", x["orderid"].c_str());
    vars2form(z, form);

    if (in["pmode"].Long() == PAY_MODE_BALANCE) // paying with balance
    {
        form.LetStr("paymode", "Payment with balance");
    } else {
        form.LetStr("paymode", "Payment with card");
    }


    form.LetStr("site", server_name);

    form.LetStr("message", server_name);
    form.LetStr("email", out["topupemail"].c_str());
    form.Email("virtualtopup.mailfile"); // this is alert
    return 0l;


}

void CustomerBalanceEmail(CVars in) {
    REQ_STRING(in, "orderid", 1, 50, "(.*)");
    CVars x;
    C_CGI_Form form("", "");
    if (load_db_record(x, "select c.*,t.*,t.added AS balance_date,appramt*0.01 AS appramt2,t.added AS trans_date,c.balance*0.01 AS balance2 from trans_balance_topup t LEFT JOIN customer c ON c.id =  t.customer_id where t.orderid = '%s' AND completed IS NOT NULL", in["orderid"].c_str())) {
        vars2form(x, form);
        form.Email("balance_updated.mailfile");
    }


}

long CustomerBalanceBonusEmail(CVars in) {
    //REQ_STRING( in, "orderid", 1, 50, "(.*)");
    REQ_LONG(in, "customer_id", 1, -1);
    CVars x;
    C_CGI_Form form("", "");
    if (load_db_record(x, "select * FROM customer WHERE id =   %lu  ", in["customer_id"].Long())) {
        vars2form(x, form);
        form.Email("bonus_balance.mailfile");
    }

    return 0;
}

void PaymentAlert(CVars in) {

}

void BalanceUpdateAlert(CVars in) {
    REQ_STRING(in, "orderid", 1, 50, "(.*)");
    CVars x;
    CVars out;
    C_CGI_Form form("", "");
    out["topupemail"] = CfgReadChar("transnotif.topupemail");

    if (load_db_record(x, "select c.*,t.*,t.added AS balance_date,appramt*0.01 AS appramt2 ,c.balance*0.01 AS balance2 from trans_balance_topup t LEFT JOIN customer c ON c.id =  t.customer_id where t.orderid = '%s' AND completed IS NOT NULL", in["orderid"].c_str())) {

        vars2form(x, form);


        form.LetStr("email", out["topupemail"].c_str());
        form.Email("alert_balance_updated.mailfile");

    }



}

void CustomerEmailWelcome(CVars in) {
    long customer_id = in["user_id"].Long();
    C_CGI_Form form("", "");
    const char * server_name = getenv("SERVER_NAME");
    CVars x;
    load_db_record(x, "select *,email as email2 from customer   WHERE id =%lu ", customer_id);
    vars2form(x, form);
    form.Email("welcome.mailfile");
}

/*****************************************************************************/
long VirtualAirSaleAlert(CVars in) {
    /*
    payquic_test=> select t.*,c.* from trans_notification t LEFT JOIN customer c ON c.id = t.customer_id  limit 1;
     id | customer_id |  orderid   | description | amount | txnref | payref | retref | status |           added            | resp | recipient_no | completed | appramt | rspcode | id |      username      | firstname | lastname |       email        |               pass
                   | status |           added            | balance 
    ----+-------------+------------+-------------+--------+--------+--------+--------+--------+----------------------------+------+--------------+-----------+---------+---------+----+--------------------+-----------+----------+--------------------+-------------------
    ---------------+--------+----------------------------+---------
      2 |           1 | 1452581056 | 08174596143 |   1000 |        |        |        |      1 | 2014-09-15 21:00:39.921535 |      | 08174596144  |           |       0 |         |  1 | ses66181@gmail.com | Olu       | Amey     | ses66181@gmail.com | d0fbea2563b377ea70
    74bced45c88dcb |      1 | 2014-07-09 13:52:02.478932 |  189700
    (1 row)

     */
    CVars out;
    out["topupemail"] = CfgReadChar("transnotif.topupemail");

    logfmt(logINFO, "SystemStatus()*************~************");

    C_CGI_Form form("", "");
    const char * server_name = getenv("SERVER_NAME");
    CVars x, y;
    load_db_record(x, "select t.*,c.*,c.loc as loc_c,c.balance*0.01 AS balance2,t.amount AS amount2,c.email AS email2 from trans_notification t LEFT JOIN customer c ON c.id = t.customer_id WHERE t.orderid='%s'", in["orderid"].c_str());
    vars2form(x, form);


    load_db_record(y, "SELECT country_code,country_name,continent_code,continent_name FROM ipligence2 WHERE ip_from <= ip2int('%s') AND ip_to>=ip2int('%s') LIMIT 1", x["loc_c"].c_str(), x["loc_c"].c_str());
    /*
    country_code | country_name  | continent_code | continent_name
    --------------+---------------+----------------+----------------
    US           | UNITED STATES | NA             | NORTH AMERICA
     */
    vars2form(y, form);

    CVars z;
    load_db_record(z, "SELECT t.paymentcode,i.responsecode,i.transactionref FROM interswitch_bill_payment_advice t LEFT JOIN interswitch_transaction i ON i.detail_id=t.id WHERE t.order_id ='%s'", x["orderid"].c_str());
    vars2form(z, form);

    if (in["pmode"].Long() == PAY_MODE_BALANCE) // paying with balance
    {
        form.LetStr("paymode", "Payment with balance");
    } else if (in["pmode"].Long() == PAY_MODE_BONUS) // paying bonus
    {
        form.LetStr("paymode", "Bonus Payment");
    } else {
        form.LetStr("paymode", "Payment with card");
    }


    form.LetStr("site", server_name);

    form.LetStr("message", server_name);
    //form.LetStr( "email",  "ses66181@gmail.com,oladeji@gmail.com" );
    form.LetStr("email", out["topupemail"].c_str());

    // form.LetStr( "email",  "acidumirae@gmail.com" );

    form.Email("virtualtopup.mailfile");
    return 0l;
}

/*****************************************************************************/

void SendAccountCreateAlert(long customer_id) {

    CVars out;
    out["topupemail"] = CfgReadChar("transnotif.topupemail");

    logfmt(logINFO, "SystemStatus()*************~************");

    C_CGI_Form form("", "");
    const char * server_name = getenv("SERVER_NAME");
    CVars x, y;
    load_db_record(x, "SELECT *,email as email2,balance*0.01 AS balance2,dollar_balance*0.01 AS dollar_balance2 from customer   WHERE id =%lu ", customer_id);
    vars2form(x, form);

    load_db_record(y, "SELECT country_code,country_name,continent_code,continent_name FROM ipligence2 WHERE ip_from <= ip2int('%s') AND ip_to>=ip2int('%s') LIMIT 1", x["loc"].c_str(), x["loc"].c_str());
    /*
    country_code | country_name  | continent_code | continent_name
   --------------+---------------+----------------+----------------
    US           | UNITED STATES | NA             | NORTH AMERICA
     */
    vars2form(y, form);
    form.LetStr("site", server_name);
    form.LetStr("message", server_name);
    form.LetStr("email", out["topupemail"].c_str());

    // form.LetStr( "email",  "acidumirae@gmail.com" );

    form.Email("alert_accountcreated.mailfile");
    //alert_accountcreated.mailfile
}

/*****************************************************************************/
void vars2form(CVars &v, C_CGI_Form &form) {
    CVars::const_iterator i;
    for (i = v.begin(); i != v.end(); i++) {
        char name[30];
        strsafecpy(name, i->first.c_str(), sizeof (name));
        // &fee, tax, total
        if (strcasecmp(name, "tax") == 0 ||
                strcasecmp(name, "total") == 0 ||
                strcasecmp(name, "price") == 0 ||
                strcasecmp(name, "amount") == 0 ||
                strcasecmp(name, "shipping") == 0 ||
                strcasecmp(name, "subtotal") == 0 ||
                (strlen(name) >= 3 && strcasecmp(&name[strlen(name) - 3], "fee") == 0)) {
            form.LetStrf(name, "%.2f", i->second.Long() / 100.0);
        } else {
            form.LetStr(i->first.c_str(), i->second.c_str());
        }
    }
}
/*****************************************************************************/
/*
vi:ts=2
 */

