<?php

include '../../core/backend.php';
include_once '../config.php';
include_once '../constants.php';
include '../formarter.php';

include_once 'functions.php';
include_once 'functions_gps.php';
include_once 'userfunc/user_card_behaviors.php';
include_once 'userfunc/user_cards.php';
include_once 'php_userlogin.php';

$endpoints = array(
    'createuser' => array('POST'),
    'userlogin' => array('POST'),
    'tracklocation' => array('POST'),
    'savecardpayment' => array('POST'),
    'getcardpaymentlist' => array('POST'),
    'managepaymentlist' => array('POST'),
    'loadprofile' => array('POST'),
    'updateprofile' => array('POST'),
    'verifysession' => array('POST'),
    "refreshsession" => array('POST'),
    'linkemail' => array('POST'),
    'listlinkedemail' => array('POST'),
    'refreshlinkemail' => array('POST'),
    'usertransportlist' => array('POST'),
    'usertransportprofile' => array('POST'),
    'getdashcarddata' => array('POST'),
    'loadsavedcards' => array('POST'),
    'savedashcard' => array('POST'),
    'saveuserbudget' => array('POST'),
    'resetpass' => array('POST'),
    'settingsarray' => array('POST'),
    'loadsubsription' => array('POST'),
    'subscriptionstatus' => array('POST'),
    'getapplist' => array('POST'),
    'getslidecarddata' => array('POST'),
    'subscribedcarddata' => array('POST'),
    'subscribecard' => array('POST'),
    "savesurvey" => array('POST'),
    "pointsdetail" => array('POST'),
    "loadredeemabale" => array('POST'),
    "redeempoints" => array('POST'),
    "managefeature" => array('POST'),
    "carpool" => array('POST'),
    'logout' => array('POST'),
    "carpoolstatus" => array('POST'),
    "getsavedtrips" => array('POST'),
    "savedtrip" => array('POST'),
    "removesavedtrip" => array('POST'),
    "trackcardclick" => array('POST'),
    "membersettings" => array('POST'),
    "persnoality" => array('POST'),
);
/*
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, client_id, x-devicetoken, x-float-device-location-latitude, x-float-device-location-longitude, x-session-id");
header("Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS");
header('Content-type: application/json');
 */

header("Access-Control-Allow-Origin: *");
header("Access-Control-Expose-Headers: Access-Control-Allow-Origin");
#Header('Access-Control-Allow-Headers: *');
#header("Access-Control-Allow-Headers: Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With, client_id");
header("Access-Control-Allow-Headers: Cache-Control, Pragma, Origin, Authorization, Content-Type, X-Requested-With, client_id, x-devicetoken, x-float-device-location-latitude, x-float-device-location-longitude, x-session-id");
header("Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS");
header('Content-type: application/json');

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

$headers = getallheaders();
if ((!isset($headers["authorization"]) || substr($headers["authorization"], -strlen($httpAuthToken)) != $httpAuthToken) &&
    (!isset($headers["Authorization"]) || substr($headers["Authorization"], -strlen($httpAuthToken)) != $httpAuthToken)) {
    header('HTTP/1.1 401 Unauthorized');
    header('Status: 401 Unauthorized');
    echo "{\"status\":\"Missing authorization\"}";
    exit();
}

$endpoint = strtolower(str_replace('/SAVVY/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\"}";
    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();
}

include '../rest_api.php';

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    if ($endpoint == "uploadfile") {
        upload_file_call();
        exit();
    } else {
        $raw_json = file_get_contents("php://input");
        $raw_array = json_decode($raw_json, true);
        if ($endpoint == "createuser") {
            $in = $raw_array;
        } else {
            $in = flatten($raw_array);
        }
    }
}

if ($_SERVER["REQUEST_METHOD"] == "PUT") {
    parse_str(file_get_contents('php://input'), $in);
}

// Decrypt the input
if (isset($in['encrypted_payload'])) {
    $payload = openssl_decrypt(hex2bin($in['encrypted_payload']), $encryptionAlg, $encryptionKey, OPENSSL_RAW_DATA, $encryptionIV);
    unset($in['encrypted_payload']);
    $in = array_merge($in, json_decode($payload, true));
}

// get who is connecting IP
$in["loc"] = getRemoteIpAddress(); // Do not use $_SERVER["REMOTE_ADDR"]; it is INVALID!!!
$in["pid"] = 100;
// override session parameter(s) with the header value
$in["session"] = $headers["x-session-id"];
$in["sessionid"] = $headers["x-session-id"];

$out = array();

