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

class Vehicle extends CI_Controller {

	public function __construct() {
		parent::__construct();
		date_default_timezone_set("Asia/Kolkata");
		$this->load->model('Vehicle_model');
		if(!$this->session->userdata('logged_in')) {
			redirect(base_url());
		}
	}

	public function vehicleSearch(){
		$return_arr = array('status'=>'0');
        if(!isset($_POST) || empty($_POST) || !isset($_POST['searchType']) || empty($_POST['searchType']) || !isset($_POST['vehLocation']) || empty($vehLocation = $_POST['vehLocation'])){
            echo json_encode($return_arr);exit;
        }
        $vehTrim = $vehEngine = '';
        if(isset($_POST['vehTrim']) && !empty($_POST['vehTrim'])){
            $vehTrim = $_POST['vehTrim'];
        }
        if(isset($_POST['vehEngine']) && !empty($_POST['vehEngine'])){
            $vehEngine = $_POST['vehEngine'];
        }
        $url = "";
        $searchType = $_POST['searchType'];
        $vehicle_data = array('car_location'=>$vehLocation);
        $this->load->model('Settings_model');
        $settings = $this->Settings_model->settings_viewing();
        if($searchType == 1 && 
           isset($_POST['vehYear']) && !empty($_POST['vehYear']) && 
    	   isset($_POST['vehModel']) && !empty($_POST['vehModel']) && 
    	   isset($_POST['vehMaker']) && !empty($_POST['vehMaker'])){
            $vehicle_data['car_maker'] = $_POST['vehMaker'];
            $vehicle_data['car_model'] = $_POST['vehModel'];
            $vehicle_data['car_model_year'] = $_POST['vehYear'];
            $url = "https://specifications.vinaudit.com/v3/selections?format=json&key=".
                    urlencode($settings['vin_audit_api'])."&id=".urlencode($_POST['vehYear'])."_".
                    urlencode($_POST['vehMaker'])."_".urlencode($_POST['vehModel']);
        }
        else if($searchType == 2 && isset($_POST['vehVin']) && !empty($_POST['vehVin'])){
            $vehicle_data['car_vin'] = $_POST['vehVin'];
            $url = "https://specifications.vinaudit.com/v3/specifications?format=json&key=".urlencode($settings['vin_audit_api'])."&vin=".urlencode($_POST['vehVin']);
        }
        if(!empty($url)){
            $vehData=file_get_contents($url);
            if(empty($vehData) || empty($vehData = json_decode($vehData,true))){
                echo json_encode($return_arr);exit;
            }
            if(!isset($vehData['success']) || empty($vehData['success']) || $vehData['success']==false ||
               ((!isset($vehData['attributes']) || empty($vehData['attributes'])) && 
                (!isset($vehData['selections']) || empty($vehData['selections'])))){
                $return_arr['status'] = 2;
                echo json_encode($return_arr);exit;
            }
            $lat_lng = getLocationLatLng($vehLocation);
            if(empty($lat_lng)){
                $return_arr['status'] = 3;
                echo json_encode($return_arr);exit;
            }
            if($searchType == 2){
                $vehDetails['vehicle'] = $vehData['attributes']['year'].' '.
                                         $vehData['attributes']['make'].' '.
                                         $vehData['attributes']['model'].' '.
                                         $vehData['attributes']['trim'];
                $vehDetails['year']    = $vehData['attributes']['year'];
                $vehDetails['make']    = $vehData['attributes']['make'];
                $vehDetails['trim']    = $vehData['attributes']['trim'];
                $vehDetails['model']   = $vehData['attributes']['model'];
                $vehDetails['engine']  = $vehData['attributes']['engine'];
                $vehicle_data['car_maker']      = $vehDetails['make'];
                $vehicle_data['car_model']      = $vehDetails['model'];
                $vehicle_data['car_model_year'] = $vehDetails['year'];
            } else if($searchType == 1){
                $vehSele = $vehData['selections'];
                $vehDetails['year']    = $vehSele['years'][0]['name'];
                $vehDetails['make']    = $vehSele['years'][0]['makes'][0]['name'];
                $vehDetails['model']   = $vehSele['years'][0]['makes'][0]['models'][0]['name'];
                $vehDetails['vehicle'] = $vehDetails['year'].' '.$vehDetails['make'].' '.
                                         $vehDetails['model'].' '.$vehTrim;
                $vehDetails['trim']             = $vehTrim;
                $vehDetails['engine']           = $vehEngine;
                $vehicle_data['car_maker']      = $vehDetails['make'];
                $vehicle_data['car_model']      = $vehDetails['model'];
                $vehicle_data['car_model_year'] = $vehDetails['year'];
            }
            $vehicle_data['car_name']     = $vehDetails['vehicle'];
            $vehicle_data['car_loc_lat']  = $lat_lng['lat'];
            $vehicle_data['car_loc_lng']  = $lat_lng['lng'];
            $vehicle_data['vehicle_data'] = json_encode($vehDetails);
            $car_id = $this->Vehicle_model->addVehicle($vehicle_data);
            if(!empty($car_id)){
                $return_arr['status']     = '1';
                $return_arr['car_id']     = $car_id;
                $return_arr['veh_data']   = $vehDetails;
                $return_arr['searchType'] = $searchType;
            }
        }
        echo json_encode($return_arr);exit;
	}

