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



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

    try {
        long member_id = REQ_LONG(in, "member_id", 1, -1);
        REQ_STRING(in, "user_pref", 5, 15, "(.*)");
        out["total_record"] = "0";
        const PGresult *res;
        res = pgsql_query("SELECT id,uid FROM members WHERE id  = %lu", member_id );

          if (res != NULL && pgsql_num_rows(res) > 0) {
                map<const char*, const char*>f = pgsql_fetch_assoc(res,0);
                CVars rec;
                map_to_cvars(f, rec);
                pgsql_query("UPDATE members SET account_pref='%s' WHERE id = %lu AND uid::text = '%s'", in["user_pref"].c_str() ,in["member_id"].Long(), rec["uid"].c_str());

             	if ( load_db_record( out, "SELECT id,uid,account_pref FROM members WHERE id  = %lu  AND uid::text = '%s' ",in["member_id"].Long(), rec["uid"].c_str() )){
                        ret = PHP_API_OK;
                        out["status"] = "OK";
                        out["status_msg"] = "members_pref_updated";
             	}
        }

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


long WrenchAccountUsePrefrence(CVars in, CVars &out){
 logfmt(logINFO, "WrenchAccountUsePrefrence()");
    char vname[30];
    long ret = PHP_API_BAD_PARAM;
/*
wrenchboard=> SELECT * FROM use_preferences WHERE status = 1 ORDER BY id ASC;
 id |                 uid                  |  pref  |            description             |       lang       |           added            | status
----+--------------------------------------+--------+------------------------------------+------------------+----------------------------+--------
  1 | 21a60345-c7f3-40aa-b386-97270d9109c6 | PREF01 | Find a task to get a reward.       | pref_lang_pref01 | 2023-12-30 16:01:53.451663 |      1
  2 | 5aa8a116-a9c5-4496-8c2b-3ac2ef51e278 | PREF02 | Organize family goals and rewards. | pref_lang_pref02 | 2023-12-30 16:01:53.460278 |      1
  3 | 1fe7b874-540d-4f39-b8f8-930541af0115 | PREF03 | Set up tasks I need to do.         | pref_lang_pref03 | 2023-12-30 16:01:53.461814 |      1
  4 | 54a6afcb-264b-4792-89d5-0d55638f375f | PREF04 | Just curiosity about everything.   | pref_lang_pref04 | 2023-12-30 16:01:53.463073 |      1
(4 rows)
*/
    try {
        long member_id = REQ_LONG(in, "member_id", 1, -1);
        out["total_record"] = "0";
        const PGresult *res;
        res = pgsql_query("SELECT * FROM use_preferences WHERE status = 1 ORDER BY id ASC");

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

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

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

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

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

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

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

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


long WrenchReturnHelpItems(CVars in, CVars &out){
    logfmt(logINFO, "WrenchReturnHelpItems()");
    char vname[30];
    long ret = PHP_API_BAD_PARAM;
/*
wrenchboard=> SELECT * FROM help_items WHERE status=1  ORDER BY lorder ASC;
 id |                 uid                  |    icon     |           title            |               contents               | lorder | status |           added
----+--------------------------------------+-------------+----------------------------+--------------------------------------+--------+--------+----------------------------
  1 | 82fabd0f-91c9-4472-9e84-8425010db4b4 | message.svg | What is WrenchBoard?       | Coming soon - Contents will be fixed |      1 |      1 | 2023-12-09 12:27:14.68754
  2 | 10392635-0098-42df-b338-9a8ec98cae93 | message.svg | Family Account             | Coming soon - Contents will be fixed |      1 |      1 | 2023-12-09 12:27:14.692123
  3 | d4e84174-5586-47b1-84fe-a2a339a33a8d | message.svg | How does Wrenchboard work? | Coming soon - Contents will be fixed |      1 |      1 | 2023-12-09 12:27:14.694878

*/
    try {
        long limit = REQ_LONG(in, "limit", 1, -1);
        REQ_LONG(in, "page", 1, -1);

        out["total_record"] = "0";

        const PGresult *res;

        res = pgsql_query("SELECT * FROM help_items WHERE status=1  ORDER BY id ASC");

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

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

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

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

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

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

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

long WrenchReturnMemberNotifications(CVars in, CVars &out){
/*

wrenchboard=> SELECT uid,icon,msg,added FROM members_notification WHERE member_id = 224 ORDER BY id DESC LIMIT 20;
                 uid                  |   icon    |                           msg                           |           added
--------------------------------------+-----------+---------------------------------------------------------+----------------------------
 ea666d19-fc60-46a0-810c-1adafffd34f8 | alert.svg | You have received a new offer waiting for you to start! | 2023-12-08 04:40:32.205169
 5374d9d4-87cf-4c2b-b374-48da88b917f3 | alert.svg | You have received a new offer waiting for you to start! | 2023-12-07 22:40:05.01972
 98d0d413-eb1f-4f5e-b11b-ad8ef8a819c6 | alert.svg | You have received a new offer waiting for you to start! | 2023-12-07 16:40:01.842667
(3 rows)

*/
    logfmt(logINFO, "WrenchReturnMemberNotifications()");
    char vname[30];
    long ret = PHP_API_BAD_PARAM;

    try {
        long limit = REQ_LONG(in, "limit", 1, -1);
        long member_id = REQ_LONG(in, "member_id", 1, -1);
        //REQ_LONG(in, "page", 1, -1);

        out["total_record"] = "0";

        const PGresult *res;

        res = pgsql_query("SELECT uid,icon,msg,added FROM members_notification WHERE member_id = %lu ORDER BY id DESC LIMIT 20", in["member_id"].Long(),limit);

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

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

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

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

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

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


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

return ret;
}

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

    try {
        long limit = REQ_LONG(in, "limit", 1, -1);
        long member_id = REQ_LONG(in, "member_id", 1, -1);
        REQ_LONG(in, "page", 1, -1);

        out["total_record"] = "0";

        const PGresult *res;
		
        res = pgsql_query("SELECT b.id bank_id,b.firstname||' '||b.lastname||' '||b.account_no||' '||k.name AS recipient,"
                " b.account_no,b.added  "
                "FROM sendmoney_recipient b "
                "LEFT JOIN bank_entity_codes k ON k.code=b.bank_code "
                "WHERE b.member_id = %lu AND b.status=1 LIMIT %lu", in["member_id"].Long(),limit);
				
        if (res != NULL && pgsql_num_rows(res) > 0) {
            out["total_record"] = pgsql_num_rows(res);

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

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

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

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

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


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

    try {
        long limit = REQ_LONG(in, "limit", 1, -1);
        long member_id = REQ_LONG(in, "member_id", 1, -1);
        REQ_LONG(in, "page", 1, -1);

        out["total_record"] = "0";

        const PGresult *res;
    
         res = pgsql_query("SELECT m.added::date AS trx_date,m.terminatingamount*0.01 AS amount,m.fee*0.01 as fee, m.id AS trx_id,"
                 " r.firstname||' '||r.lastname||'<br><b>Acc:</b>'||r.account_no||'-'||b.name AS recipient,mp.confirmation, c.code, c.description AS currency, c.symbol,"
                 " CASE WHEN m.status=1 THEN 'Pending' WHEN m.status=3 THEN 'Cancelled' WHEN m.status=5 THEN 'Completed' ELSE '' END AS status "
                 " FROM money_transfer m "
                 " LEFT JOIN sendmoney_recipient r ON r.id = m.recipientid "
                 " LEFT JOIN bank_entity_codes b ON b.code = r.bank_code "
                 " LEFT JOIN members_payments mp ON mp.what_sendmoney = m.id "
                 " LEFT JOIN currency c ON c.country=m.terminatingcountrycode "
                 " WHERE  m.member_id =%lu AND mp.confirmation IS NOT NULL ORDER BY m.id DESC LIMIT %lu", in["member_id"].Long(),limit);
         
        if (res != NULL && pgsql_num_rows(res) > 0) {
            out["total_record"] = pgsql_num_rows(res);

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


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

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

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

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

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

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

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

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

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

                snprintf(vname, sizeof (vname), "trx_id_%05d", i);
                out[vname] = rec["trx_id"];      
                
            }
        }
        ret = PHP_API_OK;
        out["status"] = "OK";
    } catch (bad_parameter) {
        logfmt(logINFO, "ERROR CALL long WrenchReturnMemberPaymentHxcd .."
                "(CVars in, CVars &out)");
    }
    logfmt(logINFO, "/WrenchReturnMemberPaymentHx()");
    return ret;
}
  

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

    try {
        long limit = REQ_LONG(in, "limit", 1, -1);
        long member_id = REQ_LONG(in, "member_id", 1, -1);
        REQ_LONG(in, "page", 1, -1);

        out["total_record"] = "0";

        const PGresult *res;



		res = pgsql_query("SELECT jo.added::date,mj.title, mj.description AS description, jo.job_description,mj.price, mj.timeline_days "
                 "FROM members_jobs_offer jo LEFT JOIN members_jobs mj ON mj.id = jo.job_id "
                 "WHERE jo.expire > now() AND jo.status = 1 "
                 "AND jo.client_id = %lu LIMIT %lu ", in["member_id"].Long(), 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);

				snprintf(vname, sizeof (vname), "title_%05d", i);
                out[vname] = rec["title"];
				
                snprintf(vname, sizeof (vname), "project_%05d", i);
                out[vname] = rec["project"];

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

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

				snprintf(vname, sizeof (vname), "delivery_date_%05d", i);
                out[vname] = rec["delivery_date"];
				
				snprintf(vname, sizeof (vname), "status_description_%05d", i);
                out[vname] = rec["status_description"];
				
				snprintf(vname, sizeof (vname), "timeline_days_%05d", i);
                out[vname] = rec["timeline_days"];
				
				snprintf(vname, sizeof (vname), "contract_%05d", i);
                out[vname] = rec["contract"];				
				
				snprintf(vname, sizeof (vname), "job_description_%05d", i);
                out[vname] = rec["job_description"];	
				
				snprintf(vname, sizeof (vname), "price_%05d", i);
                out[vname] = rec["price"];
				
                snprintf(vname, sizeof (vname), "job_id_%05d", i);
                out[vname] = rec["job_id"];
				
				snprintf(vname, sizeof (vname), "contract_id_%05d", i);
                out[vname] = rec["contract_id"];
            }
        }
        ret = PHP_API_OK;
        out["status"] = "OK";
    } catch (bad_parameter) {
        logfmt(logINFO, "ERROR CALL long WrenchMemberJobsOffers(CVars in, CVars &out)");
    }
    logfmt(logINFO, "/WrenchMemberJobsOffers()");
    return ret;



}


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

    try {
        long limit = REQ_LONG(in, "limit", 1, -1);
        long member_id = REQ_LONG(in, "member_id", 1, -1);
        REQ_LONG(in, "page", 1, -1);

        out["total_record"] = "0";

        const PGresult *res;


        res = pgsql_query("SELECT mc.id AS contract_id, mc.job_id AS job_id, mc.price, mc.timeline_days,mc.contract, "
                "  mj.title, mj.description AS description,mc.job_detail AS job_description, "
                " (CASE WHEN mc.status=4 THEN 'Review' "
                "  WHEN mc.status = 1 AND mc.delivery_date > now() THEN 'Active' "
                "  WHEN mc.status = 1 AND mc.delivery_date <now() THEN 'Past Due' "
                "  ELSE 'Others' END)  AS status_description,mc.delivery_date  "
                "  FROM members_jobs_contract mc LEFT JOIN members_jobs mj ON mj.id = mc.job_id LEFT JOIN members m ON m.id=mc.client_id  "
                "  WHERE mc.member_id = %lu AND mc.status IN (1,2,4)  OR mc.client_id =%lu AND mc.status IN (1,2,4) ", in["member_id"].Long(), in["member_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);

				snprintf(vname, sizeof (vname), "title_%05d", i);
                out[vname] = rec["title"];
				
                snprintf(vname, sizeof (vname), "project_%05d", i);
                out[vname] = rec["project"];

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

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

				snprintf(vname, sizeof (vname), "delivery_date_%05d", i);
                out[vname] = rec["delivery_date"];
				
				snprintf(vname, sizeof (vname), "status_description_%05d", i);
                out[vname] = rec["status_description"];
				
				snprintf(vname, sizeof (vname), "timeline_days_%05d", i);
                out[vname] = rec["timeline_days"];
				
				snprintf(vname, sizeof (vname), "contract_%05d", i);
                out[vname] = rec["contract"];				
				
				snprintf(vname, sizeof (vname), "job_description_%05d", i);
                out[vname] = rec["job_description"];	
				
				snprintf(vname, sizeof (vname), "price_%05d", i);
                out[vname] = rec["price"];
				
                snprintf(vname, sizeof (vname), "job_id_%05d", i);
                out[vname] = rec["job_id"];
				
				snprintf(vname, sizeof (vname), "contract_id_%05d", i);
                out[vname] = rec["contract_id"];
            }
        }
        ret = PHP_API_OK;
        out["status"] = "OK";
    } catch (bad_parameter) {
        logfmt(logINFO, "ERROR CALL long WrenchMemberActiveJobs(CVars in, CVars &out)");
    }
    logfmt(logINFO, "/WrenchMemberActiveJobs()");
    return ret;



}

long WrenchMemberMarketMessages(CVars in, CVars &out) {
    logfmt(logINFO, "WrenchMemberMarketMessages()");
    char vname[60];
	char vname_memo[60];
    long ret = PHP_API_BAD_PARAM;
	long msg_id = 0;

    try {
        long limit = REQ_LONG(in, "limit", 1, -1);
        long member_id = REQ_LONG(in, "member_id", 1, -1);
        REQ_LONG(in, "page", 1, -1);
        OPTIONAL(in, "recent") REQ_LONG(in, "recent", 1, -1);
		REQ_STRING(in, "offer_code", 5, 25, "(.*)");

		// this section ;limit recent or not recent
		if ( in["recent"].Long() == 1 ){
			snprintf(vname, sizeof (vname), " AND now() <  mm.added + '96 hours' ");
		}
		else
		{snprintf(vname, sizeof (vname), " ");
		}

		snprintf(vname_memo, sizeof (vname_memo), " AND LOWER(TRIM(mm.memo)) = LOWER('%s') ",in["offer_code"].c_str() );
        out["total_record"] = "0";

        const PGresult *res;

		res = pgsql_query("SELECT to_char(mm.added, 'Day Mon dd, yyyy HH:MI AM') AS msg_date,mm.msg,mm.id AS msg_id "
		                " ,mm.senders_id , mm.msg_type,j.title, j.description,mo.job_description,  "
						" mm.memo,ms.firstname AS msg_from,mm.reply,mm.member_id,mm.uid,TRIM(mm.memo) AS memo "
						" FROM members_messages mm "
						" LEFT JOIN members ms ON ms.id =mm.senders_id "
                        " LEFT JOIN members_jobs_offer mo ON mo.offer_code = mm.memo "
                        " LEFT JOIN members_jobs j ON j.id = mo.job_id "
						" WHERE mm.senders_id = %lu %s %s"
						" ORDER BY msg_id DESC LIMIT %lu", in["member_id"].Long(),vname,vname_memo, limit);

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

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

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

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

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

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

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

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

                snprintf(vname, sizeof (vname), "msg_from_%05d", i);
				if (rec["senders_id"] == in["member_id"] ){
				  out[vname] = "You";
				}
				else{
				   out[vname] = rec["msg_from"];
				}



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

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

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

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

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

				snprintf(vname, sizeof (vname), "message_mode_%05d", i);
				if (rec["senders_id"] == in["member_id"] ){
				  out[vname] = "sender";
				}
				else{
				  out[vname] = "recipient";
				}
            }
        }
        ret = PHP_API_OK;
        out["status"] = "OK";
    } catch (bad_parameter) {
        logfmt(logINFO, "ERROR CALL long WrenchMemberMarketMessages(CVars in, CVars &out)");
    }
    logfmt(logINFO, "/WrenchMemberMarketMessages()");
    return ret;
}

