#include "clog.h"
#include "cgi.h"
#include "input.h"
#include "wrenchboard_api.h"
#include "reco_engine.h"  //error in file name
#include "email.h"
#include "safestring.h"
#include <string>
#include "pgsql.h"
#include "pgsql_wrapper.h"
#include <curl/curl.h>
#include "account.h"
#include "cards.h"
#include "twilo.h"
#include "mobile.h"
#include "jobs_manager.h"

/*
  $mysql2 = "SELECT jo.added::date AS start_job_date, jo.expire::date AS end_job_date, j.title, (CASE WHEN jo.public_view > 0 THEN '-Public View' ELSE jo.email END)  AS job_to,jo.offer_code AS offer_code,"
            . "'<input type=submit onclick=\"return post_nav_find_action($jbx,'''||jo.offer_code||''')\"  name=\"manage\" class=\"btn btn-primary btn-xs\" value=\"View\">' AS View  "
            . "FROM members_jobs_offer jo LEFT JOIN members_jobs j ON j.id = jo.job_id "
            . "WHERE jo.expire > now() AND jo.status = 1 "
            . "AND jo.member_id = " . $_SESSION['member_id'] . " ORDER BY jo.id DESC LIMIT 400";
        $query2 = $this->db->query($mysql2);
        $data['offer_dash_rows'] = $query2->result();

        wrenchboard=> \d members_jobs_offer
                                                   Table "public.members_jobs_offer"
             Column      |            Type             | Collation | Nullable |                    Default
        -----------------+-----------------------------+-----------+----------+------------------------------------------------
         id              | integer                     |           | not null | nextval('members_jobs_offer_id_seq'::regclass)
         offer_code      | character varying(15)       |           | not null |
         member_id       | integer                     |           |          |
         client_id       | integer                     |           |          | 0
         group_id        | integer                     |           |          | 0
         job_id          | integer                     |           |          |
         email           | character varying(50)       |           |          |
         job_description | text                        |           |          |
         status          | integer                     |           |          | 1
         sent_count      | integer                     |           |          | 0
         loc             | inet                        |           |          |
         expire          | timestamp without time zone |           |          |
         added           | timestamp without time zone |           |          | now()
         payment_id      | integer                     |           |          |
         public_view     | integer                     |           |          | 0
         auto_close      | timestamp without time zone |           |          |
         reminder_count  | integer                     |           |          | 0
         reminder_date   | timestamp without time zone |           |          |
         uid             | uuid                        |           |          |
        Indexes:
            "members_jobs_offer_id_key" UNIQUE CONSTRAINT, btree (id)
            "members_jobs_offer_offer_code_key" UNIQUE CONSTRAINT, btree (offer_code)
        Foreign-key constraints:
            "members_jobs_offer_job_id_fkey" FOREIGN KEY (job_id) REFERENCES members_jobs(id)
            "members_jobs_offer_member_id_fkey" FOREIGN KEY (member_id) REFERENCES members(id)
            "members_jobs_offer_payment_id_fkey" FOREIGN KEY (payment_id) REFERENCES members_payments(id)
        Referenced by:
            TABLE "members_offer_interest" CONSTRAINT "members_offer_interest_offer_id_fkey" FOREIGN KEY (offer_id) REFERENCES members_jobs_offer(id)
            TABLE "members_payments" CONSTRAINT "members_payments_what_offer_fkey" FOREIGN KEY (what_offer) REFERENCES members_jobs_offer(id)


*/
long WrenchJobManagerOffers( CVars in, CVars &out){
  logfmt(logINFO, "ENTER CALL long WrenchJobManagerOffers");
    char vname[30];
    long ret = PHP_API_BAD_PARAM;
    const char * loc = getenv("REMOTE_ADDR");
    const PGresult *res;

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

        out["total_record"] = "0";
        res = pgsql_query("SELECT id FROM members_jobs_offer WHERE member_id = %lu AND status=1 AND expire > now() ", in["member_id"].Long());
        out["total_record"] = pgsql_num_rows(res);

        res = pgsql_query(" SELECT j.id AS job_id,jo.expire,jo.public_view, j.*,jo.uid AS offer_uid,jo.offer_code AS offer_code, j.uid AS job_uid,"
                            " (CASE WHEN jo.public_view > 0 THEN 'public' ELSE jo.email END)  AS job_to, j.job_type AS job_type, j.media_uid AS media_uid, "
                            " c.code AS currency_code, c.description AS currency_description,j.country,mf.uid AS family_uid, j.banner AS banner "
                            " FROM members_jobs_offer jo "
                            " LEFT JOIN members_jobs j ON j.id = jo.job_id "
                            " LEFT JOIN currency c ON c.country=j.country "
                            " LEFT JOIN members_family mf ON mf.family_member_id = jo.client_id "
                            " WHERE jo.expire > now() AND jo.status = 1 AND jo.member_id = %lu  AND jo.status=1 "
                            " ORDER BY jo.id DESC LIMIT %lu OFFSET %lu", in["member_id"].Long(), limit, offset);

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

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

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

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

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

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

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

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

                    snprintf(vname, sizeof (vname), "origin_job_uid_%05d", i); // added to support original job UID
                    out[vname] = rec["job_uid"];

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

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

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

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

                    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), "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";
         /*
         wrenchboard=> \d members_jobs
                                                   Table "public.members_jobs"
             Column     |            Type             | Collation | Nullable |                 Default
         ---------------+-----------------------------+-----------+----------+------------------------------------------
          id            | integer                     |           | not null | nextval('members_jobs_id_seq'::regclass)
          member_id     | integer                     |           |          |
          title         | character varying(150)      |           |          |
          description   | character varying(300)      |           |          |
          job_detail    | text                        |           |          |
          timeline_days | integer                     |           | not null |
          price         | integer                     |           | not null |
          loc           | inet                        |           |          |
          created       | timestamp without time zone |           |          | now()
          updated       | timestamp without time zone |           |          | now()
          status        | integer                     |           |          | 1
          country       | character varying(2)        |           |          |
          uid           | uuid                        |           |          | uuid_generate_v4()
         Indexes:
             "members_jobs_id_key" UNIQUE CONSTRAINT, btree (id)
         Foreign-key constraints:
             "members_jobs_country_fkey" FOREIGN KEY (country) REFERENCES country(code)
             "members_jobs_member_id_fkey" FOREIGN KEY (member_id) REFERENCES members(id)
         Referenced by:
             TABLE "members_jobs_offer" CONSTRAINT "members_jobs_offer_job_id_fkey" FOREIGN KEY (job_id) REFERENCES members_jobs(id)

         wrenchboard=>

         */

    } catch (bad_parameter) {
        logfmt(logINFO, "ERROR CALL long WrenchJobManagerOffers");
    }
