<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Agent extends Admin_Controller {

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

    public function index() {
        $this->pending();
    }

    public function agents() {

        $data = array();
        if ($this->input->post()) {
            $data = $this->input->post();
            //  print_r($data);
            $srcht = trim($data['searchtext']);
            $mysql = "SELECT * FROM agents ORDER BY id DESC limit 205";
        } else {
            $data['searchtext'] = '';
            $mysql = " SELECT * FROM agents ORDER BY id DESC limit 50";
        }

        $data['page_title'] = "Agent Search";
        $data['search_combo'] = $this->agentSearchCombo('searchparam');

        $q = $this->db->query($mysql);
        $data['transporter_search'] = $q->result();
        $this->renderAdminPage('agent/view_find_agent', $data);
    }

    public function providers()
    {
        echo 'Ameye 001';
    }
    
    public function addnew() {
        $data = array();
        $data['firstname'] = $data['lastname'] = $data['transporter'] = '';
        $data['username'] = $data['phone'] = $data['street'] = '';
        $data['zipcode'] = $data['city'] = $data['state'] = '';

        if ($this->input->post()) {
            $data = $this->getCreateTrasporterPost();

            $data['action'] = MEDTRANS_TRANSP_CREATE;
            $out = array();
            $ret = $this->medtrans_api($data, $out);
        }

        $data['transports_list'] = $this->getRecentTransportersList(10);
        $this->renderAdminPage('transp/view_addnew_transporter', $data);
    }

    public function find() {
        $data = array();


        if ($this->input->post()) {
            $data = $this->input->post();
            //  print_r($data);
            $srcht = trim($data['searchtext']);
            $mysql = "SELECT t.*,a.username,a.agent_name FROM transporter t LEFT JOIN agents a ON a.id=t.agent_id ORDER BY a.id DESC LIMIT 20";
        } else {
            $data['searchtext'] = '';

            $mysql = " SELECT t.*,a.username,a.agent_name FROM transporter t LEFT JOIN agents a ON a.id=t.agent_id ORDER BY a.id DESC LIMIT 20";
        }
        $q = $this->db->query($mysql);
        $data['transporter_search'] = $q->result();





        $data['transports_list'] = $this->getRecentTransportersList(10);
        $this->renderAdminPage('transp/view_find_transporter', $data);
    }

    public function manage() {

        $transp_id = $this->input->get('transp_id');

        // echo "Ameye 1 - ".$transp_id ; 

        $data = array();

        //   $mysql = "SELECT DATE_PART('hour', transport_date - now() ) AS day_gap, * FROM members_transport_request WHERE id=" . $data['transp_id'];
        //   $q = $this->db->query($mysql);
        //    $query = $this->db->query($mysql);
        //       $data['transport_data'] = $query->row_array();
        //   $out = $this->makeGoogleAddress($data['transport_data']);
        // $data['directionsStart'] = $out['directionsStart']; //'4201 defoors farm trail, powder springs, GA 30127, USA';
        // $data['directionsEnd'] = $out['directionsEnd']; //'2324 sta
        // echo $this->constructTranspSelect($data); // 'yes here-'.;


        $this->renderAdminPage('transp/view_transport_manage', $data);
    }

    public function findbylinkid() {

        // get the user id 
        $transp_id = $this->input->get('transp_id');

        $mysql = "SELECT *,id AS transp_id  FROM transporters WHERE id=" . $transp_id;
        $q = $this->db->query($mysql);
        $out = $q->row();

        $_SESSION['selected_transporter_row'] = $out;
        redirect('transporter/profile');
    }

    private function getRecentTransportersList($plimit) {
        $mysql = "SELECT  * FROM transporters ORDER BY id DESC LIMIT $plimit";
        $q = $this->db->query($mysql);
        $recent_transporter_list = $q->result();
        return $recent_transporter_list;
    }

    private function getCreateTrasporterPost() {
        $out = array();

        $out['transporter'] = $this->input->post('transporter');
        $out['firstname'] = $this->input->post('firstname');
        $out['lastname'] = $this->input->post('lastname');

        $out['street'] = $this->input->post('street');
        $out['zipcode'] = $this->input->post('zipcode');

        $out['phone'] = $this->input->post('phone');
        $out['city'] = $this->input->post('city');
        $out['state'] = $this->input->post('state');

        $out['username'] = $this->input->post('username');
        $out['email'] = $out['username'];
        $out['password'] = $this->input->post('password');

        return $out;
    }

    public function pending() {

        $data = array();

        $this->load->model('admindash_model');
        //   $out = $this->admindash_model->getAdminDashData($data);
        //   $data['recent_signup'] = $out['recent_signup'];

        $mysql = "SELECT DATE_PART('hour', transport_date - now() ) AS day_gap, * FROM members_transport_request";


        $mysql = " SELECT r.*,r.transport_date::time AS transport_time,DATE_PART('day', r.transport_date - now() ) AS day_gap, r.id AS transport_request_id FROM members_transport_request r "
                . " RIGHT JOIN transport_assignment a ON a.transport_id = r.id "
                . " WHERE a.status = 1 AND a.flags IN (0,1,2,3) ORDER BY r.id DESC ";


        $q = $this->db->query($mysql);
        $data['transport_request'] = $q->result();

        $data['page_title'] = "Pending Transports";

        $this->renderAdminPage('transp/view_pending_trasport', $data);
    }

    public function newrequest() {

        $data = array();

        $this->load->model('admindash_model');
        //   $out = $this->admindash_model->getAdminDashData($data);
        //   $data['recent_signup'] = $out['recent_signup'];

        $mysql = "SELECT DATE_PART('hour', transport_date - now() ) AS day_gap, * FROM members_transport_request";


        $mysql = " SELECT r.*,r.transport_date::time AS transport_time,DATE_PART('day', r.transport_date - now() ) AS day_gap, r.id AS transport_request_id FROM members_transport_request r "
                . " LEFT JOIN transport_assignment a ON a.transport_id = r.id "
                . " WHERE r.status = 1 AND r.flags IN (0) ORDER BY r.id DESC ";


        $q = $this->db->query($mysql);
        $data['transport_request'] = $q->result();

        $data['page_title'] = "New Transport Request(s)";

        $this->renderAdminPage('transp/view_pending_trasport', $data);
    }

    public function assignTranspoter() {
        $data['transport_id'] = $this->input->get('transport_id');
        $data['transporter_id'] = $this->input->get('transporter_id');
        $data['pid'] = 110;

        if ($data["transport_id"] != '' and $data["transport_id"] > 0 and $data["transporter_id"] != '' and $data["transporter_id"] > 0) {

            $data['action'] = MEDTRANS_TRANSP_ASSIGNTRANSPORT;
            $out = array();
            $ret = $this->medtrans_api($data, $out);
            echo $ret;
        } else {
            echo "Invalid transport id and/or transporter selected";
        }
    }

    public function selpending() {
        $data['transp_id'] = $this->input->get('transp_id');

        if ($data["transp_id"] != '' and $data["transp_id"] > 0) {



            $mysql = " SELECT DATE_PART('hour', t.transport_date - now() ) AS day_gap, t.*,l.language,m.firstname AS req_firstname,m.lastname AS req_lastname, m.username AS req_username"
                    . " FROM members_transport_request t "
                    . " LEFT JOIN members m ON m.id=t.member_id "
                    . "LEFT JOIN languages l ON l.code=t.lang_code WHERE t.id=" . $data['transp_id'];

            $q = $this->db->query($mysql);
            $query = $this->db->query($mysql);
            $data['selected_transport'] = $query->row_array();
            $data['rect'] = $data['selected_transport'];


            $out = $this->SelectTransporter($data["transp_id"]);
            $data['recomended_list'] = $out['recomended_list'];
            $data['search_list'] = $out['search_list'];
            $data['assign_detail'] = "Show Detail of the assignment when applicable";

            if (isset($data['selected_transport']) AND isset($data['selected_transport']['transp_assign']) AND $data['selected_transport']['transp_assign'] != '' AND $data['selected_transport']['transp_assign'] > 0) {
                $assgned_transporter = $data['selected_transport']['transp_assign'];
                $rmysql = "SELECT a.added AS date_assigned,g.agent_name,t.* FROM transport_assignment a LEFT JOIN agents g ON g.id  = a.agent_id LEFT  JOIN transporter t ON t.id = a.transporter_id WHERE a.id=" . $assgned_transporter;
                //    $q = $this->db->query($rmysql);
                $query = $this->db->query($rmysql);
                $data['selected_transporter'] = $query->row_array();
                $data['assign_detail'] = "<b>Assigned to :</b> " . $data['selected_transporter']['agent_name'] . "<br><b>Location :</b>" . $data['selected_transporter']['loc_name'] . "," . $data['selected_transporter']['street'] . "," . $data['selected_transporter']['city'] . "," . $data['selected_transporter']['state'] . "-" . $data['selected_transporter']['zipcode'];
                $data['assign_phone'] = "<b>Phone :</b> " . $data['selected_transporter']['phone'];
            }
            /*
             * mobideliv=> SELECT a.added AS date_assigned,g.agent_name,t.* FROM transport_assignment a LEFT JOIN agents g ON g.id  = a.agent_id LEFT  JOIN transporter t ON t.id = a.transporter_id WHERE a.id=4;
              date_assigned       |        agent_name         | id | pid | agent_id |       street       |   city   | zipcode |   phone   | state | country |           added            |       loc       |    loc_name
              ---------------------------+---------------------------+----+-----+----------+--------------------+----------+---------+-----------+-------+---------+----------------------------+-----------------+----------------
              2017-10-27 17:27:53.20458 | Agenr Name with name 1000 | 36 | 100 |        4 | 2600 Bentley Rd SE | Marietta | 30067   | 664651123 | GA    | US      | 2017-10-13 18:49:51.300007 | 104.238.127.115 | This is a test
              (1 row)

             */

            $data['cancel_reason_combo'] = "Cancellation Reason Combo Here";



            $this->load->view('admin/transp/extra/transport_form', $data);
        }
        // echo 'A transport line was selected';
    }

    private function SelectTransporter($trasnport_id) {

        /*
         * THIS IS JUST AN EMULATOR FOR NOW - TRANSPORTERS WILL BE RECOMENDED BASED ON RULES AND PRECOMPUTATION USING MANY FACTORS LATTER
         */

        $out = array();
        $mysql = "SELECT id, loc_name||'-'||street||', '||city||', '||state||'-'||zipcode AS name FROM transporter ORDER BY random() LIMIT 3";
        $query = $this->db->query($mysql);

        $sel1 = "<select class=\"form-control\" id=\"sel1\" name=\"recomended_list\">";
        $sel1 .="<option value=\"0\">Select from recomended list</option>";
        foreach ($query->result() as $row) {
            $sel1 .="<option value=" . $row->id . ">" . $row->name . "</option>";
        }
        $sel1 .=" </select>";
        $out['recomended_list'] = $sel1;


        $mysql = "SELECT id, loc_name||'-'||street||', '||city||', '||state||'-'||zipcode AS name FROM transporter ORDER BY random() LIMIT 20";
        $query = $this->db->query($mysql);
        $sel2 = "<select class=\"form-control\" id=\"sel2\" name=\"search_list\" style=\"min-width:200px;\">";
        $sel2 .="<option value=\"0\">Search list to select</option>";
        foreach ($query->result() as $row) {
            $sel2 .="<option value=" . $row->id . ">" . $row->name . "</option>";
        }
        $sel2 .=" </select>";
        $out['search_list'] = $sel2;
        return $out;
    }

    private function constructTranspSelect($data) {

        $trnspPage = "
            <div class = \"panel-heading\">
            <h6 class = \"panel-title\"><b>Personal Information</b> This is the person to be transported</h6>
            </div>

            <div class = \"panel-heading\">
            <h6 class = \"panel-title\"><b>Created By</b> pay attention to the person that created it account</h6>
            </div>
            
            <div class = \"panel-heading\">
            <h6 class = \"panel-title\"><b>Destination :</b>" . $data['directionsEnd'] . "</h6>
             </div>

            <div class = \"panel-heading\">
            <h6 class = \"panel-title\"><b>Origin :</b> " . $data['directionsStart'] . "</h6>
            </div>

            <div class = \"panel-heading\">
            <h6 class = \"panel-title\"><b>Transporter</b></h6>
           </div>";
        return $trnspPage;
    }

    public function active() {

        $data = array();

        $this->load->model('admindash_model');
        //   $out = $this->admindash_model->getAdminDashData($data);
        //   $data['recent_signup'] = $out['recent_signup'];

        $mysql = "SELECT DATE_PART('hour', transport_date - now() ) AS day_gap, * FROM members_transport_request";


        $mysql = " SELECT r.*,r.transport_date::time AS transport_time,DATE_PART('day', r.transport_date - now() ) AS day_gap, r.id AS transport_request_id FROM members_transport_request r "
                . " RIGHT JOIN transport_assignment a ON a.transport_id = r.id "
                . " WHERE a.status = 1 AND a.flags IN (4,5,6) ORDER BY r.id DESC ";


        $q = $this->db->query($mysql);
        $data['transport_request'] = $q->result();

        $data['page_title'] = "Active Transport(s)";

        $this->renderAdminPage('transp/view_active_trasport', $data);
    }

    private function agentSearchCombo($cmbName) {

        $selected_val = $this->input->post($cmbName);

        $agentSearchList = array(
            'm.lastname' => 'Agent Name',
            'm.lastname' => 'Lastname',
            'm.firstname' => 'Firstname',
            'm.email' => 'Email',
            'm.phone' => 'Phone',
            'mp.zipcode' => 'Zip Code'
        );

        $str_Combo = " <select class=\"form-control\" name ='" . $cmbName . "'>";
        foreach ($agentSearchList as $key => $value) {
            $selV = '';
            if ($selected_val == $key) {
                $selV = ' selected';
            }

            $str_Combo .="<option  value='" . $key . "' " . $selV . ">" . $value . "</option>";
            //echo "Key: $key, Value: $value\n";
        }
        $str_Combo .="</select>";
        return $str_Combo;
    }

    public function selagent() {
        $data['agent_id'] = $this->input->get('agent_id');

        if ($data["agent_id"] != '' and $data["agent_id"] > 0) {

            $mysql = "SELECT * FROM agents WHERE id  = " . $data['agent_id'];
            $query = $this->db->query($mysql);
            $data['selected_agent'] = $query->row_array();

            $this->load->library('table');
            $this->table->set_template($this->template);

            //   $mysql = "SELECT loc_name,street,zipcode FROM transporter WHERE agent_id = " . $data['agent_id'];
            //  $query = $this->db->query($mysql);
            //$this->table->set_heading('Account', array('data' => 'Added', 'style' => 'width:120px'), array('data' => 'Action', 'style' => 'width:100px'));
            //   $data['transporter_table'] = $this->table->generate($query);
            //   $mysql = "SELECT firstname,lastname,email FROM interpreters WHERE agent_id = " . $data['agent_id'];
            //   $query = $this->db->query($mysql);
            //$this->table->set_heading('Account', array('data' => 'Added', 'style' => 'width:120px'), array('data' => 'Action', 'style' => 'width:100px'));
            //     $data['interpreter_table'] = $this->table->generate($query);
            $this->load->view('/admin/agent/extra/agent_form', $data);
        }
        // echo 'A transport line was selected';
    }

    public function maps() {
        $data = array();


        $this->load->library('googlemaps');

        // $config['center'] = '37.4419, -122.1419';
        $config['center'] = 'atlnta,GA,USA';
        $config['zoom'] = 'auto';
        $config['directions'] = TRUE;
        $config['map_height'] = '100%';
        $config['directionsStart'] = '4201 defoors farm trail, powder springs, GA 30127, USA';
        $config['directionsEnd'] = '2324 stancrest ln, lawrenceville, 30044, GA, USA';
        $config['directionsDivID'] = 'directionsDiv';
        $this->googlemaps->initialize($config);
        $data['map'] = $this->googlemaps->create_map();


        $this->renderAdminPage('view_maps', $data);
    }

    public function transp_modal() {
        // $data = $this->getSessionArray();
        $data['transport_request_id'] = trim($this->input->get('transport_request_id'));

        $mysql = " SELECT * FROM members_transport_request WHERE id=" . $data['transport_request_id']; //'$contract_id' ";
        $query = $this->db->query($mysql);
        $num = $query->num_rows();
        if ($num > 0) {
            $data['transport_data'] = $query->row_array();

            $out = $this->makeGoogleAddress($data['transport_data']);
            $this->load->library('googlemaps');
            $config['center'] = 'atlanta,GA,USA';
            $config['zoom'] = 'auto';
            $config['directions'] = TRUE;
            $config['directionsStart'] = $out['directionsStart']; //'4201 defoors farm trail, powder springs, GA 30127, USA';
            $config['directionsEnd'] = $out['directionsEnd']; //'2324 stancrest ln, lawrenceville, 30044, GA, USA';
            $config['directionsDivID'] = 'directionsDiv';
            $this->googlemaps->initialize($config);
            $data['map'] = $this->googlemaps->create_map();

            $data['directionsStart'] = $out['directionsStart'];
            $data['directionsEnd'] = $out['directionsEnd'];
            // $lat_long = get_lat_long_from_address($config['center']);
            // $data['latCenter'] = $lat_long[0];
            // $data['longCenter'] = $lat_long[1];
            // $data['transport_request_id'] = $transport_request_id;
            $this->load->view('admin/modals/view_transp_modal', $data);
        }
    }

    /*
     * Array ( [id] => 1 [pid] => 115 [member_id] => 3744 [loc_type] => [firstname] => Adewumi [lastname] => Muyiwa [transport_date] => 2017-10-01 08:30:30 [from_phone] => 7702222380 [from_street] => Lake City Nursing And Rehab [from_aptno] => [from_city] => Lake City [from_zipcode] => 30260 [from_state] => GA [to_street] => 2324 stancrest ln [to_aptno] => [to_city] => lawrenceville [to_zipcode] => 30044 [to_state] => GA [country] => US [added] => 2017-08-23 21:47:07.505538 [status] => 1 [loc] => 38.101.241.200 )
     */
}