long WrenchMemberOwnerMarketMessages(CVars in, CVars &out) {
    logfmt(logINFO, "WrenchMemberOwnerMarketMessages()");
    char vname[60];
	char vname_memo[60];
    long ret = PHP_API_BAD_PARAM;
	long msg_id = 0;

    try {
        long limit = REQ_LONG(in, "limit", 1, -1);
        long member_id = REQ_LONG(in, "member_id", 1, -1);
        REQ_LONG(in, "page", 1, -1);
        OPTIONAL(in, "recent") REQ_LONG(in, "recent", 1, -1);
		OPTIONAL(in, "offer_code") REQ_STRING(in, "offer_code", 5, 25, "(.*)");

		// this section ;limit recent or not recent
		if ( in["recent"].Long() == 1 ){
			snprintf(vname, sizeof (vname), " AND now() <  mm.added + '96 hours' ");
		}
		else
		{snprintf(vname, sizeof (vname), " ");
		}

        if( in["offer_code"] !=""){
				snprintf(vname_memo, sizeof (vname_memo), " AND LOWER(TRIM(mm.memo)) = LOWER('%s') ",in["offer_code"].c_str() );
		}
		else{
			snprintf(vname_memo, sizeof (vname_memo), " " );
		}
        out["total_record"] = "0";

        const PGresult *res;

		res = pgsql_query("SELECT to_char(mm.added, 'Day Mon dd, yyyy HH:MI AM') AS msg_date,mm.msg,mm.id AS msg_id , "
		                " mm.senders_id , mm.msg_type,mm.uid, j.title, j.description,mo.job_description, "
						" mm.memo,ms.firstname AS msg_from,mm.reply,mm.member_id,mm.uid,TRIM(mm.memo) AS memo   FROM members_messages mm "
						" LEFT JOIN members ms ON ms.id =mm.senders_id "
						" LEFT JOIN members_jobs_offer mo ON mo.offer_code = mm.memo "
						" LEFT JOIN members_jobs j ON j.id = mo.job_id "
						" WHERE mm.member_id = %lu %s %s AND mo.expire > now()"
						" ORDER BY msg_id DESC LIMIT %lu", in["member_id"].Long(),vname,vname_memo, limit);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

				snprintf(vname, sizeof (vname), "message_mode_%05d", i);
				if (rec["senders_id"] == in["member_id"] ){
				  out[vname] = "sender";
				}
				else{
				  out[vname] = "recipient";
				}
            }
        }
        ret = PHP_API_OK;
        out["status"] = "OK";
    } catch (bad_parameter) {
        logfmt(logINFO, "ERROR CALL long WrenchMemberOwnerMarketMessages(CVars in, CVars &out)");
    }
    logfmt(logINFO, "/WrenchMemberOwnerMarketMessages()");
    return ret;
}

