// Mobile management toosl
#include "clog.h"
#include "cgi.h"
#include "input.h"
#include "wrenchboard_api.h"
#include "mobile.h"
#include "email.h"
#include "safestring.h"
#include <string>
#include "pgsql.h"
#include "pgsql_wrapper.h"
#include <curl/curl.h>
#include "account.h"
#include "history.h"
#include "jobs_manager.h"
#include "jobs.h"

#include "account_mngt.h"
#include "contract.h"

long WrenchReturnTaskMessage(CVars in, CVars &out);
long WrenchReturnOffersResponse(CVars in, CVars &out);

long mobile_calls(CVars in, CVars &out) {
    logfmt(logINFO, "mobile_calls()");
    out["result"] = "~~Backend Reached~~";
    long action = REQ_LONG(in, "action", 0, -1);
    switch (action) {
        case WRENCHBOARD_MOBILE_ACTIVEJOB:
            return WrenchReturnActiveJobsList(in, out);
            break;

        case WRENCHBOARD_MOBILE_OFFERSLIST:
            return WrenchReturnJobOffersList(in, out);
            break;

        case WRENCHBOARD_MOBILE_OFFERSRESP:
            return WrenchReturnOffersResponse(in, out);
            break;

        case WRENCHBOARD_MOBILE_LOADPROFILE:
            return WrenchReturnUserProfile(in, out);
            break;
        case WRENCHBOARD_MOBILE_UPDATEPROFILE:
            return WrenchUpdateUserProfile(in, out);
            break;
        case WRENCHBOARD_MOBILE_ACCOUNT:
            return WrenchReturnUserAccount(in, out);
            break;

        case WRENCHBOARD_MOBILE_MESSAGE:
            //return WrenchReturnMemberMessages(in, out);
            return WrenchMemberMarketMessages(in, out);
            break;

        case WRENCHBOARD_MOBILE_JOB_MESSAGE:
            return WrenchMemberOwnerMarketMessages(in, out);
            break;

        case WRENCHBOARD_MOBILE_PAYMENTHX:
            return  WrenchReturnMemberPaymentHx( in, out);
            break;
        case WRENCHBOARD_MOBILE_PURCHASEHX:
            return  WrenchPurchaseHx( in, out);
            break;
        case WRENCHBOARD_MOBILE_TASKMESSAGE:
            return  WrenchReturnTaskMessage( in, out);
            break;
        case WRENCHBOARD_MOBILE_SENDTASKMESSAGE:
            return   WrenchContractMessage( in, out);
            break;
        case WRENCHBOARD_ACCOUNT_REFFERHX:
            return  WrenchRefferHx( in, out);
            break;
    }
    logfmt(logINFO, "/mobile_calls()");
    return 0;
}
/*

#define WRENCHBOARD_MOBILE_OFFERSLIST     15010
#define WRENCHBOARD_MOBILE_ACTIVEJOB      15020
#define WRENCHBOARD_MOBILE_LOADPROFILE    15030
#define WRENCHBOARD_MOBILE_ACCOUNT        15040

long WrenchReturnActiveJobsList(CVars in, CVars &out)
long WrenchReturnJobOffersList(CVars in, CVars &out)

long WrenchReturnUserProfile(CVars in, CVars &out)
long WrenchReturnUserAccount(CVars in, CVars &out)
 */

/* This task message */
long WrenchReturnTaskMessage(CVars in, CVars &out) {
    logfmt(logINFO, "WrenchReturnTaskMessage()");
    long ret = PHP_API_BAD_PARAM;
    char vname[30];
    
 //   msg_id |      date1       |  title   |    msg                                            
 //   -----------------------------

    try {
        long member_id = REQ_LONG(in, "member_id", 1, -1);
        long limit = REQ_LONG(in, "limit", 1, -1);
         REQ_STRING(in, "sessionid", 2, 100, "(.*)");
         REQ_STRING(in, "contract", 2, 15, "(.*)");
          
        out["total_record"] = "0";
        const PGresult *res;
        res = pgsql_query("SELECT jc.id AS msg_id,to_char(jc.created, 'YYYY-MM-DD HH24:MI') AS date1, "
                " ''||(CASE WHEN jc.msg_type='FILE' THEN 'FILE' ELSE '' END) ||''||m.firstname AS title,(CASE WHEN jc.msg_type='FILE' THEN ''||jc.message||'' ELSE jc.message END) AS msg "
                " FROM jobs_contract_message jc "
                " LEFT JOIN members m ON m.id=jc.member_id "
                " WHERE jc.contract='%s' "
                " ORDER by jc.id DESC LIMIT %lu ", in["contract"].c_str(),in["limit"].Long() );

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

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

                snprintf(vname, sizeof (vname), "title_%05d", i);
                out[vname] = rec["title"];
                
                snprintf(vname, sizeof (vname), "date_%05d", i);
                out[vname] = rec["date1"];
                
                snprintf(vname, sizeof (vname), "msg_id_%05d", i);
                out[vname] = rec["msg_id"];
                
                snprintf(vname, sizeof (vname), "msg_%05d", i);
                out[vname] = rec["msg"];
            }
            
        
        }     
        
    } catch (bad_parameter) {
        logfmt(logINFO, "ERROR CALL long WrenchReturnTaskMessage(CVars in, CVars &out)");
    }
    logfmt(logINFO, "/WrenchReturnTaskMessage()");
    return ret;
}


