<?php
/*
 * USER DATA API END POINT
 *
 */
include '../../../backend.php';
include 'constants.php';
include 'formarter.php';
include 'UploadManager.php';

$endpoints = array(
    'apigate' => array('POST'),
    'generics' => array('POST'),
    'createuser' => array('POST'),
    'homebanners' => array('POST'),
    'verifysignuplink' => array('POST'),
    'completesignuplink'=> array('POST'),
    'createmobileuser' => array('POST'),
    'completemobileuser' => array('POST'),
    'startresetpasword' => array('POST'),
    'stepresetpass' => array('POST'),
    'userlogin' => array('POST'),
    'authlogin' => array('POST'),
    'startjoblist' => array('POST'),
    'dashdata' => array('POST'),
    'getjobsdata' => array('POST'),
    'offerslist' => array('POST'),
    'offersresponse' => array('POST'),
    'activejoblist' => array('POST'),
    'loadprofile' => array('POST'),
    'updateprofile'=> array('POST'),
    'account' => array('POST'),
    'message' => array('POST'),
    'pendingjob' => array('POST'),
    'paymenthx' => array('POST'),
    'purchasehx' => array('POST'),
    'couponhx' =>  array('POST'),
    'getjob' => array('POST'),
    'mybanklist' => array('POST'),
    'countrybanks' => array('POST'),
    'sendmoney' => array('POST'),
    'sendinterest' => array('POST'),
    'sendmoneyfee' => array('POST'),
    'getpendingjobs' => array('POST'),
    'taskmessage' => array('POST'),
    'sendtaskmessage' => array('POST'),
    'activejobmsglist' => array('POST'),
    'getwallets' => array('POST'),
    'sitecontact' => array('POST'),
    'signupcountry' => array('POST'),
    'userscards' => array('POST'),
    'blogdata' =>  array('POST'),
    'blogitem' =>  array('POST'),
    'couponpending' =>  array('POST'),
    'couponredeem' =>  array('POST'),
    'sendinterestmessage' =>  array('POST'),
    'replyinterestmessage' => array('POST'),
    'disableaccount' => array('POST'),
    'myjobs' => array('POST'),
    'recipients' => array('POST'),
    'addrecipient' => array('POST'),
    'sendreferral' => array('POST'),
    'refferhx' => array('POST'),
    'accounttypes' => array('POST'),
    'jobmanageragree' => array('POST'),
    'jobmanagerlist' => array('POST'),
    'jobmanageroffers' => array('POST'),
    'jobmanageractive' => array('POST'),
    'jobmanagercreatejob' => array('POST'),
    'jobmanagerupdatejob' => array('POST'),
    'jobmanagerdeletejob' => array('POST'),
    'activetaskslist' => array('POST'),
    'profilepasschange' => array('POST'),
    'starttopup' => array('POST'),
    'familylist' => array('POST'),
    'familyadd' => array('POST'),
    'familyupdate' => array('POST'),
    'familymanage' => array('POST'),
    'pendingjobextend' => array('POST'),
    'pendingjobsendtome' => array('POST'),
    'pendingjobcancel' => array('POST'),
    'assigntask' => array('POST'),
    'resources'=> array('POST'),
    'uploads'=> array('POST'),
    'marketmessage'=> array('POST'),
    'marketinterest'=> array('POST'),
    'activejobstatus'=> array('POST'),
    'activetaskstatus'=> array('POST'),
    'offersinterestlist' => array('POST'),
    'faq' => array('POST'),
    'offersinterestproc' => array('POST'),
    'payprevcard' => array('POST'),
    'paynewcard' => array('POST'),
    'paylistcard' => array('POST'),
    'payremcard' => array('POST'),
);

$call_backend =  true; // sometimes we need to overwite the call to the extenstion API 
$local_out = [];       // use local out to send output when the result is not from the extenstion 
$ret = -1;