    function updateUserCarStatus(){
        $return_arr = array('status'=>'0');
        if(!isset($_POST) || empty($_POST) || 
           !isset($_POST['car_id']) || empty($car_id = $_POST['car_id']) || 
           !isset($_POST['action']) || empty($action = $_POST['action'])){
            echo json_encode($return_arr); exit;
        }
        $return_arr['status'] = $this->Vehicle_model->changeStatus($car_id,$action);
        echo json_encode($return_arr); exit;
    }

    public function addVehBrand(){
        $template['page'] = 'Vehicles/addBrand';
        $template['pTitle'] = "Add Vehicle Brand";
        $template['pDescription'] = "Add Vehicle Brand"; 
        $template['menu'] = "Vehicle Brand Management";
        $template['smenu'] = "View Brand";
        $template['brand_id'] = '';
        $template['vehBrand_data'] = $this->Vehicle_model->getVehBrand('',1);
        $this->load->view('template',$template);
    }

    public function viewVehBrand(){
        $template['page'] = 'Vehicles/viewBrand';
        $template['menu'] = 'Vehicles Brand Management';
        $template['smenu'] = 'View Vehicles Brand ';
        $template['pTitle'] = "View Vehicles Brand ";
        $template['pDescription'] = "View and Manage Vehicles Brands";
        $template['vehBrand_data'] = $this->Vehicle_model->getVehBrand('',1);
        $this->load->view('template',$template);
    }

    function changeVehicleStatus($brand_id = '',$status = '1'){
        $flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
        if(empty($brand_id) || !is_numeric($brand_id = decode_param($brand_id))){
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Vehicle/viewVehBrand'));
        }
        $status = $this->Vehicle_model->changeVehicleStatus($brand_id,$status);
        if(!$status){
            $this->session->set_flashdata('message',$flashMsg);
        }
        redirect(base_url('Vehicle/viewVehBrand'));
    }

    public function createbrand(){
        $err = 0;
        $errMsg = '';
        $flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
        if(!isset($_POST) || empty($_POST)){
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Vehicle/addVehBrand'));
        }
        if($err == 0 && (!isset($_POST['maker']) || empty($_POST['maker']))){
            $err = 1;
            $errMsg = 'Vehicle Brand is Required';
        }
        if($err == 1){
            $flashMsg['message'] = $errMsg;
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Vehicle/addVehBrand'));
        }
        $brand_id = $this->Vehicle_model->addBrand($_POST);
        if($brand_id != '0'){
            $flashMsg =array('message'=>'Successfully Updated Brand..!','class'=>'success');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Vehicle/viewVehBrand'));
        }else {
            $flashMsg =array('message'=>'Brand Name Already Exist','class'=>'error');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Vehicle/addVehBrand'));
        }
    }

