/*
General Header
ChiefSoft Aug 2017
 */
#include "clog.h"
#include "cgi.h"
#include "input.h"
#include "jubabox_api.h"
#include "safestring.h"
#include <string>
#include "pgsql.h"
#include "pgsql_wrapper.h"
#include "cfg.h"
#include <curl/curl.h>
/*
Other Headers
 */
#include "medTEmails.h"
//#include "function_invoice.h"


void vars2form(CVars &v, C_CGI_Form &form);
void commonItems(C_CGI_Form &form);
extern int mailsend(CVars in, CVars &out);
extern long getMemberInvoiceID( long rid );
/*
long getMemberInvoiceID( long rid ){
    
    return 0;
}
*/
long member_email_calls(long action, CVars in, CVars &out) {
    logfmt(logINFO, "member_email_calls()");
    out["result"] = "ECHO BACKEND";

    CVars x, y, z, x1, x2;
    long ret = 0;
    const char * loc = getenv("REMOTE_ADDR");
    C_CGI_Form form("", "");
    // form.LetStr("subject", "KleenApp Email Test");
    form.LetStr("site_name", "KleenApp");
    form.LetStr("contactus", "https://www.kleenapp.co/");

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

    switch (action) {

        case MEDTRANS_USER_NEWLUNDRYPICK:


            break;

        case JUBABOX_BKO_ADDCARD:
             logfmt(logINFO, "SEND ADD CARD EMAIL *****() %lu", in["card_id"].Long());
              if (load_db_record(x, "SELECT c.description,c.digits,m.*,m.email AS member_email FROM members m LEFT JOIN creditcard c ON c.member_id=m.id  WHERE c.id = %lu", in["card_id"].Long()))
              {
                   vars2form(x, form);
                    form.LetStr("subject", "New Card Added");
                    form.LetStr("email", x["member_email"].c_str());
                    form.Email("USERS/member_card_added.mailfile");
                   
              }
             
            break;
            
        case JUBABOX_USER_CONFIRMPICKUP:
            if (load_db_record(x, "SELECT m.id AS member_id, a.agent_name,s.payment_id,"
                    " TO_CHAR(s.service_date :: TIMESTAMP, 'Day Mon dd, yyyy HH:MI AM') AS long_date,"
                    " a.street AS to_street,a.city AS to_city,a.state AS to_state,a.zipcode AS to_zipcode,a.phone AS to_phone,"
                    " m.firstname,m.lastname,m.email AS member_email,p.amount,p.confirmation "
                    " FROM members_service_request s "
                    " LEFT JOIN agents a ON  a.id=s.agent_id "
                    " LEFT JOIN payment p ON p.id=s.payment_id "
                    " LEFT JOIN members m ON m.id=s.member_id "
                    " WHERE s.id=%lu", in["service_id"].Long()) > 0) {
                vars2form(x, form);

                load_db_record(y, "SELECT  street1 AS from_street,  street2 AS from_street2, city AS from_city,  zipcode AS from_zipcode , state AS from_state, country AS from_country "
                        "FROM members_profile WHERE member_id =%lu", x["member_id"].Long());
                vars2form(y, form);

                res = pgsql_query("SELECT *,total*0.01 AS line_total FROM members_service_detail WHERE service_id = %lu AND quantity > 0 ORDER BY id ASC", in["service_id"].Long());

                /*
                 kleen=> SELECT * FROM members_service_detail;
 id  | member_id | service_id | code |    description    | price | quantity | total |             added             
-----+-----------+------------+------+-------------------+-------+----------+-------+-------------------------------
   1 |        23 |        127 | S02  | Shirt (Dry Clean) |   400 |        3 |  1200 | 2018-07-19 10:28:35.543359-04
   2 |        23 |        127 | S05  | Pants             |   400 |        3 |  1200 | 2018-07-19 10:28:35.544754-04
   3 |        23 |        127 | S08  | Skirt             |   500 |        1 |   500 | 2018-07-19 10:28:35.545641-04
   4 |        23 |        128 | S01  | Shirt (Laundry)   |   160 |        2 |   320 | 2018-07-19 10:42:26.895184-04
   5 |        23 |        128 | S02  | Shirt (Dry Clean) |   400 |        3 |  1200 | 2018-07-19 10:42:26.89645-04
   6 |        23 |        128 | S05  | Pants             |   400 |        3 |  1200 | 2018-07-19 10:42:26.89732-04

                 */
                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);

                        sprintf(listing_items, "<TR><td >*</td><td >%s</td><td >%s</td><td style='text-align:right;'>$%s</td></TR>", rec["description"].c_str(), rec["quantity"].c_str() , rec["line_total"].c_str());
                        inv_list->LetStr("pin", listing_items);
                        inv_list->CloseElement();
                    }
                } 
                         
                         
                if (x["member_id"].Long() > 0 && x["payment_id"].Long() > 0 ) {
                    logfmt(logINFO, "GOOD STSRT ~*******************************************************()");
                    vars2form(x, form); // bind again  - somehow this email is not coming out 
                    form.LetStr("subject", "DryClean Pickup Confirmation");
                    form.LetStr("email", x["member_email"].c_str());
                    form.Email("MEMBERS/laundry_pic_confirmed.mailfile");
                    logfmt(logINFO, "GOOD END ~*******************************************************()");

                } else {
                    form.LetStr("subject", "Failed Laundry Pickup Confirmation");
                    form.LetStr("email", x["member_email"].c_str());
                    form.Email("MEMBERS/laundry_pickup_confirmed_fail.mailfile");
                }
            }


            break;
            
            
            
        case MEDTRANS_USER_LOGIN:
            if (load_db_record(x, "SELECT *,email as email2,now() AS last_login2 FROM members WHERE id = %lu ", in["member_id"].Long())) {
                vars2form(x, form);
                form.LetStr("subject", "KleenApp Account Access");
                form.LetStr("email", x["email2"].c_str());
                form.Email("USERS/user_login.mailfile");
            }
            break;

        case MEDTRANS_USER_CREATE:
        case JUBABOX_BKO_MEMBERADD:
            if (load_db_record(x, "SELECT *,email as email2,now() AS last_login2 FROM members WHERE id = %lu ", in["member_id"].Long())) {
                vars2form(x, form);
                form.LetStr("subject", "Welcome to KleenApp ");
                form.LetStr("email", x["email2"].c_str());
                form.Email("USERS/user_welcome.mailfile");
                
                 alert_email_calls(MEDTRANS_USER_CREATE, in, out);
                 
            }

            break;

        case MEDTRANS_USER_PROFILE:
            //  email_test(in, out);
            if (load_db_record(x, "SELECT m.*,mp.*,m.email AS email2 FROM members m LEFT JOIN members_profile mp ON m.id=mp.member_id WHERE m.id = %lu ", in["member_id"].Long())) {
                vars2form(x, form);
                form.LetStr("subject", "Profile Updated ");
                form.LetStr("email", x["email2"].c_str());
                form.Email("USERS/profile_update.mailfile");
            }
            break;

 
    }
    logfmt(logINFO, "/member_email_calls()");
    return ret;
}
////TO_CHAR(r.service_date :: TIMESTAMP, 'Day Mon dd, yyyy HH:MI AM') AS long_date 
long agent_email_calls(long action, CVars in, CVars &out) {

    logfmt(logINFO, "agent_email_calls()");
    out["result"] = "ECHO BACKEND";

    CVars x, y, z, x1, x2, x3;
    long ret = 0;
      char * server_name = getenv("SERVER_NAME");
    const char * loc = getenv("REMOTE_ADDR");
    C_CGI_Form form("", "");
    // form.LetStr("subject", "KleenApp Email Test");
 char vname[100];

    form.LetStr("site_name", "KleenApp");
    form.LetStr("agent_site", "https://agent.medtransgo.com/");
    logfmt(logINFO, "@@@@@@->AMEYE-1)");

    switch (action) {


            
            
   
            

        case MEDTRANS_TRANSP_SET_TRANSSTATUS:

            if (load_db_record(x, "SELECT r.*,l.language,a.agent_id, a.driver,"
                    " TO_CHAR(r.service_date :: TIMESTAMP, 'Day Mon dd, yyyy HH:MI AM') AS long_date "
                    " FROM members_service_request r LEFT JOIN transport_assignment a ON a.id=r.transp_assign"
                    " LEFT JOIN languages l ON l.code =  r.lang_code  "
                    " WHERE r.id = %lu ", in["transport_id"].Long())) {
                vars2form(x, form);
                load_db_record(y, "SELECT email AS req_email,firstname AS req_firstname,lastname AS req_lastname FROM members WHERE id  = %lu ", x["member_id"].Long());
                vars2form(y, form);

                if (x["driver"] != "" && x["driver"].Long() > 0) {
                    //
                    load_db_record(z, "SELECT firstname AS driver_firstname,lastname AS driver_lastname,email AS driver_email FROM transport_drivers WHERE id  = %lu ", x["driver"].Long());
                    vars2form(z, form);
                }
                
            }
                        
                        
            if (in["mode"].Long() == MODE_CONFIRM_ASSIGNMENT) {
                logfmt(logINFO, "Ready to Send Confirm Email()");
            }

            if (in["mode"].Long() == MODE_ACTIVATE_ASSIGNMENT) {
                logfmt(logINFO, "Ready to Send Driver Selected Email()");
                form.LetStr("email", z["driver_email"].c_str());
                form.Email("AGENTS/transport_assign_driver.mailfile"); // email to driver to know of assignment 
            }
            break;

        case MEDTRANS_PROVIDER_SETSTATUS:
/*
            if (load_db_record(x, "SELECT r.*,l.language,a.agent_id, a.driver,"
                    " TO_CHAR(r.service_date :: TIMESTAMP, 'Day Mon dd, yyyy HH:MI AM') AS long_date "
                    " FROM members_service_request r LEFT JOIN transport_assignment a ON a.id=r.transp_assign"
                    " LEFT JOIN languages l ON l.code =  r.lang_code  "
                    " WHERE r.id = %lu ", in["transport_id"].Long())) {
                vars2form(x, form);
                load_db_record(y, "SELECT email AS req_email,firstname AS req_firstname,lastname AS req_lastname FROM members WHERE id  = %lu ", x["member_id"].Long());
                vars2form(y, form);

                if (x["driver"] != "" && x["driver"].Long() > 0) {
                    //
                     load_db_record(z, "SELECT d.firstname AS driver_firstname,d.lastname AS driver_lastname,d.email AS driver_email, a.agent_name,a.email AS agent_email FROM transport_drivers d LEFT JOIN agents a ON a.id=d.agent_id WHERE d.id  = %lu ", x["driver"].Long());
                    vars2form(z, form);
                }
            }

 //pickup_assigned.mailfile
            
*/
           

            break;
            
    }

    //email_test(in, out);
    return 0;
}