return 0;
}

long WrenchJobListFiles(CVars in, CVars &out){
  logfmt(logINFO, "ENTER CALL long WrenchJobListFiles");
    char vname[30];
    long ret = PHP_API_BAD_PARAM;
    const char * loc = getenv("REMOTE_ADDR");
    const PGresult *res;

    try{

        REQ_STRING(in, "member_uid", 15, 155, "(.*)");
        REQ_STRING(in, "job_uid", 15, 155, "(.*)");
        REQ_STRING(in, "sessionid", 15, 155, "(.*)");

        out["total_record"] = "0";
        res = pgsql_query("SELECT id,uid,job_uid,originalname,size FROM members_jobs_files WHERE job_uid='%s'", in["job_uid"].c_str());

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

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

                    snprintf(vname, sizeof (vname), "size_%05d", i);
                    out[vname] = rec["size"];
              }
          }
          ret = PHP_API_OK;
          out["status"] = "OK";
    } catch (bad_parameter) {
        logfmt(logINFO, "ERROR CALL long WrenchJobListFiles");
    }
return 0;


}

long WrenchJobManagerList( CVars in, CVars &out){
  logfmt(logINFO, "ENTER CALL long WrenchJobManagerList");
    char vname[30];
    long ret = PHP_API_BAD_PARAM;
    const char * loc = getenv("REMOTE_ADDR");
    const PGresult *res;

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

        out["total_record"] = "0";
        res = pgsql_query("SELECT id FROM members_jobs WHERE member_id = %lu AND status=1 ORDER BY id DESC", in["member_id"].Long());
        out["total_record"] = pgsql_num_rows(res);

          res = pgsql_query("SELECT j.id AS job_id, j.*,c.code AS currency_code, c.description AS currency_description,j.created AS job_create_date "
                            " FROM members_jobs j "
                            " LEFT JOIN currency c ON c.country=j.country "
                            " WHERE j.member_id = %lu  AND j.status=1 "
                            " ORDER BY j.id DESC LIMIT %lu OFFSET %lu", in["member_id"].Long(), limit, offset);

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

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

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

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

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

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

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

                    snprintf(vname, sizeof (vname), "job_country_%05d", i);
                    out[vname] = rec["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"];

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

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

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

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

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


              }
          }
          ret = PHP_API_OK;
          out["status"] = "OK";
         /*


                                 'job_country' => $out["job_country_${key}"],
                                 'currency' => 'Naira',
                                 'currency_code' => 'NGN',
                                 c.description AS currency_description

         wrenchboard=> \d members_jobs
                                                   Table "public.members_jobs"
             Column     |            Type             | Collation | Nullable |                 Default
         ---------------+-----------------------------+-----------+----------+------------------------------------------
          id            | integer                     |           | not null | nextval('members_jobs_id_seq'::regclass)
          member_id     | integer                     |           |          |
          title         | character varying(150)      |           |          |
          description   | character varying(300)      |           |          |
          job_detail    | text                        |           |          |
          timeline_days | integer                     |           | not null |
          price         | integer                     |           | not null |
          loc           | inet                        |           |          |
          created       | timestamp without time zone |           |          | now()
          updated       | timestamp without time zone |           |          | now()
          status        | integer                     |           |          | 1
          country       | character varying(2)        |           |          |
          uid           | uuid                        |           |          | uuid_generate_v4()
         Indexes:
             "members_jobs_id_key" UNIQUE CONSTRAINT, btree (id)
         Foreign-key constraints:
             "members_jobs_country_fkey" FOREIGN KEY (country) REFERENCES country(code)
             "members_jobs_member_id_fkey" FOREIGN KEY (member_id) REFERENCES members(id)
         Referenced by:
             TABLE "members_jobs_offer" CONSTRAINT "members_jobs_offer_job_id_fkey" FOREIGN KEY (job_id) REFERENCES members_jobs(id)

         wrenchboard=>

         */

    } catch (bad_parameter) {
        logfmt(logINFO, "ERROR CALL long WrenchJobManagerList");
    }
