<?php

/*
 * THIS IS AGENT INDEX FILE - THE CALL CAME FROM -
 * https://{SERVER_NAME}/agent/agentlogin
 */
include '../config.php';
include '../constants.php';

$endpoints = array(
    'createagent' => array('POST'),
    'agentlogin' => array('POST'),
    'updateprofile' => array('PUT'),
    'createtransportrequest' => array('POST'),
    'gettransportrequest' => array('GET'),
    'gettransportlist' => array('POST'),
    'verifysession' => array('POST'),
    'listtransport' => array('POST'),
    'addinterpreter' => array('POST'),
    'listinterpreters' => array('POST'),
    'listtransportlocation' => array('POST'),
    'addtransportlocation' => array('POST'),
    'editinterpreter' => array('POST'),
    'getinterpreter' => array('POST'),
    'editlocation' => array('POST'),
    'getlocation' => array('POST'),
    'getsupportedlanguage' => array('POST'),
    'uploadfile' => array('POST'),
    'download' => array('POST'),
    'interpreterlang' => array('POST'),
    'getinterpreterlanguage' => array('POST'),
    'getagentlanguage' => array('POST'),
    'createdriver' => array('POST'),
    'getdriverslist' => array('POST'),
    'updatedriver' => array('POST'),
    'updatedriverstatus' => array('POST'),
    'getdevicelist' => array('POST'),
    'transportstatus' => array('POST'),
    'getinvoice' => array('POST'),
    'getreason' => array('POST'),
    'gettranslationlist' => array('POST'),
    'translationstatus' => array('POST'),
    'getprofile' => array('POST')
);





header("Access-Control-Allow-Origin: *");
header("Access-Control-Expose-Headers: Access-Control-Allow-Origin");
header('Content-type: application/json');

$endpoint = strtolower(str_replace('/agent/', '', 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 if ($endpoint == "download") {
        download_file_call();
        exit();
    } else {
        $in = flatten(json_decode(file_get_contents('php://input'), true));
    }
}

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);
}