$extension_call = true; // by defualt unless specified at the gate
switch ($endpoint) {

    case 'createuser':$in["action"] = SAVVY_USER_CREATEACCOUNT;
        if (!isset($in["web"])) {
            $in["web"] = 100001;
        }
        break;
    case 'userlogin':
        //$extension_call = false;
        $in["action"] = SAVVY_USER_LOGINACCOUNT;
        LogLocationArray($out);
        //php_userlogin($in, $out);
        break;
    case 'tracklocation':$in["action"] = SAVVY_USER_TRACKLOCATION;
        $extension_call = false;
        LogLocationArray($in);
        $out = save_tracked($in);
        break;
    case 'savecardpayment':$in["action"] = SAVVY_USER_SAVECARDPAYMT;
        break;

    case 'getcardpaymentlist':$in["action"] = SAVVY_USER_GETCARDPMYLIST;
        break;
    case 'managepaymentlist':$in["action"] = SAVVY_USER_MANAGEPAYLIST;
        break;

    case 'loadprofile':$in["action"] = SAVVY_USER_LOADUSERPROFILE;
        break;
    case 'updateprofile':$in["action"] = SAVVY_USER_UPDATEUSERPROFILE;
        $notwanted = array("{", "[", "]", "}", ".", ":", "*", "(", ")");
        $in["firstname"] = str_replace($notwanted, "", $in["firstname"]);
        $in["lastname"] = str_replace($notwanted, "", $in["lastname"]);
        break;
    case 'verifysession':$in["action"] = SAVVY_USER_VERIFYSESSION;
        $in["limit"] = 100;
        break;
    case 'refreshsession':
        $in["action"] = SAVVY_USER_REFRESHSESSION;
        break;
    case 'resetpass':$in["action"] = SAVVY_USER_RESETPASS;
        $in["member_id"] = 0; // we dont know you
        $in["sessionid"] = "PASSWORD_RESET_SESSION";
        $in["limit"] = 100;
        break;
    case 'logout':
        break;
    case 'linkemail':
        $extension_call = false;
        saveLinkedMail($in, $out);
        break;

    case 'listlinkedemail':
        $extension_call = false;
        $out = ListLinkedEmail($in);
        break;

    case 'refreshlinkemail':
        $extension_call = false;
        sync_extCall($in, $out);
        break;
    case 'usertransportlist':
        $in["action"] = SAVVY_USER_TRANSPORTLIST;
        break;

    case 'usertransportprofile':
        $in["action"] = SAVVY_USER_TRANSPORTPROFILE;
        break;
    case 'getdashcarddata':
        $in["action"] = SAVVY_USERCARD_DASHCARD;
        break;

    case 'saveuserbudget':
        $in["action"] = SAVVY_USER_SAVEBUDGET;
        break;

    case 'savedashcard':
        $in["action"] = SAVVY_USERSAVE_DASHCARD;
        $extension_call = false;
        saveDashCard($in, $out);
        break;

    case 'loadsavedcards':
        $in["action"] = SAVVY_USERLOAD_SAVEDCARDS;
        $extension_call = false;
        loadSavedCard($in, $out);
        break;

    case 'settingsarray':
        $in["action"] = SAVVY_USERPROP_SETTINGSARRAY;
        break;

    case 'loadsubsription':
        $in["action"] = SAVVY_USERSUSC_LOAD;
        break;

    case 'subscriptionstatus':
        $in["action"] = SAVVY_USERSUSC_STATUS;
        break;
    case 'getapplist':
        $in["action"] = SAVVY_USERSAPP_GETLIST;
        break;
    case 'subscribedcarddata':
        $in["action"] = SAVVY_USERSAPP_SLIDECARD;
        $in["card_type"] = 55000;
        $extension_call = false;
        loadSliderCard($in, $out);
        break;
    case 'getslidecarddata':
        $in["action"] = SAVVY_USERSAPP_SLIDECARD;
        $extension_call = false;
        loadSliderCard($in, $out);
        break;
    case 'subscribecard':
        $in["action"] = SAVVY_USERSAPP_DEALSUB;
        break;
    case 'savesurvey':
        $in["action"] = SAVVY_USERSAPP_SURVEY;
        break;
    case 'loadredeemabale':
        $in["action"] = SAVVY_USERSAPP_LOADREDEEM;
        break;
    case 'redeempoints':
        $in["action"] = SAVVY_USERSAPP_REDEEMPPOINTS;
        break;
    case 'pointsdetail':
        $in["action"] = SAVVY_USERSAPP_POINTSDEATAIL;
        break;
    case 'managefeature':
        $in["action"] = SAVVY_USER_ENABLEFEATURE;
        break;
    case 'carpool':
        $in["action"] = SAVVY_CARPOOL_SUBSCRIBE;
        break;
    case 'carpoolstatus':
        $in["action"] = SAVVY_CARPOOL_STATUS;
        break;
    case 'getsavedtrips':
        $in["action"] = SAVVY_USER_GETSAVEDTRIPS;
        break;
    case 'savedtrip':
        $in["action"] = SAVVY_USER_SAVEUPDTTRIP;
        break;
    case 'removesavedtrip':
        $extension_call = false;
        $out = removeSavedTrip($in);
        break;
    case "trackcardclick":
        $in["action"] = SAVVY_USERSAPP_TRACKCARDCLICK;
        $extension_call = false;
        userTrackCardClick($in, $out);
        break;
    case "membersettings":

        break;
    case "persnoality":
        // #define  SAVVY_USER_PSERSONALITY        22011
        $in["action"] = SAVVY_USER_PSERSONALITY;
        break;
}

$in["pid"] = 100;

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

if ($extension_call == true) {
    Fextension_call($in, $out);
}

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

$payload = json_encode(processOutJson($in, $out));
#d($payload);
//echo $payload."\n";
$encrypted_payload = bin2hex(openssl_encrypt($payload, $encryptionAlg, $encryptionKey, OPENSSL_RAW_DATA, $encryptionIV));
echo "{\"payload\": \"${encrypted_payload}\"}";
exit();

// vi:ts=2
