<?php

class AGT_Controller extends CI_Controller {

    var $template = array(
        'table_open' => "<table class='table table-striped table-hover table-bordered table-condensed'>",
        'thead_open' => '<thead class=\'bg-indigo\'>',
        'thead_close' => '</thead>',
        'heading_row_start' => '<tr>',
        'heading_row_end' => '</tr>',
        'heading_cell_start' => '<th>',
        'heading_cell_end' => '</th>',
        'tbody_open' => '<tbody>',
        'tbody_close' => '</tbody>',
        'row_start' => '<tr>',
        'row_end' => '</tr>',
        'cell_start' => '<td>',
        'cell_end' => '</td>',
        'row_alt_start' => '<tr>',
        'row_alt_end' => '</tr>',
        'cell_alt_start' => '<td>',
        'cell_alt_end' => '</td>',
        'table_close' => '</table>'
    );
    var $template_nohead = array(
        'table_open' => "<table class='table table-striped table-hover table-bordered table-condensed'>",
        'thead_open' => '<thead>',
        'thead_close' => '</thead>',
        'heading_row_start' => '<tr>',
        'heading_row_end' => '</tr>',
        'heading_cell_start' => '<th>',
        'heading_cell_end' => '</th>',
        'tbody_open' => '<tbody>',
        'tbody_close' => '</tbody>',
        'row_start' => '<tr>',
        'row_end' => '</tr>',
        'cell_start' => '<td>',
        'cell_end' => '</td>',
        'row_alt_start' => '<tr>',
        'row_alt_end' => '</tr>',
        'cell_alt_start' => '<td>',
        'cell_alt_end' => '</td>',
        'table_close' => '</table>'
    );
    public $data = array();

    function __construct() {
        parent::__construct();
    }

    protected function smart_htmlspecialchars($str) {
        if (substr($str, 0, 1) == '<')
            return $str;
        return htmlspecialchars($str);
    }

    protected function sql_escape_func($inp) {
        if (is_array($inp)) {
            return array_map(__METHOD__, $inp);
        }


        if (!empty($inp) && is_string($inp)) {
            return str_replace(array('\\', "\0", "\n", "\r", "'", '"', "\x1a"), array('\\\\', '\\0', '\\n', '\\r', "\\'", '\\"', '\\Z'), $inp);
        }

        return $inp;
    }