long WrenchReturnMemberMessages(CVars in, CVars &out) {
    logfmt(logINFO, "WrenchReturnMemberMessages()");
    char vname[60];
	char vname_memo[60];
    long ret = PHP_API_BAD_PARAM;
	long msg_id = 0;

    try {
        long limit = REQ_LONG(in, "limit", 1, -1);
        long member_id = REQ_LONG(in, "member_id", 1, -1);
        REQ_LONG(in, "page", 1, -1);
        OPTIONAL(in, "recent") REQ_LONG(in, "recent", 1, -1);
        
		// this section ;limit recent or not recent
		if ( in["recent"].Long() == 1 ){
			snprintf(vname, sizeof (vname), " AND now() <  mm.added + '96 hours' ");
		}
		else
		{snprintf(vname, sizeof (vname), " ");			
		}
			
		// This section focus the message based on memo
	    OPTIONAL(in, "msg_id") REQ_LONG(in, "msg_id", 1, -1);
		if( in["msg_id"].Long() > 0 ){
		  REQ_STRING(in, "uid", 10, 100, "(.*)");
		  load_db_record(out, "SELECT TRIM(memo) AS memo FROM members_messages WHERE LOWER(uid::text)= LOWER('%s')", in["uid"].c_str());
		  if ( out["memo"] != "" ){
		    snprintf(vname_memo, sizeof (vname_memo), " AND LOWER(TRIM(mm.memo)) = LOWER('%s') ",out["memo"].c_str() );
		  }else{
		    snprintf(vname_memo, sizeof (vname_memo), "");
		  }
		}else{
		 snprintf(vname_memo, sizeof (vname_memo), ""); // clean it up
		}
		
        out["total_record"] = "0";

        const PGresult *res;
      /*  res = pgsql_query("SELECT mm.added::date AS msg_date,mm.msg,mm.id AS msg_id ,mm.senders_id , mm.msg_type, mm.memo,ms.firstname AS msg_from "
                "FROM members_messages mm LEFT JOIN members ms ON ms.id =mm.senders_id "
                "WHERE mm.member_id = %lu "
                " %s AND mm.reply IS NULL ORDER BY mm.id DESC LIMIT %lu", in["member_id"].Long(),vname, limit);
				to_char(mm.added, 'Day Mon dd, yyyy HH:MI AM') AS expire2 
				
				*/


		res = pgsql_query("SELECT to_char(mm.added, 'Day Mon dd, yyyy HH:MI AM') AS msg_date,mm.msg,mm.id AS msg_id ,mm.senders_id , mm.msg_type, "
						" mm.memo,ms.firstname AS msg_from,mm.reply,mm.member_id,mm.uid,TRIM(mm.memo) AS memo   FROM members_messages mm "
						" LEFT JOIN members ms ON ms.id =mm.senders_id WHERE mm.senders_id = %lu %s %s"
						" UNION "
						" SELECT to_char(mm.added, 'Day Mon dd, yyyy HH:MI AM') AS msg_date,mm.msg,mm.id AS msg_id ,mm.senders_id , mm.msg_type, "
						" mm.memo,ms.firstname AS msg_from,mm.reply,mm.member_id,mm.uid,TRIM(mm.memo) AS memo  FROM members_messages mm "
						" LEFT JOIN members ms ON ms.id =mm.senders_id WHERE mm.member_id = %lu %s %s"
						" ORDER BY msg_id DESC LIMIT %lu", in["member_id"].Long(),vname,vname_memo, in["member_id"].Long(), vname,vname_memo, limit);

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

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

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

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

                snprintf(vname, sizeof (vname), "msg_%05d", i);
                out[vname] = rec["msg"];
				
                snprintf(vname, sizeof (vname), "msg_from_%05d", i);
				if (rec["senders_id"] == in["member_id"] ){
				  out[vname] = "You";	
				}
				else{
				   out[vname] = rec["msg_from"];   
				}
                
               
				
                snprintf(vname, sizeof (vname), "senders_id_%05d", i);
                out[vname] = rec["senders_id"];  
				
                snprintf(vname, sizeof (vname), "member_id_%05d", i);
                out[vname] = rec["member_id"];  

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

                snprintf(vname, sizeof (vname), "uid_%05d", i);
                out[vname] = rec["uid"];
				
				snprintf(vname, sizeof (vname), "memo_%05d", i);
                out[vname] = rec["memo"];
				
				snprintf(vname, sizeof (vname), "message_mode_%05d", i);
				if (rec["senders_id"] == in["member_id"] ){
				  out[vname] = "sender";	
				}
				else{
				  out[vname] = "recipient";	
				}
            }
        }
        ret = PHP_API_OK;
        out["status"] = "OK";
    } catch (bad_parameter) {
        logfmt(logINFO, "ERROR CALL long WrenchReturnMemberMessages(CVars in, CVars &out)");
    }
    logfmt(logINFO, "/WrenchReturnMemberMessages()");
    return ret;
}
  

