<?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 Vehicle Model";
        $template['pDescription'] = "Add Vehicle Model"; 
        $template['menu'] = "Vehicle Model Management";
        $template['smenu'] = "View Model";
        $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 Model Management';
        $template['smenu'] = 'View Vehicles Model ';
        $template['pTitle'] = "View Vehicles Model ";
        $template['pDescription'] = "View and Manage Vehicles Models";

        $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['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($model_id){
        $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'));
        }

        $template['page'] = 'Vehicles/addModel';
        $template['menu'] = 'Model Management';
        $template['smenu'] = 'Edit Model';
        $template['pTitle'] = "Edit Model";
        $template['pDescription'] = "Update Model Name";

        $template['model_id'] = encode_param($model_id);
        $template['vehBrand_data'] = $this->Vehicle_model->getVehBrand('',1);
        $template['vehModel_data'] = $this->Vehicle_model->getVehModel($model_id,1);
        //pr($template['vehModel_data']);

        $this->load->view('template',$template);
    }

    public function updateVehModel($model_id = ''){
        $err = 0;
        $errMsg = '';
        $flashMsg = array('message'=>'Something went wrong, please try again..!','class'=>'error');
        if(empty($model_id) || !isset($_POST) || empty($_POST) || !is_numeric(decode_param($model_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['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($model_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']) ||
           empty($_POST['id'])){
            echo json_encode($return_arr);exit;
        }
        $type = (isset($_POST['type']) && $_POST['type'] == 1)?1:0;
        $result = $this->Vehicle_model->getVehModel('',1,$_POST['id']);
        $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_modal_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;
    }
}
?>