return 0;
}



long WrenchJobManagerActiveTasksList(CVars in, CVars &out) {
    logfmt(logINFO, "WrenchJobManagerActiveTasksList()");
    char vname[30];
    char status_filter[300];
    char status_no_filter[300];
    char extra_filter[300];
    long ret = PHP_API_BAD_PARAM;

    try {
         long member_id = REQ_LONG(in, "member_id", 1, -1);
         long offset = REQ_LONG(in, "offset", 1, -1);
         long limit = REQ_LONG(in, "limit", 1, -1);
         OPTIONAL(in, "family_uid") REQ_STRING(in, "family_uid", 5, 55, "(.*)");

        out["total_record"] = "0";

        // Prepare more filters
        snprintf(extra_filter, sizeof (extra_filter), " "); // just make sure it is just space when not needed
        const PGresult *res0;
        if (in["family_uid"]!=""){
           res0 = pgsql_query("SELECT family_member_id AS client_id  "
                             " FROM members_family WHERE member_id = %lu "
                             " AND uid ='%s'", in["member_id"].Long(), in["family_uid"].c_str());
               if (res0 != NULL && pgsql_num_rows(res0) > 0) {
                  map<const char*, const char*>f1 = pgsql_fetch_assoc(res0, 0);
                    CVars res0;
                    map_to_cvars(f1, res0);
                     snprintf(extra_filter, sizeof (extra_filter), " AND mc.client_id = %lu  ",res0["client_id"].Long());

               }
        }
/*
        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 %s AND mc.status IN (1,2,4) AND mc.delivery_date > now() "
                "  ORDER BY mc.id DESC LIMIT %lu OFFSET %lu", in["member_id"].Long(),extra_filter, limit, offset);
*/

       snprintf(status_filter, sizeof (status_filter), " AND mc.delivery_date > now() ");
       if (in["job_mode"]=="PASTDUE"){
           snprintf(status_filter, sizeof (status_filter), " AND mc.delivery_date < now() ");
       }

       snprintf(status_no_filter, sizeof (status_no_filter), " AND mc.status IN (1,2,4) ");
       if (in["job_mode"]=="REVIEW"){
           snprintf(status_no_filter, sizeof (status_no_filter), " AND mc.status = 4 ");
           snprintf(status_filter, sizeof (status_filter), "  ");
       }



        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.uid AS job_uid, "
                "  mj.title, mj.description AS description,mc.job_detail AS job_description, mc.uid AS contract_uid,mj.banner AS banner, mj.job_type AS job_type,  mj.media_uid AS media_uid, "
                " (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 'PASTDUE' "
                "  ELSE 'OTHERS' END)  AS status_description,mc.delivery_date, mc.ext_request AS ext_request, "
                "  (CASE WHEN mc.member_id = %lu THEN 'OWNER' ELSE 'WORKER' END) AS owner_status, m.firstname AS job_to, "
                "  c.code AS currency_code, c.description AS currency_description,mj.country, mf.uid AS family_uid "
                "  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  "
                "  LEFT JOIN members_family mf ON mf.family_member_id = mc.client_id "
                "  LEFT JOIN currency c ON c.country=mj.country "
                "  WHERE mc.member_id =%lu %s %s %s AND mc.refund_date IS NULL AND mc.status <> 7 "
                "  ORDER BY mc.id DESC LIMIT %lu OFFSET %lu", member_id, member_id ,extra_filter, status_no_filter,  status_filter, limit, offset);
//ORDER BY id DESC LIMIT %lu OFFSET %lu", in["member_id"].Long(), limit, offset);
        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), "family_uid_%05d", i);
                out[vname] = rec["family_uid"];

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

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

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

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

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

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

                snprintf(vname, sizeof (vname), "origin_job_uid_%05d", i); // added to support original job UID
                out[vname] = rec["job_uid"];

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

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

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

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

                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 WrenchJobManagerActiveTasksList(CVars in, CVars &out)");
    }
    logfmt(logINFO, "/WrenchJobManagerActiveTasksList()");
    return ret;



}