/* This return the list of jobs on the home page of the apps*/
long WrenchReturnJobList(CVars in, CVars &out) {
    logfmt(logINFO, "WrenchReturnJobList()");
    char extraQ[300];
    char vname[30];
    long ret = PHP_API_BAD_PARAM;

    try {
        long limit = REQ_LONG(in, "limit", 1, -1);
        OPTIONAL(in, "member_id")  REQ_LONG(in, "member_id", 1, -1);
        OPTIONAL(in, "uid") REQ_STRING(in, "uid", 2, 149, "(.*)");

        if ( in["member_id"].Long() >  0  && in["uid"] !=""){
          logfmt(logINFO, "***  WrenchReturnJobList() member_id = %lu uid=%s", in["member_id"].Long(), in["uid"].c_str());
          snprintf(extraQ, sizeof (extraQ), " AND j.country IN  (SELECT c.country FROM members_wallet w LEFT JOIN currency c ON c.code =w.currency WHERE w.member_id = %lu ) ", in["member_id"].Long());
        }
        else{
          snprintf(extraQ, sizeof (extraQ), " ");
        }


        REQ_LONG(in, "page", 1, -1);
        out["total_record"] = "0";
        const PGresult *res;

        res = pgsql_query("SELECT j.title,j.description,m.id AS job_id,m.expire,m.job_description,j.price, "
                        " m.offer_code,j.timeline_days, to_char(m.expire, 'Dy Mon dd, yyyy HH:MI AM') AS expire2,"
                        " m.uid AS offer_uid,j.uid AS job_uid,m.added::date AS offer_added,j.country AS job_country, "
                        " c.code AS currency_code, c.description AS currency_description,j.country, j.category "
                        " FROM members_jobs_offer m "
                        " LEFT JOIN members_jobs j ON j.id=m.job_id "
                        " LEFT JOIN currency c ON c.country=j.country "
                        " WHERE m.status = 1 AND m.client_id=0 "
                        " AND m.expire IS NOT NULL "
                        " AND  m.public_view = 1 AND m.expire> now() AND j.status = 1 %s "
                        " ORDER BY m.expire DESC LIMIT %lu", extraQ, 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);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


            }
        }