/*
  header("Access-Control-Allow-Origin: *");
  header("Access-Control-Allow-Headers", "Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
  header("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
  //header("Access-Control-Expose-Headers: Access-Control-Allow-Origin");
  header('Content-type: application/json');
  if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) {
  die();
  }
 */

header("Access-Control-Allow-Origin: *");
header("Access-Control-Expose-Headers: Access-Control-Allow-Origin");
header("Access-Control-Allow-Headers: Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With");
header("Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS");
header('Content-type: application/json');

if ("OPTIONS" === $_SERVER['REQUEST_METHOD']) {
    exit();
}

$endpoint = strtolower(str_replace('/svs/user/', '', strtok($_SERVER['REQUEST_URI'], '?')));

$id = 0; // update, get & delete actions require ID
//if (substr($endpoint, 0, 19) == 'gettransportrequest' || substr($endpoint, 0, 13) == 'updateprofile') {
//    $endpoint = strtok($endpoint, '/');
//    $id = strtok('/');
//}

if (!isset($endpoints[$endpoint])) {
    header('HTTP/1.1 400 Bad Request');
    header('Status: 400 Bad Request');
    echo "{\"status\":\"Invalid endpoint url WRB\"}";
    exit();
}

$methods = $endpoints[$endpoint];

if (array_search($_SERVER['REQUEST_METHOD'], $methods) === false) {
    header('HTTP/1.1 405 Method Not Allowed');
    header('Status: 405 Method Not Allowed');
    echo "{\"status\":\"Invalid request method\"}";
    exit();
}

$out = array();

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if ( $endpoint == 'uploads'){
        $local_out=["test_msg"=>'Yes the upload endpoint was hit******** 555'];
        $call_backend = false; // will be decided after file is saved
        //$out=[];
        $in = flatten(json_decode(file_get_contents('php://input'), true));
        //$in = json_decode($raw_json, true);
        $local_out["in_ec"] = $in;
        $in["call_backend"] = $call_backend;
        $in["system_primary_uploads"] =  getSiteConfigurations($wrenchboard,"system.primary_uploads");
        $out["system_primary_uploads"] = $in["system_primary_uploads"];
        $local_out["system_primary_uploads"] = $in["system_primary_uploads"];
        $out = reciveUpload($in, $local_out);
        $local_out["rr_ec"] = $out;
        $call_backend = $out["call_backend"];
        $in["message"] =  $out["message"];

    }
    else{
        if ($_SERVER["REQUEST_METHOD"] == "POST") {
            $in = flatten(json_decode(file_get_contents('php://input'), true));
        }
    }
   // $call_backend =  false;
    if (isset($_FILES) && is_array($_FILES) && count($_FILES)>0) {
        $in = array_merge($_POST,$_FILES);
    }
}