long provider_email_calls(long action, CVars in, CVars &out) {

    logfmt(logINFO, "provider_email_calls()");
    out["result"] = "ECHO BACKEND";

    CVars x, y, z, x1, x2, x3, q;
    long ret = 0;
    char * server_name = getenv("SERVER_NAME");
    const char * loc = getenv("REMOTE_ADDR");
    C_CGI_Form form("", "");
    // form.LetStr("subject", "KleenApp Email Test");
    char vname[100];

    form.LetStr("site_name", "KleenApp");
    form.LetStr("agent_site", "https://agent.medtransgo.com/");
    logfmt(logINFO, "@@@@@@->AMEYE-1)");

    switch (action) {

        case MEDTRANS_TRANSP_ASSIGNTRANSPORT:

            if (load_db_record(x, "SELECT m.id AS member_id, a.agent_name,s.provider,s.quantity,"
                    " TO_CHAR(s.service_date :: TIMESTAMP, 'Day Mon dd, yyyy HH:MI AM') AS long_date,"
                    " a.street AS to_street,a.city AS to_city,a.state AS to_state,a.zipcode AS to_zipcode,a.phone AS to_phone,"
                    " m.firstname,m.lastname,m.email AS member_email "
                    " FROM members_service_request s "
                    " LEFT JOIN agents a ON  a.id=s.agent_id "
                    " LEFT JOIN members m ON m.id=s.member_id "
                    " WHERE s.id=%lu", in["service_id"].Long()) > 0) {
                vars2form(x, form);
                load_db_record(y, "SELECT email AS req_email,firstname AS cus_firstname,lastname AS cus_lastname ,phone as cus_phone FROM members WHERE id  = %lu ", x["member_id"].Long());
                vars2form(y, form);


                load_db_record(q, "SELECT  street1 AS from_street,  street2 AS from_street2, city AS from_city,  zipcode AS from_zipcode , state AS from_state, country AS from_country "
                        "FROM members_profile WHERE member_id =%lu", x["member_id"].Long());
                vars2form(q, form);

                if (x["provider"] != "" && x["provider"].Long() > 0) {
                    //
                    load_db_record(z, "SELECT d.firstname AS driver_firstname,d.lastname AS driver_lastname,d.email AS driver_email FROM providers d WHERE d.id  = %lu ", x["provider"].Long());
                    vars2form(z, form);
                    logfmt(logINFO, "@@@@@@->AMEYE-101)");
                    form.LetStr("confirm_link", in["service_id"].c_str());
                    logfmt(logINFO, "@@@@@@->AMEYE-102)");
                    form.LetStr("server_link", "https://www.kleenapp.co//provider/processRequest?reqId=");
                    logfmt(logINFO, "@@@@@@->AMEYE-103)");
                    form.LetStr("subject", "Laundry Pickup Assigned");
                    form.LetStr("email", z["driver_email"].c_str());
                    form.Email("PROVIDERS/pickup_assigned.mailfile");
                    logfmt(logINFO, "@@@@@@->AMEYE-104)");
                }
            }

            break;

    }

    return 0;
}