/*
wrenchboard=> SELECT count(mo.id),mj.offer_code FROM members_offer_interest mo
     LEFT JOIN members_jobs_offer mj ON mj.id= mo.offer_id  WHERE  mj.expire > now() GROUP BY mj.offer_code
wrenchboard-> ;
 count | offer_code
-------+------------
     3 | 1B7R3134W0
     3 | 66WW5B9B45
     3 | Y1X0983WTP
(3 rows)
*/

  const PGresult *res2;

        res2 = pgsql_query("SELECT count(mo.id) AS interest_count,mj.offer_code FROM members_offer_interest mo "
                            " LEFT JOIN members_jobs_offer mj ON mj.id= mo.offer_id  "
                            " WHERE  mj.expire > now() GROUP BY mj.offer_code");

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

                for (int ii = 0, n = pgsql_num_rows(res2); ii < n; ii++) {
                    map<const char*, const char*>f2 = pgsql_fetch_assoc(res2, ii);
                    if (f2.empty()) continue;
                    CVars rec2;
                    map_to_cvars(f2, rec2);

                    snprintf(vname, sizeof (vname), "interest_count_%s", rec2["offer_code"].c_str());
                    out[vname] = rec2["interest_count"];

                     logfmt(logINFO, "WrenchReturnJobList->INTEREST COUNT %s ==== %lu",vname,rec2["interest_count"].Long());
                }
            }


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