switch ($endpoint) {
    case 'createagent': $in["action"] = MOBIDELIV_TRANSP_CREATE;
        $in["street1"] = $in["streetaddress"];
        $in["country"] = "US";
        $in['login'] = 1; // login forced
        $in["loc"] = $_SERVER["REMOTE_ADDR"];
        break;
    case 'agentlogin': $in["action"] = MOBIDELIV_TRANSP_LOGIN;
        break;
    case 'updateprofile': $in["action"] = MOBIDELIV_USER_PROFILE;
        $in["member_id"] = $id;
        $in["street1"] = $in["streetaddress"];
        $in["zipcode"] = $in["zip"];
        $in["country"] = "US";
        $in["loc"] = $_SERVER["REMOTE_ADDR"];
        break;
    case 'getprofile': $in["action"] = MOBIDELIV_TRANSP_AGENTPROFILE;
        break;
    case 'createtransportrequest': $in["action"] = MOBIDELIV_USER_REQUEST_TRAN;
        break;
    case 'gettransportrequest': $in["action"] = 0;
        $in["id"] = $id;
        break;
    case 'gettransportlist': $in["action"] = MOBIDELIV_TRANSP_GET_TRANSLIST;
        break;
    case 'verifysession': $in["action"] = MOBIDELIV_TRANSP_VERIFYSESSION;
        break;
    case 'addinterpreter': $in["action"] = MOBIDELIV_TRANSP_ADD_TRANSLATOR;
        break;
    case 'listinterpreters': $in["action"] = MOBIDELIV_TRANSP_LIST_TRANSLATOR;
        break;
    case 'getinterpreter': $in["action"] = MOBIDELIV_TRANSP_GET_TRANSLATOR;
        break;
    case 'editinterpreter': $in["action"] = MOBIDELIV_TRANSP_EDIT_TRANSLATOR;
        break;
    case 'addtransportlocation': $in["action"] = MOBIDELIV_TRANSP_ADDLOCATION;
        break;
    case 'listtransportlocation': $in["action"] = MOBIDELIV_TRANSP_LISTLOCATION;
        break;
    case 'editlocation': $in["action"] = MOBIDELIV_TRANSP_EDITLOCATION;
        break;
    case 'getlocation': $in['action'] = MOBIDELIV_TRANSP_GET_TRANSPORTER;
        break;
    case 'getsupportedlanguage': $in['action'] = MOBIDELIV_USER_GET_LANGUAGE;
        break;
    case 'interpreterlang': $in['action'] = MOBIDELIV_TRANSP_MANAGELANGUAGE;
        break;
    case 'getinterpreterlanguage': $in['action'] = MOBIDELIV_TRANSP_LANGUAGELIST;
        break;
    case 'getagentlanguage': $in['action'] = MOBIDELIV_TRANSP_AGENTLANGUAGE;
        break;
    case 'createdriver': $in["action"] = MOBIDELIV_TRANSP_DRIVERSCALL;
        $in['mode'] = MODE_ADD;
        break;
    case 'getdriverslist': $in["action"] = MOBIDELIV_TRANSP_DRIVERSCALL;
        $in['mode'] = MODE_LIST;
        break;
    case 'updatedriver': $in["action"] = MOBIDELIV_TRANSP_DRIVERSCALL;
        $in['mode'] = MODE_UPDATE;
        break;
    case 'updatedriverstatus': $in["action"] = MOBIDELIV_TRANSP_DRIVERSCALL;
        $in['mode'] = MODE_LIST;
        break;
    case 'getdevicelist': $in["action"] = MOBIDELIV_TRANSP_DEVICELIST;
        break;
    case 'transportstatus': $in["action"] = MOBIDELIV_TRANSP_SET_TRANSSTATUS;
        break;
    case 'getreason': $in["action"] = MOBIDELIV_TRANSP_GETREASON;
        break;
    case 'getinvoice': $in["action"] = MOBIDELIV_TRANSP_GETINVOICE;
        break;
    case 'gettranslationlist':$in["action"] = MOBIDELIV_TRANSP_GET_TRANSLATORLIST;
        break;
    case 'translationstatus':
        $in["action"] = MOBIDELIV_TRANSL_SET_TRANSSTATUS;
        break;
}
$in["pid"] = 100;

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

$out = array();
external_internal_call($in, $out);

header("HTTP/1.1 200 OK");
header("Status: 200 OK");
//$out = array_merge($in, $out); // DEBUG
//echo json_encode($out);
echo json_encode(processAgentOutJson($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;
}

function download_file_call() {
    global $target_url;
    $data = $_POST;
    $url = $target_url . "/../internal_agentdownload.php";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_HEADER, true);
    curl_setopt($ch, CURLOPT_VERBOSE, true);
    $output = curl_exec($ch);
    $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
    curl_close($ch);
    if ($status != 200) {
        header('HTTP/1.1 400 Bad Request');
        header('Status: 400 Bad Request');
        echo "{\"status\":\"Failed to download file\"}";
        exit();
    }
    $header = substr($output, 0, $header_size);
    $body = substr($output, $header_size);

    $headers = array();
    $data = explode("\r\n", $header);
    //$headers['status'] = $data[0];
    //array_shift($data);
    foreach ($data as $part) {
        if (strpos($part, ":") !== false) {
            $middle = explode(":", $part);
            $headers[trim($middle[0])] = trim($middle[1]);
        }
    }
    header("HTTP/1.1 200 OK");
    header("Status: 200 OK");
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename="' . basename($headers["X-File-Name"]) . '"');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . strlen($body));
    header("X-File-Name: " . $headers["X-File-Name"]);
    echo $body;
}