    public function editVehBrand($brand_id){
        $flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
        if(empty($brand_id) || !is_numeric($brand_id = decode_param($brand_id))){
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Vehicle/viewVehBrand'));
        }
        $template['page'] = 'Vehicles/addBrand';
        $template['menu'] = 'Brand Management';
        $template['smenu'] = 'Edit brand';
        $template['pTitle'] = "Edit brand";
        $template['pDescription'] = "Update brand Name";
        $template['brand_id'] = encode_param($brand_id);
        $template['vehBrand_data'] = $this->Vehicle_model->getVehBrand($brand_id,1);
        $this->load->view('template',$template);
    }

    public function updateVehBrand($brand_id = ''){
        $err = 0;
        $errMsg = '';
        $flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
        if(empty($brand_id) || !isset($_POST) || empty($_POST) || !is_numeric(decode_param($brand_id))){
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Vehicle/viewVehBrand'));
        }
        if(!isset($_POST) || empty($_POST)){
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Vehicle/addVehBrand'));
        }
        if($err == 0 && (!isset($_POST['maker']) || empty($_POST['maker']))){
            $err = 1;
            $errMsg = 'Vehicle Brand is Required';
        }
        if($err == 1){
            $flashMsg['message'] = $errMsg;
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Vehicle/addVehBrand'));
        }
        $brand = $this->Vehicle_model->updateVehBrand(decode_param($brand_id),$_POST);
        if($brand){
            $flashMsg =array('message'=>'Successfully Updated Brand Data..!','class'=>'success');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Vehicle/viewVehBrand'));
        } else {
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Vehicle/editVehBrand/'.$brand_id));
        }
    }

    public function addVehModel(){
        $template['page'] = 'Vehicles/addModel';
        $template['pTitle'] = "Add Vehicles";
        $template['pDescription'] = "Add Vehicles"; 
        $template['menu'] = "Vehicles Management";
        $template['smenu'] = "View Vehicles";
        $template['model_id'] = '';
        $template['vehBrand_data'] = $this->Vehicle_model->getVehBrand('',1);
        $template['vehModel_data'] = $this->Vehicle_model->getVehModel('',1);
        $this->load->view('template',$template);
    }

     public function viewVehModel(){
        $template['page'] = 'Vehicles/viewModel';
        $template['menu'] = 'Vehicles Management';
        $template['smenu'] = 'View Vehicles';
        $template['pTitle'] = "View Vehicles";
        $template['pDescription'] = "View and Manage Vehicles";
        //$template['vehModel_data'] = $this->Vehicle_model->getVehModel('',1);
        $this->load->view('template',$template);
    }

    function changeModelStatus($model_id = '',$status = '1'){
        $flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
        if(empty($model_id) || !is_numeric($model_id = decode_param($model_id))){
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Vehicle/viewVehModel'));
        }
        $status = $this->Vehicle_model->changeVehicleStatus($model_id,$status,'2');
        if(!$status){
            $this->session->set_flashdata('message',$flashMsg);
        }
        redirect(base_url('Vehicle/viewVehModel'));
    }