if ($_SERVER["REQUEST_METHOD"] == "PUT") {
    parse_str(file_get_contents('php://input'), $in);
}
if ($_SERVER["REQUEST_METHOD"] == "GET") {
    $in = $_GET;
}
$in["loc"] = $_SERVER["REMOTE_ADDR"];
switch ($endpoint) {
    case 'payprevcard':
        $in["action"] =  WRENCHBOARD_USER_USESAVEDCC;
        break;
    case 'paynewcard':
        $in["action"] =  WRENCHBOARD_USER_ADNEWCC;
        break;
    case 'paylistcard':
        // not ye
        break;
    case 'payremcard':
        // pending
        break;
    case 'offersinterestproc':
        $in= procOfferInterest($in);
        break;
    case 'faq':
        $local_out = faqData();
        $call_backend =  false;
        break;
    case 'offersinterestlist':
        $in["action"] =  WRENCHBOARD_JOB_OFFER_INTLIST;
        break;
    case 'activejobstatus':
    case 'activetaskstatus':
        $in = processJobStatus($in);
        break;
    case 'marketmessage':
        $in["action"] =  WRENCHBOARD_JOB_SEND_QUESTION;
        break;

    case 'marketinterest':
        $in["action"] =  WRENCHBOARD_JOB_SEND_INTEREST;
        break;

    case 'assigntask':
        $in["action"] =  WRENCHBOARD_JOB_OFFER_SYSTEM;
        break;

    case 'pendingjobextend':
        $in["action"] =  WRENCHBOARD_JOB_EXTEND_EXPIRE;
        break;

    case 'pendingjobsendtome':
        $in["action"] =  WRENCHBOARD_JOB_RESEND_MESSAGE;
        break;

    case 'pendingjobcancel':
        $in["action"] =  WRENCHBOARD_JOB_CANCEL_OFFER;
        break;

    case 'familylist':
        $in["action"] =  WRENCHBOARD_FAMILY_LIST;
        break;

    case 'activetaskslist':
        $in["action"] =  WRENCHBOARD_JOB_USERACTIVE;
        break;

    case 'familyadd':
        $in["action"] =  WRENCHBOARD_FAMILY_ADD;
        break;

    case 'familyupdate':
        $in["action"] =  WRENCHBOARD_FAMILY_UPDATE;
        break;

    case 'familymanage':
        $in["action"] =  WRENCHBOARD_FAMILY_MANAGE;
        break;
    case 'jobmanagercreatejob':
        $in["action"] =  WRENCHBOARD_JOB_CREATEJOB;
        $in["job_mode"] = ADD_JOB;
        break;
    case 'jobmanagerupdatejob':
        $in["action"] =  WRENCHBOARD_JOB_CREATEJOB;
        $in["job_mode"] = UPDATE_JOB;
        break;
    case 'jobmanageractive':
        $in["job_mode"] = $in["job_mode"] ?? "ACTIVE";
        $in["action"] =  WRENCHBOARD_JOB_ACTIVE;
        break;
    case 'jobmanagerdeletejob':
        $in["action"] =  WRENCHBOARD_JOB_DELETEJOB;
        break;
    case 'jobmanageroffers':
        $in["action"] =  WRENCHBOARD_JOB_OFFERS;
        break;
    case 'stepresetpass':
        if($in['step']==300){
            $in["action"] =  WRENCHBOARD_COMPLETE_PASSWORDRESET;
        }
        break;
    case 'starttopup':
        $in["action"] =  WRENCHBOARD_ACCOUNT_PREPARE_TOPUP;
        break;
    case 'profilepasschange':
        $in["action"] =  WRENCHBOARD_PROFILE_RESETPASS;
        break;
    case 'addrecipient':
        $in["action"] =  WRENCHBOARD_ACCOUNT_ADD_RECIPEINT;
        break;
    case 'jobmanageragree':
            $in["action"] =  WRENCHBOARD_JOB_POSTAGREE;
            break;
    case 'jobmanagerlist':
        $in["action"] =  WRENCHBOARD_JOB_LISTJOBS;
        break;
    case 'homebanners':
        $in["action"] =  WRENCHBOARD_ACCOUNT_HOMEBANNERS ;
        break;
    case 'verifysignuplink':
        $in["action"] =  WRENCHBOARD_VERIFY_PENDING_LINK ;
        break;
    case 'disableaccount':
        $in['action'] = WRENCHBOARD_USER_DELETEACC;
        break;
    case 'replyinterestmessage':
        $in["action"] =  WRENCHBOARD_JOB_REPLY_QUESTION;
        break;
    case 'sendinterestmessage':
       // $in['offer_code'] = $this->input->get('offer_code');
        $in['yourmessage'] = $in["question"];
        //$in['member_id'] = $_SESSION['member_id']; // just maing sure
        $in['msg_type'] = 'JOB';
       // $in['action'] = WRENCHBOARD_JOB_SEND_QUESTION;

        $in["action"] = WRENCHBOARD_JOB_SEND_QUESTION;
        break;
    case 'couponredeem':
        $in["action"] = WRENCHBOARD_COUPON_REDEEM;
        break;
    case 'couponpending':
        $in["action"] = WRENCHBOARD_COUPON_PENDLIST;
        break;
    case 'couponhx':
        $in["action"] = WRENCHBOARD_COUPON_MEMLIST;
        break;
    case 'signupcountry':
        // checi if in cache if not read
        $local_out = [
            'result'=>'100',
            'signup_country'=>[
                ['NG', 'Nigeria'],
                ['US', 'United States']
            ]
        ];
        $call_backend =  false;
        break;
    case 'blogitem':
        $blogData = getBlogItem();
        $local_out = [
            'result'=>'100',
            'blog_data'=> $blogData
        ];
        $call_backend =  false;
        break;
    case 'blogdata':
        $blogData = getBlogData();
        $local_out = [
            'result'=>'100',
            'blog_data'=> $blogData
        ];
        $call_backend =  false;
        break;
    case 'userscards':
        $in["action"] =  WRENCHBOARD_CARDS_GETCARDLIST;
        $local_out = [
            'result'=>'100',
            'result_list'=>[
                ['title'=>'This is your coupon',
                    'description'=>'This is the description of the description',
                    'card_type'=>'COUPON',
                    'card_style' =>'card1',
                    'card_icon' =>'icon1',
                    'assign_id'=> 0,
                    'Nigeria'],
                ['title'=>'A Recommended Story',
                    'description'=>'This is the description of the description',
                    'card_type'=>'BLOG',
                    'card_style' =>'card2',
                    'card_icon' =>'icon1',
                    'assign_id'=> 0,
                    'United States'],
                ['title'=>'You have a new task sent to you',
                    'description'=>'This is the description of the description',
                    'card_type'=>'NEWTASK',
                    'card_style' =>'card1',
                    'card_icon' =>'icon1',
                    'assign_id'=> 0,
                    'United States'],
                ['title'=>'You just Earned some token',
                    'description'=>'This is the description of the description',
                    'card_type'=>'TOKEN',
                    'card_style' =>'card2',
                    'card_icon' =>'icon1',
                    'assign_id'=> 0,
                    'United States']
            ]
        ];
        // $call_backend =  false;

        break;
    case 'myjobs': $in["action"] = WRENCHBOARD_ACCOUNT_JOBLIST;
        break;
    case 'sitecontact':
        $local_out =  ['result'=>'100','msg'=>'Received'];
        $call_backend =  false;
        break;
	case 'generics':
	case 'apigate':
	//$in["action"] = WRENCHBOARD_ACCOUNT_LOGIN;
	break;
    case 'startjoblist': $in["action"] = WRENCHBOARD_START_JOBLIST;
		if (!array_key_exists("limit",$in)) $in["limit"] = 10;
		if (!array_key_exists("page",$in))  $in["page"]  = 1;
        break;
		
    case 'createmobileuser': $in["action"] = WRENCHBOARD_CREATE_MOBILEUSER;
        $in["loc"] = $_SERVER["REMOTE_ADDR"];
        $in["news"] = 0;
        $in["terms"] = 1;
        $in["mobile"] = "MOBILE";
        break;
    case 'completemobileuser': $in["action"] = WRENCHBOARD_COMPLETE_MOBILEUSER;
        $in["loc"] = $_SERVER["REMOTE_ADDR"];
        break;
    case 'completesignuplink': $in["action"] = WRENCHBOARD_COMPLETE_MOBILEUSER;
        $in["loc"] = $_SERVER["REMOTE_ADDR"];
        break;
    case 'startresetpasword':
        $in["action"] = WRENCHBOARD_RESET_PASSWORD;
        break;
    case 'createuser': $in["action"] = WRENCHBOARD_ACCOUNT_PENDING;
        $in["street1"] = $in["streetaddress"];
        $in["zipcode"] = $in["zip"];
        $in["country"] = "US";
        $in["loc"] = $_SERVER["REMOTE_ADDR"];
        $in["mobile"] = "MOBILE";
        break;
    case 'activejoblist': $in["action"] = WRENCHBOARD_MOBILE_ACTIVEJOB;
        break;
    case 'message': $in["action"] = WRENCHBOARD_MOBILE_MESSAGE;
        break;
    case 'paymenthx': $in["action"] = WRENCHBOARD_MOBILE_PAYMENTHX;
        break;
    case 'purchasehx': $in["action"] = WRENCHBOARD_MOBILE_PURCHASEHX;
        break;
    case 'getjobsdata': $in["action"] = WRENCHBOARD_ACCOUNT_JOBLIST;
        break;

    case 'userlogin': $in["action"] = WRENCHBOARD_ACCOUNT_LOGIN;
        if (!isset($in["login_mode"])){
            $in["login_mode"] = MOBILE_LOGIN;
        }
        break;

    case 'dashdata': $in["action"] = WRENCHBOARD_ACCOUNT_DASHDATA;
        break;
    case 'offerslist': $in["action"] = WRENCHBOARD_MOBILE_OFFERSLIST;
        break;

    case 'offersresponse': $in["action"] = WRENCHBOARD_MOBILE_OFFERSRESP;
        break;

    case 'loadprofile': $in["action"] = WRENCHBOARD_MOBILE_LOADPROFILE;
        break;
    case 'updateprofile': $in["action"] = WRENCHBOARD_MOBILE_UPDATEPROFILE;
        break;
    case 'account': $in["action"] = WRENCHBOARD_MOBILE_ACCOUNT;
        break;
    case 'getpendingjobs':
        $in["action"] = WRENCHBOARD_ACCOUNT_PENDJOB;
        break;
    case 'pendingjob':

        break;
    case 'getjob':

        break;

    case 'mybanklist':$in["action"] = WRENCHBOARD_USER_GETBANKLIST;
        break;
    case 'sendmoney':$in["action"] = WRENCHBOARD_USER_SENDMONEY;
        $out["internal_return"] = 0;
        $in["InitiatingChannel"] = 7;
        $in["InitiatingPaymentMethodCode"] = "CA";
        $in["InitiatingCurrencyCode"] = '566'; // 566 - NRN - Naira
        $in["InitiatingEntityCode"] = "MBA";
        $in["transaction_id"] = "T" . rand(120000, 999999);
        $in["TerminatingPaymentMethodCode"] = "AC";
        $in["TerminatingCurrencyCode"] = '566'; // 566 - NRN - Naira
        $in["TerminatingCountryCode"] = 'NG'; // NG - Nigeria
        $in["bankid"] =  $in["recipientid"];
        $in["InitiatingAmount"] =  $in["amount"];
        $in["TerminatingAmount"] =  $in["amount"];
        break;
    case 'sendinterest':$in["action"] = WRENCHBOARD_USER_SENDJOBINT;
        $out["internal_return"] = 0;
        break;
    case 'sendmoneyfee': $in["action"] = WRENCHBOARD_SMONEY_PROCFEE;
        break;
    case 'taskmessage': $in["action"] = WRENCHBOARD_MOBILE_TASKMESSAGE;
        break;
    case 'sendtaskmessage': $in["action"] = WRENCHBOARD_MOBILE_SENDTASKMESSAGE;
        break;
    case 'activejobmsglist':
        $in["action"] =  WRENCHBOARD_CONTRACT_MSGLIST;
        break;
    case 'getwallets': $in["action"] = WRENCHBOARD_ACCOUNT_WALLETS;
        break;

    case WRENCHBOARD_ACCOUNT_PRICE_COMBO:    break ;  //    11171);
    case WRENCHBOARD_ACCOUNT_JOBPOST_DURATION:    break ;  //11173);
    case 'recipients': $in["action"] =WRENCHBOARD_ACCOUNT_USER_RECIPEINT;  break;  // 11175);
    case 'accounttypes': $in["action"] = WRENCHBOARD_ACCOUNT_ACCOUNT_TYPES;    break ;  //  11177);
    case WRENCHBOARD_ACCOUNT_COUNTRY_COMBO:    break ;  //  11179);
    case WRENCHBOARD_ACCOUNT_JOB_COUNTRY:    break ;  //    11181);
    case 'sendreferral': $in["action"] =WRENCHBOARD_ACCOUNT_SENDREFER;  break;
    case 'refferhx': $in["action"] = WRENCHBOARD_ACCOUNT_REFFERHX; break;
    case 'countrybanks':    $in["action"] =WRENCHBOARD_ACCOUNT_COUNTRY_BANKS; break;

}