long CreateMobileWrenchBoardAccount(CVars in, CVars &out) {
    long ret = PHP_API_BAD_PARAM;

    try {

        REQ_STRING(in, "username", 5, 49, "(.*)");
        REQ_STRING(in, "firstname", 2, 49, "(.*)");
        REQ_STRING(in, "lastname", 2, 49, "(.*)");
        REQ_STRING(in, "email", 5, 49, "(.*)");
        OPTIONAL(in, "phone") REQ_STRING(in, "phone", 3, 15, "(.*)");
        OPTIONAL(in, "loc") REQ_STRING(in, "loc", 3, 15, "(.*)");
        long news = REQ_LONG(in, "news", 1, -1);
        long terms = REQ_LONG(in, "terms", 1, -1);
        REQ_STRING(in, "password", 5, 25, "(.*)");
        OPTIONAL(in, "country") REQ_STRING(in, "country", 1, 3, "(.*)");
        //const char * loc = getenv('REMOTE_ADDR');
        //in["loc"]  = loc;
        OPTIONAL(in, "mobile") REQ_STRING(in, "mobile", 3, 15, "(.*)");

       // in["news"] =  "1";
        //in["news"].set_valid( true );
        
        
         ret = CreateWrenchBoardAccountPending(in, out);
    } catch (bad_parameter) {
        out["status"] = "ERROR";
    }

    return ret;
}

long CompleteMobileAccountCreation(CVars in, CVars &out){
   long ret = PHP_API_BAD_PARAM;
   CVars x;

   OPTIONAL(in, "mobile") REQ_STRING(in, "mobile", 3, 15, "(.*)");
   REQ_STRING (in, "password",   3, 15, "(.*)");

   if ( in["mobile"]=="MOBILE" ){
         REQ_STRING(in, "random_text", 3, 10, "(.*)");
         REQ_STRING(in, "pending_uid", 2, 120, "(.*)");
         CVars  ox;
   		if ( load_db_record(ox, "SELECT id,verify_link FROM members_pending WHERE  "
   		                         " LOWER(username)=LOWER('%s') "
   		                         " AND signup_random = '%s' AND uid ='%s' "
   		                         " AND password =md5('%s') ",in["username"].c_str(),in["random_text"].c_str(),in["pending_uid"].c_str(), in["password"].c_str()) > 0 ){
   			in["verify_link"] = ox["verify_link"]; in["verify_link"].set_valid( true );
   		}
   		else{
            out["status_message"] = "invalid_pin_or_password";
            out["status"] = "error";
            return ret;
   		}

   }

   x["password"]  = in["password"];  x["password"].set_valid( true );
   x["sessionid"] = "IINITIAL_SESSION_DUMMY";  x["sessionid"].set_valid( true );
   x["username"]  = in["username"];  x["username"].set_valid( true );
   x["login_mode"]= "100";  x["login_mode"].set_valid( true );

    if (  CreateWrenchBoardAccount(in, out) > 0 )
    {
         ret = LoginWrenchBoardAccount(x, out);
    }
   return ret;    
}