/* This account apps*/
long WrenchReturnUserAccount(CVars in, CVars &out) {
    logfmt(logINFO, "WrenchReturnUserAccount()");
    char vname[30];
    long ret = PHP_API_BAD_PARAM;

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

        if (res != NULL && pgsql_num_rows(res) > 0) {
            out["total_record"] = pgsql_num_rows(res);
            map<const char*, const char*>f = pgsql_fetch_assoc(res, 0);
            map_to_cvars(f, out);  
            ret = PHP_API_OK;
            out["status"] = "OK";
        } 
    } catch (bad_parameter) {
        logfmt(logINFO, "ERROR CALL long WrenchReturnUserAccount(CVars in, CVars &out)");
    }
    logfmt(logINFO, "/WrenchReturnUserAccount()");
    return ret;
}

/* This profile apps*/
long WrenchReturnUserProfile(CVars in, CVars &out) {
    logfmt(logINFO, "WrenchReturnUserProfile()");
    long ret = PHP_API_BAD_PARAM;

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

        if (res != NULL && pgsql_num_rows(res) > 0) {
            out["total_record"] = pgsql_num_rows(res);
            map<const char*, const char*>f = pgsql_fetch_assoc(res, 0);
            map_to_cvars(f, out);  
            ret = PHP_API_OK;
            out["status"] = "OK";
            out["password"] = "";
            LoginWrenchBoardSetDashType(in, out);
        }     
        
    } catch (bad_parameter) {
        logfmt(logINFO, "ERROR CALL long WrenchReturnUserProfile(CVars in, CVars &out)");
    }
    logfmt(logINFO, "/WrenchReturnUserProfile()");
    return ret;
}

/* This profile apps*/
long WrenchUpdateUserProfile(CVars in, CVars &out) {
    logfmt(logINFO, "WrenchUpdateUserProfile()");
    long ret = PHP_API_BAD_PARAM;
    try {
        REQ_STRING(in, "firstname", 3, 49, "(.*)");
        REQ_STRING(in, "lastname", 3, 49, "(.*)");
        REQ_STRING(in, "email", 5, 150, "(.*)");
        REQ_STRING(in, "state",2, 150, "(.*)");
        REQ_STRING(in, "city", 3, 150, "(.*)");
        long member_id = REQ_LONG(in, "member_id", 1, -1);
        REQ_STRING(in, "uid", 3, 150, "(.*)");
        OPTIONAL(in, "online_name") REQ_STRING(in, "online_name", 3, 15, "(.*)");
        REQ_LONG(in, "pref_email", 1, -1);
        REQ_LONG(in, "pref_phone", 1, -1);

        const PGresult *res;
        res = pgsql_query("SELECT * FROM members WHERE id = %lu AND uid='%s'", member_id, in["uid"].c_str() );
        if (res != NULL && pgsql_num_rows(res) > 0) {
            CVars x;
            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["state"] = in["state"];
            x["state"].set_valid(true);
            x["city"] = in["city"];
            x["city"].set_valid(true);

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


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

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

            update_db_record(DBS_VALID, "members", x, member_id);
            ret = PHP_API_OK;
        }

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

/* This return the list of jobs on the home page of the apps*/
long WrenchReturnJobOffersList(CVars in, CVars &out) {
    logfmt(logINFO, "WrenchReturnJobOffersList()");
    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.id AS offer_id, mj.id AS job_id, jo.id AS contract_id, "
		         " jo.added::date,mj.title, jo.offer_code,jo.uid AS offer_uid,jo.expire, "
		         " jo.public_view, mj.uid AS job_uid, jo.added AS offer_added, mj.job_type AS job_type, mj.media_uid AS media_uid, "
		         " mj.description AS description, jo.job_description,mj.price, mj.timeline_days,jo.job_description AS job_detail, "
		         " c.code AS currency_code, c.description AS currency_description,mj.country,mf.uid AS family_uid,mj.banner AS banner "
                 " FROM members_jobs_offer jo "
                 " LEFT JOIN members_jobs mj ON mj.id = jo.job_id "
                 " LEFT JOIN currency c ON c.country=mj.country "
                 " LEFT JOIN members_family mf ON mf.family_member_id = jo.client_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), "offer_id_%05d", i);
                out[vname] = rec["id"];

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

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

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

				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["offer_code"];				
				
				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"];

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

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

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

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

                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_detail_%05d", i);   // delivery details from members_jobs_offers
                out[vname] = rec["job_detail"];

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

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

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

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

}

/* This return the list of jobs on the home page of the apps*/
long WrenchReturnActiveJobsList(CVars in, CVars &out) {
   // return WrenchUsersTasksList(in, out);
     return WrenchMemberActiveJobs(in, out);
}

/* This return the list of jobs on the home page of the apps*/
long WrenchReturnOffersResponse(CVars in, CVars &out) {

        long offer_result = REQ_LONG(in, "offer_result", 1, -1);
        long member_id = REQ_LONG(in, "member_id", 1, -1);
        REQ_STRING(in, "offer_code", 2, 15, "(.*)");

        return WrenchConcludeJobsOffer(in, out);

}