$in["pid"] = 100;

//file_put_contents("in_debug.log", $in); // DEBUG


if ( $call_backend ==  true && $in["action"] !='' ){
   $ret = $wrenchboard->wrenchboard_api($in, $out);
   $out['internal_return'] = $ret; // this is reserved array parameter - to be captured and received before you use the out array()
}  
else
{
    $out =  $local_out;
    $out['internal_return'] = 100; // to match the other
}

function getSiteConfigurations($wrenchboard,$config_item){
    return  $wrenchboard->cfgReadChar($config_item);
}

function faqData(){

    $total = 8;

    $data = array(
        "status" => 100,
        "total_record" => ($total - 1),
        "internal_return" => 0,
        "result_list" => array(),
    );
    for ($i = 0; $i < $total; $i++) {
        $key = sprintf("%05d", $i);
        $data["result_list"][] = array(
            "title" => "This is faq title dummy text ".$key,
            "msg" => "Random gibberish text to use in web pages, site templates and in typography demos. Get rid of Lorem Ipsum forever. A tool for web designers who want to save time. ".$key,
        );
    }

   return $data;
}

 function procOfferInterest($in) {
    $proc = $in['proc'];
    $in['interest'] = 0;
    switch ($proc) {
        case 'ACCEPT':
            $in['interest'] = JOB_INTEREST_ACCEPT;
            break;

        case 'REJECT':
            $in['interest'] = JOB_INTEREST_REJECT;
            break;

        case 'CANCEL':
            $in['interest'] = JOB_INTEREST_CANCEL;
            break;
    }
     $in["action"] =  WRENCHBOARD_JOB_PROC_INTEREST;
    return $in;

}
 function processJobStatus($data) {

    /*$data['member_id'] = $_SESSION['member_id']; // = $ret->email;
    $data['proc'] = $this->input->get('proc');
    $data['job_id'] = $this->input->get('jobID');
    $data['job_contract'] = $this->input->get('job_contract');
    $data['extension']
    */

    $data['job_action'] = 0;
    switch ($data['job_action']) {
        case 'NOTIFY_COMPLETE':  // notify completed
            $data['job_action'] = CONTRACT_NOTIFY_COMPLETE;
            break;
        case 'REQUEST_CANCEL':  // request cancel
            $data['job_action'] = CONTRACT_REQUEST_CANCEL;
            break;

        case 'ACCEPT_COMPLETE':
            $data['job_action'] = CONTRACT_ACCEPT_COMPLETE;
            break;
        case 'REJECT_COMPLETE':
            $data['job_action'] = CONTRACT_REJECT_COMPLETE;
            break;
        case 'EXTEND_TIMELINE':
            $data['job_action'] = CONTRACT_EXTEND_TIMELINE;
            break;
        case 'CANCEL_CONTRACT':
            $data['job_action'] = CONTRACT_CANCEL_CONTRACT;
            break;
    }
    $data['action'] = WRENCHBOARD_CONTRACT_STATUS;

    return $data;
}
// system.primary_uploads

header("HTTP/1.1 200 OK");
header("Status: 200 OK");
//$out = array_merge($in, $out); // DEBUG
echo json_encode(processOutJson($in, $out));
exit();

function flatten($data, $parentkey = "") {
    $result = array();
    foreach ($data as $key => $val) {
        if (is_array($val)) {
            $result = array_merge($result, flatten($val, $parentkey . $key . "_"));
        } else {
            $result[$parentkey . $key] = $val;
        }
    }
    return $result;
}


// vi:ts=2