long transporter_email_calls(long action, CVars in, CVars &out) {
    email_test(in, out);

    return 0;
}


long dailyReport();

long cron_email_calls(long action, CVars in, CVars &out) {

    switch (action) {

        case 900005:
            return dailyReport();
            break;
    }

    return 0;
}

long dailyReport() {
    CVars out;
    logfmt(logINFO, "dailyReport()");
    out["result"] = "ECHO BACKEND";

    long ret = 0;
    const char * loc = getenv("REMOTE_ADDR");
    C_CGI_Form form("", "");
    form.LetStr("subject", "KleenApp Alert Email");
    out["alertrequest"] = CfgReadChar("alerts.request");
    form.LetStr("site_name", "KleenApp");

    CVars w, x, y, z;
    load_db_record(x, "SELECT  TO_CHAR( now() :: DATE, 'Day Mon dd, yyyy') AS long_date,  now()::date AS report_date, count(id) AS today_members_count  FROM members WHERE added::date = now()::date;");
    vars2form(x, form);

    load_db_record(w, "SELECT count(id) AS new_translation_request FROM members_service_request WHERE translate=1 AND added::date=now()::date");
    vars2form(w, form);

    load_db_record(y, "SELECT count(id) AS new_transport_request FROM members_service_request WHERE transport=1 AND added::date=now()::date");
    vars2form(y, form);

    load_db_record(z, "SELECT count(id) AS new_partners FROM agents WHERE added::date=now()::date");
    vars2form(z, form);

    load_db_record(z, " SELECT count(id) AS new_transporter FROM transport_drivers WHERE added::date=now()::date;");
    vars2form(z, form);

    load_db_record(z, "SELECT count(id) AS new_translators FROM interpreters WHERE added::date=now()::date");
    vars2form(z, form);

    form.LetStr("email", out["alertrequest"].c_str());
    //  form.LetStr("email", "obi@utransportcorp.com,okeh@utransportcorp.com,support@medtransgo.net,ses66181@gmail.com");
    form.Email("ALERTS/daily_report.mailfile");

    return 0;
}