    protected function medtrans_call_api($action, $in, &$out) {
        $ret = -1;
        $in['pid'] = 115;

        // THE BASE ENDPOINT WILL COME FROM CONFIG FILE 
        $endpointbase = "https://extlayer.kleenapp.co/agent/";

        switch ($action) {
            case MEDTRANS_TRANSP_DEVICELIST:
                $endpoint = $endpointbase . "getdevicelist";
                $data = array(
                    "agent_id" => $_SESSION["agent_id"],
                    "location_id" => $in["location_id"],
                    "sessionid" => $_SESSION["agent_sessionid"]
                );
                break;

            case MEDTRANS_TRANSP_LOGIN:
                $endpoint = $endpointbase . "agentlogin";
                $data = array(
                    "username" => $in["username"],
                    "password" => $in["password"]
                );
                break;
            case MEDTRANS_TRANSP_CREATE:
                $endpoint = $endpointbase . "createagent"; //"agentcreate";
                $data = $in;
                // $data['login'] = 1; // force login after creattion
                break;
            case MEDTRANS_TRANSP_GET_TRANSLIST:
                $endpoint = $endpointbase . "gettransportlist";
                $data = array(
                    "agent_id" => $in["agent_id"],
                    "limit" => $in["limit"],
                    "transport_id" => $in["transport_id"]
                );
                break;
            case MEDTRANS_TRANSP_VERIFYSESSION:
                $endpoint = $endpointbase . "verifysession";
                $data = array(
                    "agent_id" => $_SESSION["agent_id"],
                    "sessionid" => $_SESSION["agent_sessionid"]
                );
                break;

            case MEDTRANS_TRANSP_GET_TRANSPORTER:
                $endpoint = $endpointbase . "getlocation";
                $data = array(
                    "agent_id" => $_SESSION["agent_id"],
                    "transporter_id" => $in["location_id"],
                    "sessionid" => $_SESSION["agent_sessionid"]
                );
                break;
            case MEDTRANS_TRANSP_ADDLOCATION:
                $endpoint = $endpointbase . "addtransportlocation";
                $data = array(
                    "agent_id" => $_SESSION["agent_id"],
                    "sessionid" => $_SESSION["agent_sessionid"],
                    "loc_name" => $in["loc_name"],
                    "phone" => $in["phone"],
                    "street" => $in["street"],
                    "city" => $in["city"],
                    "zipcode" => $in["zipcode"],
                    "state" => $in["state"],
                    "country" => "US"
                );
                break;
            case MEDTRANS_TRANSP_EDITLOCATION:
                $endpoint = $endpointbase . "editlocation";
                $data = array(
                    "agent_id" => $_SESSION["agent_id"],
                    "transporter_id" => $in["location_id"],
                    "sessionid" => $_SESSION["agent_sessionid"],
                    "loc_name" => $in["loc_name"],
                    "phone" => $in["phone"],
                    "street" => $in["street"],
                    "city" => $in["city"],
                    "zipcode" => $in["zipcode"],
                    "state" => $in["state"],
                    "country" => "US"
                );
                break;
            case MEDTRANS_TRANSP_LISTLOCATION:
                $endpoint = $endpointbase . "listtransportlocation";
                $data = array(
                    "agent_id" => $_SESSION["agent_id"],
                    "sessionid" => $_SESSION["agent_sessionid"],
                    "limit" => $in["limit"]
                );
                break;
            case MEDTRANS_TRANSP_GET_TRANSLATOR:
                $endpoint = $endpointbase . "getinterpreter";
                $data = array(
                    "agent_id" => $_SESSION["agent_id"],
                    "interpreter_id" => $in["interpreter_id"],
                    "sessionid" => $_SESSION["agent_sessionid"]
                );
                break;
            case MEDTRANS_TRANSP_ADD_TRANSLATOR:
                $endpoint = $endpointbase . "addinterpreter";
                $data = array(
                    "agent_id" => $_SESSION["agent_id"],
                    "sessionid" => $_SESSION["agent_sessionid"],
                    "email" => $in["email"],
                    "firstname" => $in["firstname"],
                    "lastname" => $in["lastname"],
                    "phone" => $in["phone"],
                    "street" => $in["street"],
                    "city" => $in["city"],
                    "zipcode" => $in["zipcode"],
                    "state" => $in["state"],
                    "country" => "US"
                );
                break;
            case MEDTRANS_TRANSP_EDIT_TRANSLATOR:
                $endpoint = $endpointbase . "editinterpreter";
                $data = array(
                    "agent_id" => $_SESSION["agent_id"],
                    "interpreter_id" => $in["interpreter_id"],
                    "sessionid" => $_SESSION["agent_sessionid"],
                    "email" => $in["email"],
                    "firstname" => $in["firstname"],
                    "lastname" => $in["lastname"],
                    "phone" => $in["phone"],
                    "street" => $in["street"],
                    "city" => $in["city"],
                    "zipcode" => $in["zipcode"],
                    "state" => $in["state"],
                    "country" => "US"
                );
                break;
            case MEDTRANS_TRANSP_LIST_TRANSLATOR:
                $endpoint = $endpointbase . "listinterpreters";
                $data = array(
                    "agent_id" => $_SESSION["agent_id"],
                    "sessionid" => $_SESSION["agent_sessionid"],
                    "limit" => $in["limit"]
                );
                break;
            case MEDTRANS_USER_GET_LANGUAGE:
                $endpoint = $endpointbase . "getsupportedlanguage";
                $data = array(
                    "agent_id" => $_SESSION["agent_id"],
                    "sessionid" => $_SESSION["agent_sessionid"],
                    "limit" => 1000,
                    'status' => 0
                );
                break;
            case MEDTRANS_TRANSP_LANGUAGELIST:
                $endpoint = $endpointbase . "getinterpreterlanguage";
                $data = array(
                    "agent_id" => $_SESSION["agent_id"],
                    "sessionid" => $_SESSION["agent_sessionid"],
                    "interpreter_id" => $in["interpreter_id"],
                    "language_id" => $in["language_id"],
                    "limit" => 1000,
                    'status' => 0
                );
                break;
            case MEDTRANS_TRANSP_MANAGELANGUAGE:
                $endpoint = $endpointbase . "interpreterlang";
                $data = array(
                    "agent_id" => $_SESSION["agent_id"],
                    "interpreter_id" => $in["interpreter_id"],
                    "sessionid" => $_SESSION["agent_sessionid"],
                    "mode" => $in["mode"],
                    "lang_code" => $in["lang_code"]
                );
                if (isset($in["language_id"]))
                    $data["language_id"] = $in["language_id"];
                if (isset($in["flags"]))
                    $data["flags"] = $in["flags"];
                break;
            case MEDTRANS_UPLOADS:
                $endpoint = $endpointbase . "uploadfile";
                $data = array(
                    "agent_id" => $_SESSION["agent_id"],
                    "interpreter_id" => $in["interpreter_id"],
                    "sessionid" => $_SESSION["agent_sessionid"],
                    "language_id" => $in["language_id"],
                    "file_type" => INTERPRETER_CERTIFICATE,
                    "name" => $in["name"],
                    "data" => $in["data"]
                );
                return $this->fileUpload($endpoint, $data, $out);
                break;

            case MEDTRANS_DOWNLOAD:
                $endpoint = $endpointbase . "download";
                $data = array(
                    "agent_id" => $_SESSION["agent_id"],
                    "interpreter_id" => $in["interpreter_id"],
                    "sessionid" => $_SESSION["agent_sessionid"],
                    "language_id" => $in["language_id"],
                    "file_type" => INTERPRETER_CERTIFICATE,
                    "document_id" => $in["document_id"]
                );
                list($ret, $name, $data) = $this->fileDownload($endpoint, $data, $out);
                $out["file"] = $name;
                $out["data"] = $data;
                return $ret;
                break;

            case MEDTRANS_TRANSP_AGENTLANGUAGE:
                $endpoint = $endpointbase . "getagentlanguage";
                $data = array(
                    "agent_id" => $_SESSION["agent_id"],
                    "sessionid" => $_SESSION["agent_sessionid"],
                    "language_id" => $in["language_id"]
                );
                break;

            case MEDTRANS_TRANSP_DRIVERSCALL:

                if ($in["mode"] == MODE_LIST) {
                    $endpoint = $endpointbase . "getdriverslist";
                    $data = array(
                        "agent_id" => $_SESSION["agent_id"],
                        "sessionid" => $_SESSION["agent_sessionid"],
                        "driver_id" => $in["driver_id"]
                    );
                } else if ($in['mode'] == MODE_ADD) {
                    $endpoint = $endpointbase . "createdriver";
                    $data = array(
                        "agent_id" => $_SESSION["agent_id"],
                        "sessionid" => $_SESSION["agent_sessionid"],
                        "email" => $in["email"],
                        "firstname" => $in["firstname"],
                        "lastname" => $in["lastname"],
                        "phone" => $in["phone"],
                        "street" => $in["street"],
                        "city" => $in["city"],
                        "zipcode" => $in["zipcode"],
                        "state" => $in["state"],
                        "country" => "US",
                        "lic_number" => $in["lic_number"],
                        "lic_state" => $in["lic_state"],
                        "expr_month" => $in["expr_month"],
                        "expr_year" => $in["expr_year"]
                    );
                } else if ($in['mode'] == MODE_UPDATE) {
                    $endpoint = $endpointbase . "updatedriver";
                    $data = array(
                        "agent_id" => $_SESSION["agent_id"],
                        "driver_id" => $in["driver_id"],
                        "sessionid" => $_SESSION["agent_sessionid"],
                        "email" => $in["email"],
                        "firstname" => $in["firstname"],
                        "lastname" => $in["lastname"],
                        "phone" => $in["phone"],
                        "street" => $in["street"],
                        "city" => $in["city"],
                        "zipcode" => $in["zipcode"],
                        "state" => $in["state"],
                        "country" => "US",
                        "lic_number" => $in["lic_number"],
                        "lic_state" => $in["lic_state"],
                        "expr_month" => $in["expr_month"],
                        "expr_year" => $in["expr_year"]
                    );
                }
                break;
        }

        //  call the endpoint here 
        $content = json_encode($data);
        $curl = curl_init($endpoint);
        curl_setopt($curl, CURLOPT_HEADER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array("Content-type" => "application/json"));
        curl_setopt($curl, CURLOPT_POST, true);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $content);
        $json_response = curl_exec($curl);
        $status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
        if ($status != 200) {
            $out["status"] = "Service error: call to URL $endpoint failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl);
            return $ret;
        }
        $out["status"] = "";