function upload_file_call() {
    global $target_url;
    $data = $_POST;
    $url = $target_url . "/../internal_agentupload.php";
    $uploaddir = realpath('./') . '/files/';
    $uploadfile = $uploaddir . basename($_FILES['file_contents']['name']);
    if (!move_uploaded_file($_FILES['file_contents']['tmp_name'], $uploadfile)) {
        $in["uploadfile"] = $uploadfile;
        header('HTTP/1.1 400 Bad Request');
        header('Status: 400 Bad Request');
        echo "{\"status\":\"Failed to upload file\"}";
        exit();
    }

    //-----------------------------------------------------------
    $file_name_with_full_path = realpath($uploadfile);
    /* curl will accept an array here too.
     * Many examples I found showed a url-encoded string instead.
     * Take note that the 'key' in the array will be the key that shows up in the
     * $_FILES array of the accept script. and the at sign '@' is required before the
     * file name.
     */
    $data['file_contents'] = '@' . $file_name_with_full_path;

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

    $json_response = curl_exec($curl);

    $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

    if ($status != 200) {
        header('HTTP/1.1 400 Bad Request');
        header('Status: 400 Bad Request');
        echo "{\"status\":\"Error: call to URL $url failed with status $status, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl) . "\"}";
    }

    curl_close($curl);
    unlink($file_name_with_full_path);

    //$response = json_decode($json_response, true);

    header("HTTP/1.1 200 OK");
    header("Status: 200 OK");

    echo $json_response;
}