long WrenchUsersActiveTasksList(CVars in, CVars &out) {
    logfmt(logINFO, "WrenchJobManagerActiveTasksList()");
    char extraq[60];
     char extraq2[160];
    char vname[30];
    long ret = PHP_API_BAD_PARAM;

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

         long recent_past_due = REQ_LONG(in, "recent_past_due", 1, -1);



        if ( allstatus ==  100 ){
           snprintf(extraq, sizeof (extraq), "");
        }
        else
        {
           snprintf(extraq, sizeof (extraq), " AND mc.delivery_date > now() ");
        }

        if ( recent_past_due ==  100 ){
            snprintf(extraq, sizeof (extraq), "");
            snprintf(extraq2, sizeof (extraq2), " AND mc.delivery_date< now() AND mc.delivery_date >  ( now() - interval '1440 minutes' ) ");
        }
        else
        {
            snprintf(extraq2, sizeof (extraq2), "");
        }

        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,mc.strict_timeline, "
                "  mj.title, mj.description AS description,mc.job_detail AS job_description,mc.uid AS contract_uid, mj.job_type AS job_type, mj.media_uid AS media_uid, "
                "  mj.banner AS banner, c.code AS currency_code, c.description AS currency_description, mj.uid AS job_uid, (mc.delivery_date - interval ' 10 hours') AS minimum_due,"
                " (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 'PASTDUE' "
                "  ELSE 'Others' END)  AS status_description,mc.delivery_date,  "
                "  (CASE WHEN mc.member_id = %lu THEN 'OWNER' ELSE 'WORKER' END) AS owner_status, mc.ext_request AS ext_request "
                "  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  "
                "  LEFT JOIN currency c ON c.country=mj.country "
                "  WHERE mc.client_id =%lu AND mc.status IN (1,2,4) %s %s"
                "  ORDER BY mc.id DESC LIMIT %lu OFFSET %lu",member_id, member_id,extraq,extraq2, limit, offset);
//ORDER BY id DESC LIMIT %lu OFFSET %lu", in["member_id"].Long(), limit, offset);
        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["contract_id"];

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

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

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

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

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

				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), "origin_job_uid_%05d", i); // added to support original job UID
                out[vname] = rec["job_uid"];

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

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

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

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

                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), "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 WrenchJobManagerActiveTasksList(CVars in, CVars &out)");
    }
    logfmt(logINFO, "/WrenchJobManagerActiveTasksList()");
    return ret;



}

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

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

        if ( allstatus ==  100 ){
           snprintf(extraq, sizeof (extraq), "");
        }
        else
        {
         //  snprintf(extraq, sizeof (extraq), " AND mc.delivery_date > now() ");
        }

        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,mc.uid AS contract_uid, "
                "  mj.banner AS banner, c.code AS currency_code, c.description AS currency_description, mj.uid AS job_uid, "
                " (CASE WHEN mc.status=4 THEN 'REVIEW' "
                "  WHEN mc.status = 5  THEN 'COMPLETED' "
                "  WHEN mc.status = 1 AND mc.delivery_date <now() THEN 'PASTDUE' "
                "  ELSE 'Others' END)  AS status_description,mc.delivery_date,  "
                "  (CASE WHEN mc.member_id = %lu THEN 'OWNER' ELSE 'WORKER' END) AS owner_status, mc.ext_request AS ext_request "
                "  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  "
                "  LEFT JOIN currency c ON c.country=mj.country "
                "  WHERE mc.client_id =%lu AND mc.status IN (5) %s "
                "  ORDER BY mc.id DESC LIMIT %lu OFFSET %lu",member_id, member_id,extraq, limit, offset);
//ORDER BY id DESC LIMIT %lu OFFSET %lu", in["member_id"].Long(), limit, offset);
        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["contract_id"];

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

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

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

				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), "origin_job_uid_%05d", i); // added to support original job UID
                out[vname] = rec["job_uid"];

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

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

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

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

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

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



}