    public function createModel(){
        $err = 0;
        $errMsg = '';
        $flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
        if(!isset($_POST) || empty($_POST)){
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Vehicle/addVehModel'));
        }
         if($err == 0 && (!isset($_POST['vehYear']) || empty($_POST['vehYear']))){
            $err = 1;
            $errMsg = 'Please Select an year';
        }else if($err == 0 && (!isset($_POST['veh_brand_id']) || empty($_POST['veh_brand_id']))){
            $err = 1;
            $errMsg = 'Please Select a Brand';
        }else if($err == 0 && (!isset($_POST['model']) || empty($_POST['model']))){
            $err = 1;
            $errMsg = 'Vehicle Model is Required';
        }
        if($err == 1){
            $flashMsg['message'] = $errMsg;
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Vehicle/addVehModel'));
        }
        $model_id = $this->Vehicle_model->addModel($_POST);
        if($model_id != '0'){
            $flashMsg =array('message'=>'Successfully Updated Vehicle Model..!','class'=>'success');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Vehicle/viewVehModel'));
        }else {
            $flashMsg =array('message'=>'Model Name Already Exist','class'=>'error');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Vehicle/addVehModel'));
        }
    }

    public function editVehModel($veh_id){
        $flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
        if(empty($veh_id) || !is_numeric($veh_id = decode_param($veh_id))){
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Vehicle/viewVehModel'));
        }
        $template['page'] = 'Vehicles/addModel';
        $template['menu'] = 'Edit Vehicle Management';
        $template['smenu'] = 'Edit Vehicle';
        $template['pTitle'] = "Edit Vehicle Management";
        $template['pDescription'] = "Update Vehicle Name";
        $template['vehicle_id'] = encode_param($veh_id);
        $template['vehBrand_data'] = $this->Vehicle_model->getVehBrand('',1);
        $template['vehModel_data'] = $this->Vehicle_model->getVehModel('',1);
        $template['vehModel_datas'] = $this->Vehicle_model->getVehModel('',1,'',$veh_id);
       // pr($template['vehModel_datas']);
        $this->load->view('template',$template);
    }

    public function updateVehModel($vehicle_id = ''){
        $err = 0;
        $errMsg = '';
        $flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
        if(empty($vehicle_id) || !isset($_POST) || empty($_POST) || !is_numeric(decode_param($vehicle_id))){
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Vehicle/viewVehModel'));
        }
        if(!isset($_POST) || empty($_POST)){
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Vehicle/addVehModel'));
        }
        if($err == 0 && (!isset($_POST['vehYear']) || empty($_POST['vehYear']))){
            $err = 1;
            $errMsg = 'Please Select an year';
        }else if($err == 0 && (!isset($_POST['veh_brand_id']) || empty($_POST['veh_brand_id']))){
            $err = 1;
            $errMsg = 'Please Select a Brand';
        }else if($err == 0 && (!isset($_POST['model']) || empty($_POST['model']))){
            $err = 1;
            $errMsg = 'Vehicle Model is Required';
        }
        if($err == 1){
            $flashMsg['message'] = $errMsg;
            $this->session->set_flashdata('message',$flashMsg);
            redirect(base_url('Vehicle/addVehModel'));
        }
        $model = $this->Vehicle_model->updateVehModel(decode_param($vehicle_id),$_POST);
        if($model){
            $flashMsg =array('message'=>'Successfully Updated Vehicle Model..!','class'=>'success');
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Vehicle/viewVehModel'));
        } else {
            $this->session->set_flashdata('message', $flashMsg);
            redirect(base_url('Vehicle/editVehModel/'.$model_id));
        }
    }
    
    public function getVehModel(){
        $return_arr = array('status'=>'0');
        if(!isset($_POST) || empty($_POST) || !isset($_POST['id']) || empty($_POST['id']) || !isset($_POST['year']) || empty($_POST['year'])){
            echo json_encode($return_arr);exit;
        }
        $type = (isset($_POST['type']) && $_POST['type'] == 1)?1:0;
        $result = $this->Vehicle_model->getVehModel('',1,$_POST);
        $results = '<option value="-1">No Models</option>';
        if($result){
            $modArr = array();
            $results = '<option value="-1">Choose Vehicle Model</option>';
            foreach ($result as $model) {
                if($type == 1 && in_array($model->model,$modArr)){
                    continue;
                }
                $modArr[] = $model->model;
                $results .= '<option value="'.$model->veh_model_id.'" vehicle_id="'.$model->veh_id.'" model="'.$model->model.'">';
                $results .= $model->model;
                if($type == 0){
                    $results .= (!empty($model->trim))?' '.$model->trim:'';
                    $results .= (!empty($model->engine))?', '.$model->engine:'';
                }
                $results .= '</option>';
            }
        }
        echo $results;
    }

