#include "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 CronWelcomeAccountMail(CVars in);
long CronAccountPendingMail(CVars in) ;
long CronJobEmail(long mailtype, CVars in, CVars &out);
long CronAccountMail(long mailtype, CVars in);
/*

CREATE TABLE email_message(
		id SERIAL,
		uid uuid DEFAULT  uuid_generate_v4(),
		topic  VARCHAR(150)  NOT NULL,
		action INT DEFAULT 0,
		member_id INT DEFAULT 0,
		job_id INT DEFAULT 0,
		offer_id INT DEFAULT 0,
		contract_id INT DEFAULT 0,
		status INT DEFAULT 1,
		added timestamp without time zone DEFAULT now(),
		completed timestamp
	);
 ALTER TABLE ONLY email_message
    ADD CONSTRAINT email_message_id_key UNIQUE (id);
    */

long submit_cron_email(CVars in){
  return insert_db_record( DBS_VALID, "email_message", "email_message_id_seq", in );
}

long CronSendMail(CVars in, CVars &out){
  logfmt(logINFO, " ***** CALL long CronSendMail(CVars in, CVars &out)");



char vname[30];
long ret = PHP_API_BAD_PARAM;

    try {
            out["total_record"] = "0";
            const PGresult *res;
            res = pgsql_query("SELECT *, member_id AS pending_id  FROM email_message WHERE topic ='WRENCHBOARD_ACCOUNT_PENDING' AND status = 1 ORDER BY id ASC LIMIT 20");

            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);
                    pgsql_query("UPDATE email_message SET status = 2 WHERE id = %lu ", rec["id"].Long()); // move the status so no retry
                    CronAccountPendingMail(rec); // send the cron email
                    pgsql_query("UPDATE email_message SET status = 5, completed = now() WHERE id = %lu ", rec["id"].Long()); // move the status so no retry
                }
            }
            ret = PHP_API_OK;
            out["status"] = "OK";
        } catch (bad_parameter) {
            logfmt(logINFO, "ERROR CALL long WRENCHBOARD_ACCOUNT_LOGIN(CVars in, CVars &out)");
        }


try {
        out["total_record"] = "0";
        const PGresult *res;
        res = pgsql_query("SELECT * FROM email_message WHERE topic ='WRENCHBOARD_ACCOUNT_LOGIN' AND status = 1 ORDER BY id ASC LIMIT 20");

        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);
                pgsql_query("UPDATE email_message SET status = 2 WHERE id = %lu ", rec["id"].Long()); // move the status so no retry
                CronWelcomeAccountMail(rec); // send the cron email
                pgsql_query("UPDATE email_message SET status = 5, completed = now() WHERE id = %lu ", rec["id"].Long()); // move the status so no retry
            }
        }
        ret = PHP_API_OK;
        out["status"] = "OK";
    } catch (bad_parameter) {
        logfmt(logINFO, "ERROR CALL long WRENCHBOARD_ACCOUNT_LOGIN(CVars in, CVars &out)");
    }


try {
        out["total_record"] = "0";
        const PGresult *res;
        res = pgsql_query("SELECT * FROM email_message "
                          " WHERE topic IN ('JOBS_INDIVIDUAL_OFFER_MAIL', 'JOBS_OFFER_INTEREST_MAIL', 'JOBS_GROUP_OFFER_PUBLIC', 'JOBS_MESSAGE_ADDED') "
                          " AND status = 1 ORDER BY id ASC LIMIT 20");

        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);
                pgsql_query("UPDATE email_message SET status = 2 WHERE id = %lu ", rec["id"].Long()); // move the status so no retry
                CronJobEmail(rec["action"].Long(), rec, out); // send the cron email
                pgsql_query("UPDATE email_message SET status = 5, completed = now() WHERE id = %lu ", rec["id"].Long()); // move the status so no retry
            }
        }
        ret = PHP_API_OK;
        out["status"] = "OK";
    } catch (bad_parameter) {
        logfmt(logINFO, "ERROR CALL long WRENCHBOARD_ACCOUNT_LOGIN(CVars in, CVars &out)");
    }

try {
        out["total_record"] = "0";
        const PGresult *res;
        res = pgsql_query("SELECT * FROM email_message WHERE topic IN ('ACCOUNT_SEND_REFEREMAIL' ) AND status = 1 ORDER BY id ASC LIMIT 20");

        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);
                pgsql_query("UPDATE email_message SET status = 2 WHERE id = %lu ", rec["id"].Long()); // move the status so no retry
                CronAccountMail(rec["action"].Long(), rec); // send the cron email
                pgsql_query("UPDATE email_message SET status = 5, completed = now() WHERE id = %lu ", rec["id"].Long()); // move the status so no retry
            }
        }
        ret = PHP_API_OK;
        out["status"] = "OK";
    } catch (bad_parameter) {
        logfmt(logINFO, "ERROR CALL long CronAccountMail(CVars in,)");
    }



  return 0;
}

long CronAccountPendingMail(CVars in) //TESTED
{
    REQ_LONG(in, "pending_id", 1, -1);
    CVars x;
    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) {
                form.Email("ACCOUNT/member_pending_mobile.mailfile");

            } else {
                form.Email("ACCOUNT/member_pending_mobile.mailfile");
            }
        }
    } catch (bad_parameter) {
        out["status"] = "ERROR";
    }
    return 0;
}
long CronWelcomeAccountMail(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");
        }
    return 0;
}
long CronJobEmail(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 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");
           }
        break;

        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:
            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_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");
                }
            }
            break;

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

            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  "
                    " 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, "/CronJobEmail()");
    return 0;
}

long CronAccountMail(long mailtype, CVars in){
    logfmt(logINFO, "CronAccountMail()");
    CVars out, 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 ACCOUNT_SEND_REFEREMAIL:
                REQ_LONG(in, "refer_id", 1, -1);
                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;
            }

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