        $ret = -1; // PHP_API_OK
        curl_close($curl);
        $out = json_decode($json_response, true);

        $ret = isset($out['internal_return']) ? $out['internal_return'] : -1;
        //$out = array_merge($out, $response);
        return $ret;
    }

    protected function fileDownload($endpoint, $data) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $endpoint);
        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);
        if ($status != 200) {
            $out["status"] = "Service error: call to URL $endpoint failed with status $status, curl_error " . curl_error($ch) . ", curl_errno " . curl_errno($ch);
            return -1;
        }
        curl_close($ch);
        $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]);
            }
        }
        return array(0, $headers["X-File-Name"], $body);
    }

    protected function fileUpload($endpoint, $data, $out) {
        $ret = -1;
        $uploaddir = realpath('./') . '/tmp/';
        $uploadfile = $uploaddir . $data['name'];
        if (file_put_contents($uploadfile, $data['data']) === FALSE) {
            return $ret;
        }
        unset($data['name']);
        unset($data['data']);
        /*
          $uploadfile = $uploaddir . basename($_FILES['file_contents']['name']);
          if (move_uploaded_file($_FILES['file_contents']['tmp_name'], $uploadfile)) {
          // OK
          } else {
          return $ret;
          }
         */
        $file_name_with_full_path = realpath($uploadfile);
        $data['file_contents'] = '@' . $file_name_with_full_path;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $endpoint);
        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);
        curl_close($curl);
        unlink($file_name_with_full_path);
        if ($status != 200) {
            $out["status"] = "Error: call to URL $url failed with status $status, response $json_response, curl_error " . curl_error($curl) . ", curl_errno " . curl_errno($curl);
            $ret = -1;
        } else {
            $out = json_decode($json_response, true);
            $ret = 0;
        }
        return $ret;
    }

    protected function populateAgentsession($out) {


        $_SESSION['agent_id'] = $out['id'];
        $_SESSION['city'] = $out['city'];
        $_SESSION['email'] = $out['email'];
        $_SESSION['firstname'] = $out['firstname'];
        $_SESSION['lastname'] = $out['lastname'];
        $_SESSION['loc'] = $out['loc'];
        $_SESSION['phone'] = $out['phone'];
        $_SESSION['state'] = $out['state'];
        $_SESSION['username'] = $out['username'];
        $_SESSION['zipcode'] = $out['zipcode'];
        $_SESSION['transporter'] = $out['transporter'];
        $_SESSION['agent_sessionid'] = $out['sessionid'];
        $_SESSION['sessionid'] = $out['sessionid'];
        $_SESSION['agent_name'] = $out["agent_name"];
        $_SESSION['agent_type'] = $out["agent_type"];


        // print_r($out);
    }

    protected function formatedMesage($msgType, $theMessage) {
        return "<div class=\"text-left\"><div class=\"alert alert-danger no-border\">" . $theMessage . "</div></div>";
    }

    protected function renderAgentPage($page_name, $data) {
        $this->load->view('template/view_agent_header', $data);
        $this->load->view('agent/' . $page_name, $data);
        $this->load->view('template/view_agent_footer', $data);
    }

    protected function testLoginInput(&$username, &$password, &$error_message, &$valid_entry) {
        $valid_entry = true;
        $username = urlencode(trim($this->input->post('username')));
        $password = trim($this->input->post('password'));
        if ($username == '' or $password == '') {
            $valid_entry = false;
            $error_message = 'Enter a Username/Password to continue';
        }
    }

}