    public function getVehTrim(){
        $return_arr = array('status'=>'0');
        if(!isset($_POST) || empty($_POST) || !isset($_POST['id']) || empty($_POST['id']) || !isset($_POST['year']) || empty($_POST['year']) || !isset($_POST['vehModel']) || empty($_POST['vehModel'])){
            echo json_encode($return_arr);exit;
        }
        $result = $this->Vehicle_model->getVehModel($_POST['vehModel'],1,$_POST);
        $results = '<option value="-1">No Trims</option>';
        if($result){
            $trim = array();
           // $results = '<option value="-1">Choose Vehicle Trim</option>';
            $results = '';
            foreach ($result as $key => $trim) {
                if(empty($trim->trim)){
                    unset($result[$key]);
                    continue;
                }
                $results .= '<option value="'.$trim->veh_id.'" trim="'.$trim->trim.'">'.$trim->trim.'</option>';
            }
        }
        echo (!empty($results))?$results:'1';
    }

    public function get_all_activity(){
        $data = $_GET;
        $columns = array("vehicles.year","vehicles_brand.maker","vehicle_models.model_name","vehicles.trim","vehicles.engine","vehicles.status");


        $value['search'] = $data['search']['value'];
        $value['start'] = $data['start'];
        $value['length'] = $data['length'];

       // $search_box = array('bookingId','name','operatorName','travelDate','mobile','amount','payType','Action');

        $limit = count($data['columns']);

        $value['where'] = '';
        $where_data = array();
        
        if(!empty($value['search'])) {
            $where = array();
            foreach($columns as $c) {
                $where_data[] = $c." like '%".$value['search']."%' ";
            }
            $where = implode(" OR ", $where_data);
            $where = "(".$where.")";
            $value['where'] = $where;
        }

        $value['order_type'] = $data['order'][0]['dir'];

        
        $activity = $this->Vehicle_model->get_activity($value);
        $all_activity = $this->Vehicle_model->get_activity();

         $filtered = count($all_activity);
        if($value['where']!='') {
            $value['length'] = '-1';
            $page_activity = $this->Vehicle_model->get_activity($value);
            $filtered = count($page_activity);
        }
        
        
        $data = array();
        if($activity) {
            foreach ($activity  as $r) {
                $edit = "<a class='btn btn-sm btn-primary' href=editVehModel/".encode_param($r->veh_id).">
                            <i class='fa fa-fw fa-edit'></i>Edit
                        </a>";
                $del  = "<a class='btn btn-sm btn-danger' onClick='return doconfirm()' 
                          href=changeModelStatus/".encode_param($r->veh_id)."/2>
                          <i class='fa fa-fw fa-trash'></i>Delete
                        </a>";
                $activate = ($r->status == '1')?
                    "<a class='btn btn-sm btn-success' style='background-color:#ac2925' href=changeModelStatus/".encode_param($r->veh_id)."/0>
                        <i class='fa fa-cog'></i> De-activate
                      </a>":
                    "<a class='btn btn-sm btn-success' href=changeModelStatus/".encode_param($r->veh_id)."/1>
                        <i class='fa fa-cog'></i> Activate
                      </a>";

                array_push($data, array(
                    $r->year,
                    $r->maker,
                    $r->model,
                    ($r->trim != '')?$r->trim:'-',
                    ($r->engine != '')?$r->engine:'-',
                    ($r->status == '1')?'Active':'De-activate',
                    $edit.' '.$del.' '.$activate
                ));
            }
        }
 
        echo json_encode(array('recordsFiltered' => $filtered, 'recordsTotal' => count($all_activity), 'data' => $data));

    }   
}
?>