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

$endpoints = array(
    'apigate' => array('POST'),
    'generics' => array('POST'),
    'createuser' => array('POST'),
    'createmobileuser' => array('POST'),
    'completemobileuser' => array('POST'),
    'startresetpasword' => array('POST'),
    'userlogin' => array('POST'),
    'startjoblist' => array('POST'),
    'dashdata' => array('POST'),
    'getjobsdata' => array('POST'),
    'offerslist' => array('POST'),
    'activejoblist' => array('POST'),
    'loadprofile' => array('POST'),
    'account' => array('POST'),
    'message' => array('POST'),
    'pendingjob' => array('POST'),
    'paymenthx' => array('POST'),
    'getjob' => array('POST'),
    'mybanklist' => array('POST'),
    'sendmoney' => array('POST'),
    'sendinterest' => array('POST'),
    'sendmoneyfee' => array('POST'),
    'getpendingjobs' => array('POST'),
    'taskmessage' => array('POST'),
    'sendtaskmessage' => array('POST'),
    'getwallets' => array('POST'),
    'sitecontact' => array('POST'),
    'signupcountry' => array('POST'),
    'userscards' => array('POST'),
    'blogdata' =>  array('POST'),
    'blogitem' =>  array('POST'),
    'couponhx' =>  array('POST'),
    'couponpending' =>  array('POST'),
    'couponredeem' =>  array('POST'),
    'sendinterestmessage' =>  array('POST'),
    'replyinterestmessage' => 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();
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $in = flatten(json_decode(file_get_contents('php://input'), true));
}
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 '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 '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 '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 'getjobsdata': $in["action"] = WRENCHBOARD_ACCOUNT_JOBLIST;
        break;

    case 'userlogin': $in["action"] = WRENCHBOARD_ACCOUNT_LOGIN;
          $in["login_mode"] = MOBILE_LOGIN; 
        break;

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

    case 'loadprofile': $in["action"] = WRENCHBOARD_MOBILE_LOADPROFILE;
        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;
        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 'getwallets': $in["action"] = WRENCHBOARD_ACCOUNT_WALLETS;
        break;
}



$in["pid"] = 100;

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

$out = array();
if ( $call_backend ==  true){
   $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;
}


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
