<?php

namespace Dashboard\Controller;

use Application\Controller\RestAPIClientController;
use Dashboard\Form\{
    VehicleDetailSearchForm,
    VehicleDetailMapDriverForm,
    VehicleDetailAddNewCabForm,
    VehicleDetailAddDriverLoginForm,
    DriverManagementLoginForm,
    DriverManagementLoginFormFilter,
    ProfilePersonalForm,
    VehicleDetailMappingForm
};
use Zend\View\Model\{
    ViewModel,
    JsonModel
};
use Zend\Json\Json;
use Zend\Session\Container;
use Zend\Debug\Debug;
use Dashboard\Model\Vehicle;
use Dashboard\Model\User;

class VehicleDetailsController extends RestAPIClientController {

    private $owned = 1;
    private $attached = 2;

    public function __construct() {
        $this->vehicleModel = new Vehicle();
        $this->userModel = new User();
    }

    /**
     * index
     * @return ViewModel
     */
    public function indexAction() {
        $sessionContainer = new Container('userlogin');
        $userData = $sessionContainer->userData;
        $userTypeId = $userData['user_type_id'];
        $userId = $userData['user_id'];
        $status=1;
        VehicleDetailSearchForm::$modelYear = $this->getModelYearList();
        VehicleDetailSearchForm::$cab_type = $this->vehicleModel->getVehicleTypeList();
        $form = new VehicleDetailSearchForm();
        $request = $this->getRequest();
        $data = [];
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $status=(isset($post['status']))? $post['status']:'';
            $form->setData($request->getPost());
            $data = [
                'vehicle_name' => $post['vehicle_name'],
                'vehicle_number' => $post['vehicle_number'],
                'vehicle_model' => (isset($post['model_year']))? $post['model_year']:'',
                'vehicle_type_id' => $post['vehicle_type'],
                'status' => $post['status']
            ];

            $data = array_filter($data);
            $data['status'] = $post['status'];
           //echo'<pre>';print_r($data);die();
        }
         if($userTypeId!='10'){
                $data['created_by']=$userId;
            }