long alert_email_calls(long action, CVars in, CVars &out) {

    logfmt(logINFO, "alert_email_calls()");
    out["result"] = "ECHO BACKEND";

    CVars x, y, z,x1,x2,x3,q;
    long ret = 0;
    const char * loc = getenv("REMOTE_ADDR");
    C_CGI_Form form("", "");
    form.LetStr("subject", "KleenApp Alert Email");
    out["alertrequest"] = CfgReadChar("alerts.request");
    out["alertaccount"] = CfgReadChar("alerts.account");
    CGIList * inv_list = new CGIList( &form, "inv_items" );
    char listing_items[1024];
    const PGresult *res;

    form.LetStr("site_name", "KleenApp");

    switch (action) {


        case MEDTRANS_USER_CREATE:
            if (load_db_record(x, "SELECT *,email as email2,now() AS last_login3 FROM members WHERE id = %lu ", in["member_id"].Long())) {
                vars2form(x, form);
                form.LetStr("email", out["alertrequest"].c_str());
                form.Email("ALERTS/signup_alert.mailfile");
            }
            break;
            
        case MEDTRANS_USER_NEWLUNDRYPICK:

            if (load_db_record(x, "SELECT m.id AS member_id, a.agent_name,"
                    " TO_CHAR(s.service_date :: TIMESTAMP, 'Day Mon dd, yyyy HH:MI AM') AS long_date,"
                    " a.street AS to_street,a.city AS to_city,a.state AS to_state,a.zipcode AS to_zipcode,a.phone AS to_phone,"
                    " m.firstname,m.lastname,m.email AS member_email,"
                    " mp.street1 AS from_street, mp.street2 , "
                    " mp.city AS from_city,mp.zipcode AS from_zipcode,"
                    " m.email AS customer_email,mp.state AS from_state, mp.country AS from_country  "
                    " FROM members_service_request s "
                    " LEFT JOIN agents a ON  a.id=s.agent_id "
                    " LEFT JOIN members m ON m.id=s.member_id "
                    " LEFT JOIN  members_profile mp ON mp.member_id=m.id "
                    " WHERE s.id=%lu", in["service_id"].Long()) > 0) {
                vars2form(x, form);

                res = pgsql_query("SELECT *,total*0.01 AS line_total FROM members_service_detail WHERE service_id = %lu AND quantity > 0 ORDER BY id ASC", in["service_id"].Long());

                if (res != NULL && pgsql_num_rows(res) > 0) {
                    out["total_record"] = pgsql_num_rows(res);

                    for (int i = 0, n = pgsql_num_rows(res); i < n; i++) {
                        map<const char*, const char*>f = pgsql_fetch_assoc(res, i);
                        if (f.empty()) continue;
                        CVars rec;
                        map_to_cvars(f, rec);

                        sprintf(listing_items, "<TR><td >*</td><td >%s</td><td >%s</td><td style='text-align:right;'>$%s</td></TR>", rec["description"].c_str(), rec["quantity"].c_str(), rec["line_total"].c_str());
                        inv_list->LetStr("pin", listing_items);
                        inv_list->CloseElement();
                    }
                }
                form.LetStr("subject", "Alert - Service Request");
                form.LetStr("email", out["alertrequest"].c_str());
                form.Email("ALERTS/service_request.mailfile");
            }

            break;


        case JUBABOX_USER_CONFIRMPICKUP:
            
                        if (load_db_record(x, "SELECT m.id AS member_id, a.agent_name,s.payment_id,"
                    " TO_CHAR(s.service_date :: TIMESTAMP, 'Day Mon dd, yyyy HH:MI AM') AS long_date,"
                    " a.street AS to_street,a.city AS to_city,a.state AS to_state,a.zipcode AS to_zipcode,a.phone AS to_phone,"
                    " m.firstname,m.lastname,m.email AS member_email,p.amount,p.confirmation "
                    " FROM members_service_request s "
                    " LEFT JOIN agents a ON  a.id=s.agent_id "
                    " LEFT JOIN payment p ON p.id=s.payment_id "
                    " LEFT JOIN members m ON m.id=s.member_id "
                    " WHERE s.id=%lu", in["service_id"].Long()) > 0) {
                vars2form(x, form);

                load_db_record(y, "SELECT  street1 AS from_street,  street2 AS from_street2, city AS from_city,  zipcode AS from_zipcode , state AS from_state, country AS from_country "
                        "FROM members_profile WHERE member_id =%lu", x["member_id"].Long());
                vars2form(y, form);

                res = pgsql_query("SELECT *,total*0.01 AS line_total FROM members_service_detail WHERE service_id = %lu AND quantity > 0 ORDER BY id ASC", in["service_id"].Long());

                if (res != NULL && pgsql_num_rows(res) > 0) {
                    out["total_record"] = pgsql_num_rows(res);

                    for (int i = 0, n = pgsql_num_rows(res); i < n; i++) {
                        map<const char*, const char*>f = pgsql_fetch_assoc(res, i);
                        if (f.empty()) continue;
                        CVars rec;
                        map_to_cvars(f, rec);

                        sprintf(listing_items, "<TR><td >*</td><td >%s</td><td >%s</td><td style='text-align:right;'>$%s</td></TR>", rec["description"].c_str(), rec["quantity"].c_str() , rec["line_total"].c_str());
                        inv_list->LetStr("pin", listing_items);
                        inv_list->CloseElement();
                    }
                } 
                         
                         
                if (x["member_id"].Long() > 0 && x["payment_id"].Long() > 0 ) {
                    logfmt(logINFO, "GOOD STSRT ~*******************************************************()");
                    vars2form(x, form); // bind again  - somehow this email is not coming out 
                    form.LetStr("subject", "Alert Laundry Pickup Confirmation");
                     form.LetStr("email", out["alertrequest"].c_str());
                   form.Email("ALERTS/laundry_pickup_confirmed.mailfile");
                    logfmt(logINFO, "GOOD END ~*******************************************************()");

                } else {
                    form.LetStr("subject", "Alert Failed Laundry Pickup Confirmation");
                    form.LetStr("email", out["alertrequest"].c_str());
                     form.Email("ALERTS/laundry_pickup_confirmed_fail.mailfile");
                }
            }

            break;
        
        
        case MEDTRANS_USER_LOGIN:
            if (load_db_record(x, "SELECT *,email as email2,now() AS last_login2 FROM members WHERE id = %lu ", in["member_id"].Long())) {
                vars2form(x, form);
                form.LetStr("email", out["alertrequest"].c_str());
                form.Email("USERS/user_login.mailfile");
            }
            break;

       /* case MEDTRANS_USER_CREATE:
            if (load_db_record(x, "SELECT *,email as email2,now() AS last_login2 FROM members WHERE id = %lu ", in["member_id"].Long())) {
                vars2form(x, form);
                form.LetStr("email", out["alertrequest"].c_str());
                form.Email("USERS/user_welcome.mailfile");
            }
*/
            break;
        case MEDTRANS_TRANSP_LOGIN:


            if (load_db_record(x, "SELECT * FROM agents WHERE id = %lu ", in["agent_id"].Long())) {
                vars2form(x, form);
                form.LetStr("email", out["alertaccount"].c_str());
                form.Email("ALERTS/agent_login.mailfile");
            }
            break;

    
            
            
            
            break;

        case CRON_PROCESS_DISTANCE:
            if (load_db_record(x, "SELECT r.*,l.language,TO_CHAR(r.service_date :: TIMESTAMP, 'Day Mon dd, yyyy HH:MI AM') AS long_date"
                    " FROM members_service_request r LEFT JOIN languages l ON l.code =  r.lang_code  WHERE r.id = %lu ", in["request_id"].Long())) {
                vars2form(x, form);


                load_db_record(y, "SELECT email AS req_email,firstname AS req_firstname,lastname AS req_lastname FROM members WHERE id  = %lu ", out["member_id"].Long());
                vars2form(y, form);

                if (x["transport"] == 1) {
                    long invoice_id = getMemberInvoiceID( in["request_id"].Long() );
                    
                    load_db_record(z, "SELECT (transport+translate+concierge)*0.01 AS total_price FROM members_invoice WHERE id = %lu",invoice_id);
                    vars2form(z, form);       
                            
                    res = pgsql_query("SELECT *,total*0.01 AS line_total FROM members_invoice_detail WHERE invoice_id = %lu AND total > 0 ORDER BY id ASC", invoice_id);

                    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);

                            sprintf(listing_items, "<TR><td >*</td><td >%s</td><td ></td><td >$%s</td></TR>", rec["description"].c_str(), rec["line_total"].c_str());
                            inv_list->LetStr("pin", listing_items);
                            inv_list->CloseElement();

                        }
                    }                                      
                  
                    form.LetStr("email", out["alertrequest"].c_str());
                    form.Email("ALERTS/transport_confirm_recieved.mailfile");
                }

                if (x["translate"] == 1) {
                    //           form.LetStr("email", out["alertrequest"].c_str());
                    //          form.Email("ALERTS/translation_recieved.mailfile");
                }

            }
            break;

        case MEDTRANS_TRANSL_ASSIGNFAIL:

            if (load_db_record(x, "SELECT r.*,l.language,TO_CHAR(r.service_date :: TIMESTAMP, 'Day Mon dd, yyyy HH:MI AM') AS long_date"
                    " FROM members_service_request r LEFT JOIN languages l ON l.code =  r.lang_code  WHERE r.id = %lu ", in["transport_id"].Long())) {
                vars2form(x, form);
                load_db_record(y, "SELECT email AS req_email,firstname AS req_firstname,lastname AS req_lastname FROM members WHERE id  = %lu ", out["member_id"].Long());
                vars2form(y, form);
                if (x["translate"] == 1) {
                    form.LetStr("email", out["alertrequest"].c_str());
                    form.Email("ALERTS/translation_autoassign_fail.mailfile");
                }
            }
            break;

    }
    logfmt(logINFO, "/alert_email_calls()");


}

/*****************************************************************************/
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());
        }
    }
}

void commonItems(C_CGI_Form &form) {
    char * server_name = getenv("SERVER_NAME");
    form.LetStr("server_name", server_name);

    form.LetStr("site_name", "KleenApp");
    form.LetStr("facebook", "KleenApp");
    form.LetStr("twitter", "KleenApp");
    form.LetStr("contactus", "KleenApp");
}

long email_test(CVars in, CVars &out) {
    logfmt(logINFO, "email_test()");

    long member_id = 1;
    CVars x;
    C_CGI_Form form("", "");
    out["alertemail"] = CfgReadChar("alerts.system");


    //form.LetStr( "site_name",  "KleenApp" );
    form.LetStr("subject", "KleenApp Email Test");

    commonItems(form);

    if (load_db_record(x, "SELECT *,email as email2 FROM members WHERE id = %lu ", member_id)) {
        vars2form(x, form);
        form.LetStr("email", out["alertemail"].c_str());
        //form.LetStr( "email",   "ses66181@gmail.com" );
        form.Email("ALERTS/testmail.mailfile");
    }
    return 0;

}

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