function processAgentOutJson($in, $out) {
    if ($in["action"] != MOBIDELIV_TRANSP_GET_TRANSLIST) {
        //return $out;
    }

    switch ($in["action"]) {

        case MOBIDELIV_TRANSP_GET_TRANSLATORLIST:

            $total = $out["total_record"];
            $res = array(
                "status" => $out["status"],
                "total_record" => ($total - 1),
                "internal_return" => $out["internal_return"],
                "result_list" => array(),
            );
            for ($i = 0; $i < $total; $i++) {
                $key = sprintf("%05d", $i);
                $res["result_list"][] = array(
                    "transport_date" => $out["transport_date_${key}"],
                    "transport_time" => $out["transport_time_${key}"],
                    "firstname" => $out["firstname_${key}"],
                    "lastname" => $out["lastname_${key}"],
                    "from_phone" => $out["from_phone_${key}"],
                    "from_street" => $out["from_street_${key}"],
                    "to_street" => $out["to_street_${key}"],
                    "from_city" => $out["from_city_${key}"],
                    "to_city" => $out["to_city_${key}"],
                    "from_state" => $out["from_state_${key}"],
                    "to_state" => $out["to_state_${key}"],
                    "from_zipcode" => $out["from_zipcode_${key}"],
                    "to_zipcode" => $out["to_zipcode_${key}"],
                    "miles" => $out["distance_${key}"],
                    "transport" => $out["transport_${key}"],
                    "translate" => $out["translate_${key}"],
                    "id" => $out["id_${key}"],
                    "lang_code" => $out["lang_code_${key}"],
                    "language" => $out["language_${key}"],
                    "status" => $out["status_${key}"],
                    "assign_date" => $out["assign_date_${key}"],
                    "dist_mode" => $out["dist_mode_${key}"],
                    "needwheelchair" => $out["needwheelchair_${key}"],
                    "abilitytowalk" => $out["abilitytowalk_${key}"],
                    "conciergeneeded" => $out["conciergeneeded_${key}"],
                    "courtappearance" => $out["courtappearance_${key}"],
                    "dt_confirmed" => $out["dt_confirmed_${key}"],
                    "dt_rejected" => $out["dt_rejected_${key}"],
                    "dt_completed" => $out["dt_completed_${key}"],
                    "language" => $out["language_${key}"],
                    "interpreter_id" => $out["interpreter_id_${key}"],
                    "status_description" => $out["status_description_${key}"],
                    "pstatus_date" => $out["pstatus_date_${key}"],
                    "flags" => $out["flags_${key}"]
                );
            }
            break;

        case MOBIDELIV_TRANSP_GET_TRANSLIST:

            $total = $out["total_record"];
            $res = array(
                "status" => $out["status"],
                "total_record" => ($total - 1),
                "internal_return" => $out["internal_return"],
                "result_list" => array(),
            );
            for ($i = 0; $i < $total; $i++) {
                $key = sprintf("%05d", $i);
                $res["result_list"][] = array(
                    "transport_date" => $out["transport_date_${key}"],
                    "transport_time" => $out["transport_time_${key}"],
                    "firstname" => $out["firstname_${key}"],
                    "lastname" => $out["lastname_${key}"],
                    "from_phone" => $out["from_phone_${key}"],
                    "from_street" => $out["from_street_${key}"],
                    "to_street" => $out["to_street_${key}"],
                    "from_city" => $out["from_city_${key}"],
                    "to_city" => $out["to_city_${key}"],
                    "from_state" => $out["from_state_${key}"],
                    "to_state" => $out["to_state_${key}"],
                    "from_zipcode" => $out["from_zipcode_${key}"],
                    "to_zipcode" => $out["to_zipcode_${key}"],
                    "miles" => $out["distance_${key}"],
                    "transport" => $out["transport_${key}"],
                    "translate" => $out["translate_${key}"],
                    "id" => $out["id_${key}"],
                    "lang_code" => $out["lang_code_${key}"],
                    "language" => $out["language_${key}"],
                    "status" => $out["status_${key}"],
                    "assign_date" => $out["assign_date_${key}"],
                    "dist_mode" => $out["dist_mode_${key}"],
                    "needwheelchair" => $out["needwheelchair_${key}"],
                    "abilitytowalk" => $out["abilitytowalk_${key}"],
                    "conciergeneeded" => $out["conciergeneeded_${key}"],
                    "courtappearance" => $out["courtappearance_${key}"],
                    "dt_confirmed" => $out["dt_confirmed_${key}"],
                    "dt_rejected" => $out["dt_rejected_${key}"],
                    "dt_completed" => $out["dt_completed_${key}"],
                    "language" => $out["language_${key}"],
                    "driver" => $out["driver_${key}"],
                    "status_description" => $out["status_description_${key}"],
                    "pstatus_date" => $out["pstatus_date_${key}"],
                    "flags" => $out["flags_${key}"]
                );
            }
            break;
        case MOBIDELIV_USER_GET_LANGUAGE:
            $total = $out["total_record"];
            $res = array(
                "status" => $out["status"],
                "total_record" => ($total - 1),
                "internal_return" => $out["internal_return"],
                "result_list" => array(),
            );
            for ($i = 0; $i < $total; $i++) {
                $key = sprintf("%05d", $i);
                $res["result_list"][] = array(
                    "language" => $out["language_${key}"],
                    "code" => $out["code_${key}"]
                );
            }
            break;

        case MOBIDELIV_TRANSP_GETREASON:

            $total = $out["total_record"];
            $res = array(
                "status" => $out["status"],
                "total_record" => ($total - 1),
                "internal_return" => $out["internal_return"],
                "result_list" => array(),
            );
            for ($i = 0; $i < $total; $i++) {
                $key = sprintf("%05d", $i);
                $res["result_list"][] = array(
                    "key" => $out["lkey_${key}"],
                    "name" => $out["name_${key}"],
                    "lorder" => $out["lorder_${key}"]
                );
            }


            break;

        case MOBIDELIV_TRANSP_LISTLOCATION:

            $total = $out["total_record"];
            $res = array(
                "status" => $out["status"],
                "total_record" => ($total - 1),
                "internal_return" => $out["internal_return"],
                "result_list" => array(),
            );
            for ($i = 0; $i < $total; $i++) {
                $key = sprintf("%05d", $i);
                $res["result_list"][] = array(
                    "agent_id" => $out["agent_id_${key}"],
                    "street" => $out["street_${key}"],
                    "city" => $out["city_${key}"],
                    "id" => $out["id_${key}"],
                    "state" => $out["state_${key}"],
                    "zipcode" => $out["zipcode_${key}"],
                    "state" => $out["state_${key}"],
                    "loc_name" => $out["loc_name_${key}"]
                );
            }

            break;

        case MOBIDELIV_TRANSP_LIST_TRANSLATOR:
            $total = $out["total_record"];
            $res = array(
                "status" => $out["status"],
                "total_record" => ($total - 1),
                "internal_return" => $out["internal_return"],
                "result_list" => array(),
            );
            for ($i = 0; $i < $total; $i++) {
                $key = sprintf("%05d", $i);
                $res["result_list"][] = array(
                    "agent_id" => $out["agent_id_${key}"],
                    "firstname" => $out["firstname_${key}"],
                    "lastname" => $out["lastname_${key}"],
                    "street" => $out["street_${key}"],
                    "city" => $out["city_${key}"],
                    "id" => $out["id_${key}"],
                    "state" => $out["state_${key}"],
                    "zipcode" => $out["zipcode_${key}"],
                    "state" => $out["state_${key}"],
                    "mobile_key" => $out["mobile_key_${key}"],
                    "mobile_pin" => $out["mobile_pin_${key}"]
                );
            }


            break;

        case MOBIDELIV_TRANSP_LANGUAGELIST:
            $total = $out["total_record"];
            $res = array(
                "status" => $out["status"],
                "total_record" => ($total - 1),
                "internal_return" => $out["internal_return"],
                "result_list" => array(),
            );
            for ($i = 0; $i < $total; $i++) {
                $key = sprintf("%05d", $i);
                $res["result_list"][] = array(
                    "agent_id" => $out["agent_id_${key}"],
                    "interpreter_id" => $out["interpreter_id_${key}"],
                    "language_id" => $out["language_id_${key}"],
                    "lang_code" => $out["lang_code_${key}"],
                    "language" => $out["language_${key}"],
                    "flags" => $out["flags_${key}"],
                    "status" => $out["status_${key}"],
                    "document" => $out["document_${key}"],
                    "document_id" => $out["document_id_${key}"],
                    "weekend" => $out["weekend_${key}"]
                );
            }

            break;

        case MOBIDELIV_TRANSP_AGENTLANGUAGE:
            $total = $out["total_record"];
            $res = array(
                "status" => $out["status"],
                "total_record" => ($total - 1),
                "internal_return" => $out["internal_return"],
                "result_list" => array(),
            );
            for ($i = 0; $i < $total; $i++) {
                $key = sprintf("%05d", $i);
                $res["result_list"][] = array(
                    "agent_id" => $out["agent_id_${key}"],
                    "firstname" => $out["firstname_${key}"],
                    "lastname" => $out["lastname_${key}"],
                    "street" => $out["street_${key}"],
                    "city" => $out["city_${key}"],
                    "state" => $out["state_${key}"],
                    "zipcode" => $out["zipcode_${key}"],
                    "language_id" => $out["language_id_${key}"],
                    "lang_code" => $out["lang_code_${key}"],
                    "language" => $out["language_${key}"],
                    "flags" => $out["flags_${key}"],
                    "weekend" => $out["weekend_${key}"],
                    "phone" => $out["phone_${key}"],
                    "interpreter_id" => $out["interpreter_id_${key}"],
                );
            }



            break;

        case MOBIDELIV_TRANSP_DRIVERSCALL:
            if ($out['mode'] == MODE_LIST) {
                $total = $out["total_record"];
                $res = array(
                    "status" => $out["status"],
                    "total_record" => ($total - 1),
                    "internal_return" => $out["internal_return"],
                    "result_list" => array(),
                );
                for ($i = 0; $i < $total; $i++) {
                    $key = sprintf("%05d", $i);
                    $res["result_list"][] = array(
                        "agent_id" => $out["agent_id_${key}"],
                        "firstname" => $out["firstname_${key}"],
                        "lastname" => $out["lastname_${key}"],
                        "street" => $out["street_${key}"],
                        "city" => $out["city_${key}"],
                        "state" => $out["state_${key}"],
                        "zipcode" => $out["zipcode_${key}"],
                        "lic_state" => $out["lic_state_${key}"],
                        "email" => $out["email_${key}"],
                        "expr_month" => $out["expr_month_${key}"],
                        "expr_year" => $out["expr_year_${key}"],
                        "lic_number" => $out["lic_number_${key}"],
                        "phone" => $out["phone_${key}"],
                        "driver_id" => $out["driver_id_${key}"],
                        "mobile_key" => $out["mobile_key_${key}"],
                        "mobile_pin" => $out["mobile_pin_${key}"],
                    );
                }
            }

            break;





        default:
            return $out;
    }

    return $res;
}

// vi:ts=2