        $vehicleList = $this->getAllVehicleList($data);
        $viewModel = new ViewModel(['form' => $form, 'vehicleListing' => $vehicleList, 'status' => $status]);
        return $viewModel;
    }

    /**
     * index
     * @return ViewModel
     */
    public function vehicleMappingAction() {
        $status="1";
        $sessionContainer = new Container('userlogin');
        $userData = $sessionContainer->userData;
        $userTypeId = $userData['user_type_id'];
        $userId = $userData['user_id'];
        //$username = $loginData['login_id'];
        VehicleDetailSearchForm::$modelYear = $this->getModelYearList();
        VehicleDetailSearchForm::$cab_type = $this->vehicleModel->getVehicleTypeList();
        $form = new VehicleDetailSearchForm();
        $request = $this->getRequest();
        $data = [];
        $data2 = [];
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $status=(isset($post['status']))? $post['status']:'';
            //Debug::dump($post); exit;
            $form->setData($request->getPost());
            $data = [
                'vehicle_type_id' => $post['vehicle_type'],
                'vehicle_model_id' => $post['vehicle_model_id'],
                'model_year' => $post['model_year'],
                'vehicle_no' => $post['vehicle_number'],
                'driver_name' => $post['driver_name'],
                'state_id' => $post['state_value'],
                'city_id' => $post['city_value'],
                //'mapping_status' => $post['status']

            ];
            //echo'<pre>';print_r($data);die();
            $data = array_filter($data);
            $data['mapping_status'] = $status;
            //echo'<pre>';print_r($data);die();
        }
        //$data['user_id']=$userId;
        if($userTypeId!='10'){
                $data['created_by']=$userId;               
                //$data['user_id'] = $userId;               
          }
        
        $data2['user_type_id'] = '1,2,3,5,6,7,8';
        if($userTypeId != 10){
           $data2['parent_id'] = $userId;
        }
        $data['company_id'] = $this->config()->getConfig()->company->companyId;
        
        // Vendor' driver list //
        $userListing = $this->userModel->getUserList($data2);
        if(!empty($userListing['data']['responsedata'])){
            $vendorDriverListing = $userListing['data']['responsedata'];
        }
        // End //
        
        $vehicleList = $this->getAllVehicleList($data);     //Get vendor vehicle list //
        //$vehicleList = $this->getAllMappingVehicleList($data);  // old function comment by verma 3-march-2020
       
        $viewModel = new ViewModel(['form' => $form, 'vehicleListing' => $vehicleList, 'status' => $status,'vendorDriverListing'=>$vendorDriverListing]);
        return $viewModel;
    }

    /**
     * Map Driver
     * @return ViewModel
     
    public function mapDriverActionOld() {
        $request = $this->getRequest();

        $stateList = $this->getStateList();
        VehicleDetailMapDriverForm::$stateList = $stateList;

        $form = new VehicleDetailMapDriverForm();

        if ($request->isPost()) {

        }

        $viewModel = new ViewModel(['form' => $form]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }*/

    /**
     * Map Driver
     * @return ViewModel
     */
    public function mapDriverAction() {
        $request = $this->getRequest();
        VehicleDetailMapDriverForm::$cabType = $this->vehicleModel->getVehicleTypeList();

        $form = new VehicleDetailMapDriverForm();

        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
              $mappingId     =  $post['mappingId'];
              $driverId      =  $post['driver_id'];
              $vehicle_master_id  =  $post['vehicle_master_id'];
            $data = $this->vehicleModel->updateVehicleDriverMapping($mappingId,$driverId,$vehicle_master_id);

        }

        $viewModel = new ViewModel(['form' => $form]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function mappingDriverAction() { 
        $viewModel = new ViewModel();
        $data = [];
        $val = [];
        $driverlistparam = [];
        $vehicleListJsonDataArray = [];
        $driverListJsonArray = [];
        
        $sessionContainer = new Container('userlogin');
        $userData = $sessionContainer->userData;
        $userTypeId = $userData['user_type_id'];
        $userId = $userData['user_id'];
        if($userTypeId!='10'){
            $data2['created_by'] = $userId;
            $driverlistparam['parent_id'] = $userId;
        }
        $vehicleList = $this->getAllVehicleList($data2); 
        if(!empty($vehicleList)){
            foreach($vehicleList as $value){
                      $vehicleListJsonDataArray[$value['vehicle_master_id']] = $value['vehicle_model_name'].'-'.$value['vehicle_no'].' ('.$value['vehicle_type_name'].')';
            }
             $vehicleListJsonDataArray;           
        }
        
        // Vendor' driver list //
        $userListing = $this->userModel->getUserList($driverlistparam);
        if(!empty($userListing['data']['responsedata'])){
            $vendorDriverListing = $userListing['data']['responsedata'];
             foreach($vendorDriverListing as $value){
                      $driverListJsonArray[$value['user_id']] = $value['name'].'-'.$value['mobile'];
            }
             $driverListJsonArray;  
        }
        
        VehicleDetailMappingForm::$modelYear = $this->getModelYearList();
        VehicleDetailMappingForm::$vendor_drivers = $driverListJsonArray;
        VehicleDetailMappingForm::$vehicle_list = $vehicleListJsonDataArray;
        VehicleDetailMappingForm::$cab_type = $this->vehicleModel->getVehicleTypeList();


        $form = new VehicleDetailMappingForm();
        $request = $this->getRequest();
        $msg = '';
        $result = '';
        $mapped_id = '';
        $data = $this->getRequest()->getPost();
        $val['vehicle_master_id'] = $data['vmid'];
        $val['mapping_id'] = $data['vmpid'];
        $mapped_id = $data['vmpid'];

        //$getres = $this->getAllMappingVehicleList($val);
        $getres = $this->getAllVehicleList($val);   
        //echo '<pre>';print_r($vehicleList);die();
        if (isset($getres[0])) {
            $result = $getres[0];
        }

        if ($request->isXmlHttpRequest()) {

            $postdata = $request->getPost()->toArray();
            //echo '<pre>';print_r($postdata);die();

            if (isset($postdata['mapped_id'])) {

              //  if ($form->isValid() ) {

                $form->setData($postdata);
                $mapped_id = isset($postdata['mapped_id'])?$postdata['mapped_id']:0;
                $vehicle_master_id = $postdata['vehicle_name_mapping'];
                $driverId = $postdata['driver_name'];
                $map_status = $postdata['map_status'];

                

                $resdata = $this->vehicleModel->updateVehicleDriverMapping($mapped_id, $driverId, $vehicle_master_id, $map_status);


                if ($resdata['response']['affectedRows'] > 0) {
                    $status = true;

                    $msg = " Updated Successfully";
                } else {
                    $status = false;
                    $msg = "Could Not Updated !";
                }
                $result = ['result' => $status, 'message' => $msg];

//            } else {
//                $result = ['result' => false, 'message' => $form->getMessages()];
//            }
                if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                    $viewModel = new JsonModel();
                }
                $viewModel->setVariables(['data' => $result]);
                return $viewModel;
            }
        }
        
        if($userTypeId != 10){
          
        }
        $data['company_id'] = $this->config()->getConfig()->company->companyId;
        
       
      //  $vehicleList = $this->getAllMappingVehicleList($data = []); 
        
        $viewModel = new ViewModel(['form' => $form, 'result' => $result, 'mapped_id' => $mapped_id]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /*     * s
     * AddDriver
     * @return ViewModel
     */

    public function addDriverLoginPageAction() {
        //write code here...
        $form = new VehicleDetailAddDriverLoginForm();
        $viewModel = new ViewModel(['form' => $form]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /**
     * Add new Cab
     * @return ViewModel
     */
    public function addNewCabAction() {
        $sessionContainer = new Container('userlogin');
        $user_id = $sessionContainer->user_id;
        VehicleDetailAddNewCabForm::$cabType = $this->vehicleModel->getVehicleTypeList();
        VehicleDetailAddNewCabForm::$ignitionType = $this->getFuelTypeList();
        VehicleDetailAddNewCabForm::$vehicleColor = $this->vehicleModel->getVehicleColour();
        VehicleDetailAddNewCabForm::$amenities = $this->getVehicleAmenitiesList();
        VehicleDetailAddNewCabForm::$modelYear = $this->getModelYearList();
        $request = $this->getRequest();
        $form = new VehicleDetailAddNewCabForm();
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $form->setData($request->getPost());
            if ($post['vehicle_owner'] == $this->attached) {
                $form->getInputFilter()->get('owner_name')->setRequired(true);
                $form->getInputFilter()->get('mobile_number')->setRequired(true);
                $form->get('vehicle_attach_selected')->setValue(1);
            }
            if ($post['vehicle_owner'] == $this->owned) {
                $form->getInputFilter()->get('owner_name')->setRequired(false);
                $form->getInputFilter()->get('mobile_number')->setRequired(false);
                $form->get('vehicle_owned_selected')->setValue(0);
            }

            if ($form->isValid()) {
                $postData = $request->getPost();
                $finalData = [];
                $finalData = [
                    'vehicle_type_id' => $postData['vehicle_type'],
                    'name' => $postData['vehicle_name'],
                    //'vehicle_value' => $postData['vehicle_model_id'],
                    'vehicle_exist_id' => $postData['vehicle_model_id'],
                    'ignition_type_id' => $postData['ignition_type'],
                    'color' => $postData['vehicle_color'],
                    'vehicle_owner_type' => ($postData['vehicle_owner'] == '1' ? 'Owned' : 'Attached'),
                    'vehicle_owner_name' => $postData['owner_name'],
                    'vehicle_owner_mobile' => $postData['mobile_number'],
                    'permit_exp_date' => date('Y-m-d',strtotime($postData['permit_expiry_date'])),
                    'insurance_validity' => date('Y-m-d',strtotime($postData['insurance_validity'])),
                    'model' => $postData['model_year'],
                    'vehicle_no' => $postData['vehicle_number'],
                    'passenger' => $postData['passengers'],
                    'large_suitcase' => $postData['large_suitcase'],
                    'small_suitcase' => $postData['small_suitcase'],
                    'vehicle_amenities' => implode(",", $postData['vehicle_amenities']),
                    'created_date' => date('Y-m-d H:i:s'),
                    'created_by'=> $user_id
                ];
                $finalData = array_filter($finalData);
                $JsonData = $this->insertVehicleDetails($finalData);
                //echo '<pre>';print_r($JsonData);die();
                if ($JsonData['response']['affectedRows'] > 0) {
                    $this->redirect()->toRoute('vehicle-details', ['action' => 'index']);
                }
            }

        }


        $viewModel = new ViewModel(['form' => $form]);
        return $viewModel;
    }

    /**
     * Edit new Cab
     * @return ViewModel
     */
    public function editNewCabAction() {
        $sessionContainer = new Container('userlogin');
        $user_id = $sessionContainer->user_id;
        $id='';
        $vehicleColor='';
        $vehicleDetails=[];
        VehicleDetailAddNewCabForm::$cabType = $this->vehicleModel->getVehicleTypeList();
        VehicleDetailAddNewCabForm::$ignitionType = $this->getFuelTypeList();
        VehicleDetailAddNewCabForm::$amenities = $this->getVehicleAmenitiesList();
        VehicleDetailAddNewCabForm::$modelYear = $this->getModelYearList();
        VehicleDetailAddNewCabForm::$vehicleColor = $this->vehicleModel->getVehicleColour();
        $form = new VehicleDetailAddNewCabForm();
        if (intval($this->params('id'))) {
            $id = intval($this->params('id'));
        }
        if (!empty($id)) {
            $data['vehicle_master_id'] = $id;
            $JsonData = $this->getAllVehicleList($data);
            $vehicleDetails = isset($JsonData[0])?$JsonData[0]:0;
            //echo '<pre>';print_r($vehicleDetails);die();
            $vehicleColor=$vehicleDetails['color'];
            $form->get('id')->setValue($id);
            $form->get('model_year')->setValue($vehicleDetails['model']);
            $form->get('vehicle_type')->setValue($vehicleDetails['vehicle_type_id']);
            $form->get('vehicle_name')->setValue($vehicleDetails['vehicle_model_name']);
            $form->get('vehicle_model_id')->setValue($vehicleDetails['vehicle_model_id']);
            $form->get('permit_expiry_date')->setValue(date('d-m-Y', strtotime($vehicleDetails['permit_exp_date'])));
            $form->get('insurance_validity')->setValue(date('d-m-Y', strtotime($vehicleDetails['insurance_validity'])));
            $form->get('ignition_type')->setValue($vehicleDetails['ignition_type_id']);
            $form->get('vehicle_color')->setValue($vehicleDetails['color']);
            $form->get('vehicle_number')->setValue($vehicleDetails['vehicle_no']);
            $form->get('passengers')->setValue($vehicleDetails['passenger']);
            $form->get('large_suitcase')->setValue($vehicleDetails['large_suitcase']);
            $form->get('small_suitcase')->setValue($vehicleDetails['small_suitcase']);

            if ($vehicleDetails['vehicle_owner_type'] == 'Owned') {
                $form->get('owner_name')->setValue('');
                $form->get('mobile_number')->setValue('');
                $form->get('vehicle_owned_selected')->setValue(0);
            }

            if ($vehicleDetails['vehicle_owner_type'] == 'Attached') {
                $form->get('owner_name')->setValue($vehicleDetails['vehicle_owner_name']);
                $form->get('mobile_number')->setValue($vehicleDetails['vehicle_owner_mobile']);
                $form->get('vehicle_attach_selected')->setValue(1);
            }
        }
        $request = $this->getRequest();

        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $form->setData($request->getPost());
            $id = $post['id'];
            if ($post['vehicle_owner'] == $this->attached) {
                $form->getInputFilter()->get('owner_name')->setRequired(true);
                $form->getInputFilter()->get('mobile_number')->setRequired(true);
                $form->get('vehicle_attach_selected')->setValue(1);
            }
            if ($post['vehicle_owner'] == $this->owned) {
                $form->getInputFilter()->get('owner_name')->setRequired(false);
                $form->getInputFilter()->get('mobile_number')->setRequired(false);
                $form->get('vehicle_owned_selected')->setValue(0);
            }

            if ($form->isValid()) {
                $postData = $request->getPost();
                $finalData = [];
                $finalData = [
                    'id' => $postData['id'],
                    'vehicle_type_id' => $postData['vehicle_type'],
                    'name' => $postData['vehicle_name'],
                    'vehicle_exist_id' => $postData['vehicle_model_id'],
                    'ignition_type_id' => $postData['ignition_type'],
                    'color' => $postData['vehicle_color'],
                    'vehicle_owner_type' => ($postData['vehicle_owner'] == '1' ? 'Owned' : 'Attached'),
                    'vehicle_owner_name' => $postData['owner_name'],
                    'vehicle_owner_mobile' => $postData['mobile_number'],
                    'permit_exp_date' => date('Y-m-d',strtotime($postData['permit_expiry_date'])),
                    'insurance_validity' => date('Y-m-d',strtotime($postData['insurance_validity'])),
                    'model' => $postData['model_year'],
                    'vehicle_no' => $postData['vehicle_number'],
                    'passenger' => $postData['passengers'],
                    'large_suitcase' => $postData['large_suitcase'],
                    'small_suitcase' => $postData['small_suitcase'],
                    'vehicle_amenities' => implode(",", $postData['vehicle_amenities']),
                    'created_date' => date('Y-m-d'),
                    'modified_by' => $user_id
                ];
                $finalData = array_filter($finalData);

                $JsonData = $this->updateVehicleDetails($finalData);

                if ($JsonData['response']['affectedRows'] > 0) {
                    $this->redirect()->toRoute('vehicle-details', ['action' => 'index']);
                }
            }
        }

        $amenitiesList = $this->getVehicleModelAmenitiesList($id);
        $viewModel = new ViewModel(['form' => $form, 'vehicleDetails' => $vehicleDetails, 'amenitiesList' => $amenitiesList, 'id' => $id,'vehicleColor'=>$vehicleColor]);
        return $viewModel;
    }

    /**
     * Add Driver Login Page
     * @return ViewModel
     */
    public function addAction() {
        //echo 'raza';die;

        $request = $this->getRequest();
        $form = new DriverManagementLoginForm();

        if ($request->isPost()) {
            $form->setData($request->getPost());

            $sessionContainer = new Container('driverlogindetail');
            $loginData = $this->getRequest()->getPost();
            $sessionContainer->loginData = $loginData;

            $driverRegistrationFilter = new DriverManagementLoginFormFilter();
            $form->setInputFilter($driverRegistrationFilter);

            if ($form->isValid()) {
                $this->redirect()->toRoute('vehicle-details', [
                    'action' => 'add-driver-detail'
                        ]
                );
            }
        }

        $viewModel = new ViewModel(['form' => $form]);
        return $viewModel;
    }

    /**
     * Add Driver Detail...
     * @return ViewModel
     */
    public function addDriverDetailAction() {
        //echo 'raza';die;

        $request = $this->getRequest();
        $form = new ProfilePersonalForm();

        $viewModel = new ViewModel(['form' => $form]);
        return $viewModel;
    }


    /**
     * Vehicle Details View Update Record
     * @return ViewModel
     */
    public function searchvehicleUpdateRecordAction() {
        //write code here...
        //  echo 'hello';die;

        $vehicleListing = [
            '0' => [
                'vehicle_model' => '2015',
                'vehicle_name' => 'suzuki',
                'vehicle_number' => 'DL AR 5678',
                'vehicle_type' => 'Sedan',
                'state_id' => 'Delhi',
                'city_id' => 'New Delhi',
                'driver' => 'niharika',
                'status' => 'Maped',
            ],
            '1' => [
                'vehicle_model' => '2016',
                'vehicle_name' => 'Suzuki',
                'vehicle_number' => 'DL AR 5678',
                'vehicle_type' => 'Sedan',
                'state_id' => 'Delhi',
                'city_id' => 'New Delhi',
                'driver' => 'Nitin',
                'status' => 'Maped',
            ]
        ];

        $viewModel = new ViewModel(['vehicleListing' => $vehicleListing]);
        $viewModel->setTemplate('/dashboard/vehicle-details/vehicle-listing');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /**
     *
     * Delete...
     * @return type
     */
    public function deleteAction() {
        $sessionContainer = new Container('userlogin');
        $user_id = $sessionContainer->user_id;
        $id = $this->params()->fromRoute('id');

        if($id !=''){
        $data = ['user_id' => $user_id, 'id' => $id, 'vehicle_status' => 2];
        $vehicle_status=$this->updateVehicleStatus($data);
        if ($vehicle_status['response']['status']=='success') {
                    $msg = "Data Deleted Successfully..";
                    $this->redirect()->toRoute('vehicle-details', ['action' => 'index']);
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                }
                else{
                    $msg = "Could Not Deleted..";
                    $this->redirect()->toRoute('vehicle-details', ['action' => 'index']);
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                }
        }

        return $this->redirect()->toRoute('vehicle-details', ['action' => 'index']);
    }

    /**
     * Ajax Call
     * @return type Description
     * Get City List...
     */
    public function getCityListAction() {
        $request = $this->getRequest();

        if ($request->isPost()) {
            $stateId = $request->getPost("state_id");
            $cityName = $this->getCityListByStateId($stateId);

            if (count($cityName))
                return new JsonModel(["Status" => "Success", "citylist" => $cityName]);
            else
                return new JsonModel(["Status" => "Failed", "citylist" => null]);
        }
    }

    /**
     * Get City List By StateId...
     * @param type $stateId
     * @return array
     */
    public function getCityListByStateId($stateId) {

        if ($stateId == 1) {
            $rowset = [
                '0' => ['id' => '1',
                    'city_name' => 'New Delhi'
                ]
            ];
        } elseif ($stateId == 2) {
            $rowset = [
                '0' => ['id' => '1',
                    'city_name' => 'Noida'
                ],
                '1' => ['id' => '2',
                    'city_name' => 'Lucknow'
                ],
                '2' => ['id' => '3',
                    'city_name' => 'Aligarh'
                ],
                '3' => ['id' => '4',
                    'city_name' => 'Meerut'
                ]
            ];
        } elseif ($stateId == 3) {
            $rowset = [
                '0' => ['id' => '1',
                    'city_name' => 'Gurugram'
                ],
                '1' => ['id' => '2',
                    'city_name' => 'Faridabad'
                ]
            ];
        } elseif ($stateId == 4) {
            $rowset = [
                '0' => ['id' => '1',
                    'city_name' => 'Patna'
                ],
                '1' => ['id' => '2',
                    'city_name' => 'Gaya'
                ],
                '2' => ['id' => '3',
                    'city_name' => 'Nawada'
                ],
                '3' => ['id' => '4',
                    'city_name' => 'Bhagalpur'
                ]
            ];
        }

        if (count($rowset)) {
            return $rowset;
        } else {
            return null;
        }
    }

    /**
     *
     * Driver List...
     * @return ViewModel
     */
    public function driverListAction() {

        $request = $this->getRequest();

        $postdata = $request->getPost();
        $postdata = $postdata['term'];

        //call API here...

        $driverList[] = [
            "label" => 'Subodh Kumar',
            "value" => '1'
        ];

        $view = new JsonModel($driverList);
        return $view;
    }

    /**
     *
     * Vehicle Number List...
     * @return ViewModel
     */
    public function vehicleNumberListAction() {
        $request = $this->getRequest();

        $postdata = $request->getPost();
        $postdata = $postdata['term'];
        //echo $postdata;die();
        //call API here...

        $vehicleNumberList[] = [
            "label" => 'DL-6768',
            "value" => '1'
        ];

        $view = new JsonModel($vehicleNumberList);
        return $view;
    }

    /**
     *
     * Vehicle Type List...
     * @return ViewModel
     */
    public function getVehicleTypeList($data = null) {
        $vehicleTypeJsonDataArray = [];
        $url = $this->apiUrl() . "/vehicle-type";
        $resp = $this->get($url);
        $vehicleTypeJsonData = Json::decode($resp->getBody(), true);
        foreach ($vehicleTypeJsonData['data'] as $res) {
            $vehicleTypeJsonDataArray[$res['id']] = $res['vehicle_type'];
        }
        return $vehicleTypeJsonDataArray;
    }

    /**
     *
     * Vehicle List...
     * @return ViewModel
     */
    public function getAllVehicleList($data) {
        $url = $this->apiUrl() . "/vehicle-master/getallvehicle";
        $resp = $this->post($url, $data);
        $vehiclelistJsonData = Json::decode($resp->getBody(), true);
        $vehicleList = [];
        if($vehiclelistJsonData['responsedata']['status']=='success'){
            return $vehicleList = $vehiclelistJsonData['responsedata']['data'];
        }else{
            return $vehicleList;
        }
        
    }

    /**
     *
     * Vehicle Mapping List...
     * @return ViewModel
     */
    public function getAllMappingVehicleList($data) {
        $url = $this->apiUrl() . "/vehicle-master/listDriverVehicleMap";
        $resp = $this->post($url, $data);
        $vehiclelistJsonData = Json::decode($resp->getBody(), true);
        $vehicleList = $vehiclelistJsonData['responsedata'];
        return $vehicleList;
    }

    /** Function to change VEHICLE STATUS */
    public function vehicleStatusAction() {
        $finaldata = [];
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $finaldata['user_id'] = ($userTypeId != 10) ? $user_id : 0;
        $data = $this->getRequest()->getPost();
        $id = implode(',', $data['selected']);
        $vehicle_status = $data['status'];
        $data = ['user_id' => $user_id, 'id' => $id, 'vehicle_status' => $vehicle_status];
        $this->updateVehicleStatus($data);
        $vehicleListing = $this->getAllVehicleList($finaldata);
        $viewModel = new ViewModel(['vehicleListing' => $vehicleListing]);
        $viewModel->setTemplate('dashboard/vehicle-details/vehicle-listing.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /** Function to Update VEHICLE STATUS */
    public function updateVehicleStatus($data) {
        $url = $this->apiUrl() . "/vehicle-master/vehicleStatus";
        $resp = $this->put($url, $data);
        $data = Json::decode($resp->getBody(), true);
        return $data;
    }

    /** Function to GET VEHICLE IGNITION TYPES */
    public function getFuelTypeList() {
        $fuelTypeJsonDataArray = [];
        $url = $this->apiUrl() . "/fuel-type";
        $resp = $this->get($url);
        $fuelTypeJsonData = Json::decode($resp->getBody(), true);
        if($fuelTypeJsonData['status']=="success"){
        foreach ($fuelTypeJsonData['data'] as $res) {
            $fuelTypeJsonDataArray[$res['id']] = $res['fuel_type'];
        }
        }
        return $fuelTypeJsonDataArray;
    }

    /** Function to Get VEHICLE AMENITIES */
    public function getVehicleAmenitiesList() {
        $amenitiesJsonDataArray = [];
        $url = $this->apiUrl() . "/vehicle-amenities";
        $resp = $this->get($url);
        $amenitiesJsonData = Json::decode($resp->getBody(), true);
        foreach ($amenitiesJsonData as $res) {
            $amenitiesJsonDataArray[$res['id']] = $res['amenities_name'];
        }
        return $amenitiesJsonDataArray;
    }

    /** Function to Get VEHICLE MODEL YEARS */
    public function getModelYearList() {
        $yearJsonDataArray = [];
        $date = date('Y');
        for ($i = $date; $i >= $date - 20; $i--) {
            $yearJsonDataArray[$i] = $i;
        }
        return $yearJsonDataArray;
    }

    /**
     * Vehicle Model List...
     * @return ViewModel
     */
    public function getVehicleModelListAction() {
        $request = $this->getRequest();
        $postdata = $request->getPost();
        $term = $postdata['term'];
        $vehicle_type = $postdata['vehicle_type'];
        $val = '{"where":{"AND": [{"vehicle_type_id": "' . $vehicle_type . '"},{"name": {"like": "' . $term . '%"}}]}}';
        $val = rawurlencode($val);
        //$url = $this->apiUrl() . "/vehicle-model?&filter=" . $val;
        $url = $this->apiUrl() . "/vehicle-model/GetvehicleName?&vehicle_type_id=" . $vehicle_type.'&vehicle_name=' .$term;
        $resp = $this->get($url);
        $cityJsonData = Json::decode($resp->getBody(), true);
        if (!empty($cityJsonData['responsedata']['data'])) {
            foreach ($cityJsonData['responsedata']['data'] as $value) {
                $data[] = ["label" => $value['name'], "value" => $value['id']];
            }
        } else {
            $data[] = ["label" => 'Not Exist'];
        }
        $view = new JsonModel($data);
        return $view;
    }

    /**
     * INSERT VEHICLE DETAILS
     * @return JSON
     */
    public function insertVehicleDetails($finalData) {
        $url = $this->apiUrl() . "/vehicle-master/adminAddVehicle";
        $val = $this->post($url, $finalData);
        $JsonData = $val->getBody();
        $JsonData = Json::decode($JsonData, true);
        return $JsonData;
    }

    /**
     * UPDATE VEHICLE DETAILS
     * @return JSON
     */
    public function updateVehicleDetails($finalData) {
        $url = $this->apiUrl() . "/vehicle-master/updateVehicleDetail";
        $val = $this->post($url, $finalData);
        $JsonData = $val->getBody();
        $JsonData = Json::decode($JsonData, true);
        return $JsonData;
    }

    /**
     * Get Vehicle Model Amenities List
     * @return JSON
     */
    public function getVehicleModelAmenitiesList($id) {
        $amenitiesJsonDataArray = [];
        $val = '{"where": {"vehicle_master_id": "' . $id . '"}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/vehicles-amenities?&filter=" . $val;
        $resp = $this->get($url);
        $data = Json::decode($resp->getBody(), true);
        foreach ($data as $res) {
            $amenitiesJsonDataArray[$res['id']] = $res['amenities_id'];
        }
        return $amenitiesJsonDataArray;
    }

    public function deleteVehicleMapAction() {
        $vehicle_status=[];
        $sessionContainer = new Container('userlogin');
        $user_id = $sessionContainer->user_id;
        $id = $this->params()->fromRoute('id');
        if($id !=''){
        $data = ['user_id' => $user_id, 'id' => $id, 'vehicle_status' => 2];
       // $vehicle_status=$this->updateVehicleStatus($data);
        if ($vehicle_status['response']['status']=='success') {
                    $msg = "Data Deleted Successfully..";
                    $this->redirect()->toRoute('vehicle-details', ['action' => 'vehicle-mapping']);
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                }
                else{
                    $msg = "Could Not Deleted..";
                    $this->redirect()->toRoute('vehicle-details', ['action' => 'vehicle-mapping']);
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                }
        }

        return $this->redirect()->toRoute('vehicle-details', ['action' => 'index']);
    }

    public function getVehicleNumbersAction() {
        $JsonDataArray=[];
        $request = $this->getRequest();
        $getdata = $this->getRequest()->getPost();
             $val['vehicle_model_id'] = $getdata['vehicle_model_id'];
             $getres = $this->getAllMappingVehicleList($val);

         if (!empty($getres)) {
            foreach ($getres as $value) {
                $data[] = ["id" => $value['vehicle_master_id'], "name" => $value['vehicle_no']];
            }
            $response = ["status" => true, "data" => $data];
        } else {
            $response = ["status" => false];
        }
        $view = new JsonModel($response);
        return $view;

    }

}