long CreateWrenchBoardAccount(CVars in, CVars &out) {
    logfmt(logINFO, "CreateWrenchBoardAccount()");
    long ret = PHP_API_BAD_PARAM;
    bool compt = false;
    REQ_STRING(in, "verify_link", 2, 120, "(.*)");
    REQ_STRING (in, "password",   3, 15, "(.*)");
    REQ_STRING(in, "username", 5, 49, "(.*)");
    OPTIONAL(in, "loc") REQ_STRING(in, "loc", 3, 15, "(.*)");
    CVars x;
    //const char * loc = getenv('REMOTE_ADDR');
    //in["loc"]  = loc;
    try {
        long lonkF = load_db_record(out, "SELECT *,id AS pending_id FROM members_pending WHERE verify_link ='%s' AND password =md5('%s') AND username ='%s' AND status= 1 AND expire > now() LIMIT 1", in["verify_link"].c_str(), in["password"].c_str(), in["username"].c_str());
        if (lonkF) {
         if (out["pending_id"].Long() >  0 ){
                out["status"] = "prepare to create account";

                x["username"] = out["username"];
                x["username"].set_valid(true);
                x["firstname"] = out["firstname"];
                x["firstname"].set_valid(true);
                x["lastname"] = out["lastname"];
                x["lastname"].set_valid(true);
                x["email"] = out["email"];
                x["email"].set_valid(true);
                x["phone"] = out["phone"];
                x["phone"].set_valid(true);
                x["loc"] = out["loc"];
                x["loc"].set_valid(true);
                x["country"] = out["country"];
                x["country"].set_valid(true);
                x["password"] = out["password"];
                x["password"].set_valid(true);
                ret = insert_db_record(DBS_VALID, "members", "members_id_seq", x);
                compt = true;
         }
         else{
         out["status"] = "Invalid Link & Password Combination";
         ret = PHP_API_BAD_PARAM;
         }


            if (ret > 0 && compt==true) {
                out["member_id"] = ret;
                out["member_id"].set_valid(true);
                x["member_id"] = ret;
                x["member_id"].set_valid(true);
                x["pending_id"] = out["pending_id"];
                x["pending_id"].set_valid(true);

                CVars u;
                out["wallet_status"] = "-1";
                load_db_record(u,"SELECT code AS currency FROM currency WHERE country = TRIM('%s')", x["country"].c_str() );
                logfmt(logINFO, " The Currency code = %s", u["currency"].c_str());
                out["wallet_id"] =  CheckWallet( x["member_id"].Long() , u);
                logfmt(logINFO, " The wallet_id = %lu", out["wallet_id"].Long());

                 if ( u["currency"]  !="" && out["wallet_id"].Long() > 0 ){
                     load_db_record( out, "SELECT amount AS balance,amount AS default_wallet_balance "
                                          " FROM members_wallet WHERE member_id = %lu AND currency='%s' ", out["member_id"].Long(), u["currency"].c_str()); // retired
                     out["wallet_status"] = "1";
                 }



                CVars vw;
             //   vw["currency"] = "NAIRA";  // this will become a variable based on the country
             //   vw["currency"].set_valid( true );
              //  out["wallet_id"] = CheckWallet(out["member_id"].Long(),vw); // initial wallet

                // - password already set pgsql_query("UPDATE members SET password = md5('%s') WHERE id = %lu",in["pass1"].c_str(),ret);
                pgsql_query("UPDATE members_pending SET status = 5 WHERE id = %lu", out["pending_id"].Long());
                pgsql_query("UPDATE members_refer_friend SET status = 5 WHERE status = 1 AND email = '%s'", x["email"].c_str());


                WelcomeAccountMail(x);
                SignupCompletedAlertMailfile(x);


            }


        }


    } catch (bad_parameter) {
        out["status"] = "ERROR";
    }

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

long CreateWrenchBoardAccountPending(CVars in, CVars &out) {
    long ret = PHP_API_BAD_PARAM;
    out = in;

    try {

        if ( load_db_record(out, "SELECT id AS pending_id, expire < now() AS expire,remind_count,now() > updated+'90 minutes' AS remind   FROM members_pending WHERE  LOWER(username)=LOWER('%s')",in["username"].c_str()) > 0 ){
             ret =  out["pending_id"].Long();
            if (out["remind"]=="t"  ){

                 if (in["mobile"] != "" && in["mobile"] == "MOBILE") {
                     //ALTER TABLE members_pending ADD signup_random INT;
                     in["mobile_email"] = "100"; in["mobile_email"].set_valid( true );
                     AccountPendingMail(out);
                 } else {
                     AccountPendingMail(out);
                 }
                   pgsql_query("UPDATE members_pending SET remind_count = remind_count+1  WHERE id = %lu", ret);
             }

             if (out["expire"]=="f"  ){
               load_db_record(out, "SELECT *,id AS pending_id FROM members_pending WHERE id=%lu LIMIT 1", ret);
               out["signup_random"] ="REMOVED";
               out["verify_link"] ="REMOVED";

               return ret;
             }

            pgsql_query("UPDATE members_pending SET username = '%lu'||'-'||username  WHERE id = %lu", ret, ret);
            out["password"]="REMOVED";
            out["acc"]="EXPIRED";
        return PHP_API_BAD_PARAM;
        }
        if ( load_db_record(out, "SELECT uid FROM members WHERE LOWER(username)=LOWER('%s')",in["username"].c_str())> 0 ){
            out["password"]="REMOVED";
            out["acc"]="DULPICATE";
        return PHP_API_BAD_PARAM;
        }



         REQ_STRING(in, "username", 5, 49, "(.*)");
         REQ_STRING(in, "firstname", 2, 49, "(.*)");
         REQ_STRING(in, "lastname", 2, 49, "(.*)");
         REQ_STRING(in, "email", 5, 49, "(.*)");
         OPTIONAL(in, "phone") REQ_STRING(in, "phone", 3, 15, "(.*)");
         OPTIONAL(in, "loc") REQ_STRING(in, "loc", 3, 15, "(.*)");
         long news = REQ_LONG(in, "news", 1, -1);
         long terms = REQ_LONG(in, "terms", 1, -1);
         REQ_STRING(in, "password", 5, 25, "(.*)");
         OPTIONAL(in, "country") REQ_STRING(in, "country", 1, 3, "(.*)");
         //const char * loc = getenv('REMOTE_ADDR');
         //in["loc"]  = loc;
         OPTIONAL(in, "mobile") REQ_STRING(in, "mobile", 3, 15, "(.*)");

         int r1, r2, r3,signup_random;
         char verify_link[100];
         srand(time(NULL));
         r1 = abs(rand()*100);
         srand(time(NULL));
         r2 = abs(rand() * r1);
         srand(time(NULL));
         r3 = abs(rand() * r2);
         srand(time(NULL));

         signup_random  = abs(rand()*0.009);
         sprintf(verify_link, "WRENCHB-%09lu-%08lu-%08lu", r1, r2, r3);

             CVars x;
             x["username"] = in["username"];
             x["username"].set_valid(true);
             x["firstname"] = in["firstname"];
             x["firstname"].set_valid(true);
             x["lastname"] = in["lastname"];
             x["lastname"].set_valid(true);
             x["email"] = in["email"];
             x["email"].set_valid(true);
             x["phone"] = in["phone"];
             x["phone"].set_valid(true);
             x["country"] = in["country"];
             x["country"].set_valid(true);

             if (in["loc"].length() > 0) x["loc"] = in["loc"];
             x["loc"].set_valid(true);
             x["verify_link"] = verify_link;
             x["verify_link"].set_valid(true);

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

             ret = insert_db_record(DBS_VALID, "members_pending", "members_pending_id_seq", x);

             if (ret > 0) {
                 pgsql_query("UPDATE members_pending SET password = md5('%s'),signup_random=%lu WHERE id = %lu", in["password"].c_str(),signup_random/1000, ret);
                 pgsql_query("UPDATE members_refer_friend SET status = 5 WHERE status = 1 AND email = '%s'", x["email"].c_str());

                load_db_record(out, "SELECT *,id AS pending_id FROM members_pending WHERE id=%lu LIMIT 1", ret);
             }

             if (ret > 0) {
                 out["pending_id"] = ret;
                 out["pending_id"].set_valid(true);
                 x["pending_id"] = ret;
                 x["pending_id"].set_valid(true);

                 if (in["mobile"] != "" && in["mobile"] == "MOBILE") {
                     //ALTER TABLE members_pending ADD signup_random INT;
                     x["mobile_email"] = "100"; x["mobile_email"].set_valid( true );
                     AccountPendingMail(x);
                 } else {
                     AccountPendingMail(x);
                 }
                 SignupPendingAlertMailfile(x);
             }


     		} catch (bad_parameter) {
     		out["status"] = "ERROR";
     	}
    out["verify_link"] ="REMOVED";
    out["signup_random"] ="REMOVED";

    return ret;
}

long WrenchAccountSettings( CVars in, CVars &out ){
   logfmt(logINFO, "WrenchAccountSettings()");
    char vname[30];
    long ret = PHP_API_BAD_PARAM;
    const PGresult *res;
    const PGresult *res0;

    try {
        long member_id =  REQ_LONG(in, "member_id", 1, -1);

        res0 = pgsql_query("SELECT pref_id,status FROM members_settings WHERE member_id = %lu",member_id);
        if (res0 != NULL && pgsql_num_rows(res0) > 0) {
             for (int i = 0, n = pgsql_num_rows(res0); i < n; i++) {
                map<const char*, const char*>f = pgsql_fetch_assoc(res0, i);
                if (f.empty()) continue;
                CVars rec;
                map_to_cvars(f, rec);
                snprintf(vname, sizeof (vname), "VALUE_%s",rec["pref_id"].c_str());
                out[vname] = rec["status"];
             }
         }



        out["total_record"] = "0";
        res = pgsql_query("SELECT id,title,description,pref_id,uid,'settings.svg' AS banner FROM  members_settings_options ORDER BY lorder ASC");
        if (res != NULL && pgsql_num_rows(res) > 0) {
            out["total_record"] = pgsql_num_rows(res);

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

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

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

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

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

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

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