<?php

namespace Dashboard\Controller;

use Application\Controller\RestAPIClientController;
use Dashboard\Form\{
    FaremanagementFareSearchForm,
    FareAddSearchForm,
    FareAddBasicForm,
    FaremanagementAddpriceCommonForm,
    FareAddpriceDistanceForm,
    FareAddPriceDistanceHourForm,
    FareAddPriceFixedRoutesForm,
    FareAddPriceHourForm,
    FaremanagementAddPricePackageCalculation,
    FareAddPricePremiumForm,
    FaremanagementAddPriceShareForm,
    FareAddPriceDistanceWaitingForm,
    FareAddCancellationFeesForm,
    FareAddShareForm,
    LocalPackageFareForm
};
use Zend\View\Model\{
    ViewModel,
    JsonModel
};
use Zend\Json\Json;
use Zend\Debug\Debug;
use Zend\Session\Container;
use Dashboard\Model\CommonModel;

class CabFareController extends RestAPIClientController {

    public function __construct() {
        $this->CommonModel = new CommonModel();
    }

    private $publicFare = 1;
    private $clientFare = 2;
    private $pointDispatch = 1;
    private $garageDispatch = 2;
    private $ownGarage = 1;
    private $compGarage = 2;
    private $netRate = 1;
    private $commissionRate = 2;
    private $distanceHourFare = 'distance-hour-fare';
    private $distanceFare = 'distance_fares';
    private $hourlyFare = 'hourly-fare';
    private $distanceWaitingFare = 'distance-waiting-fare';
    private $basicTax = 'tax';
    private $fareSetting    = 'basic-fare-settings';
    private $localPkgFare   = 'local-package-fare';
    private $fareShare      = 'company-share';
    private $cancellationFare   = 'cancellation-fare';
    private $waitingCharge   = 'waiting-charge';
    private $preWaitingCharge   = 'pre-waiting-charge';
    private $nightCharge   = 'night-charge';
    private $premiumsCharge   = 'premiums-fare';
    private $fixRoute   = 'fix-route';
    private $postalFare   = 'postalcode-fare';
    private $peakTimeCharge   = 'peak_time_charges';
    private $extras   = 'extras';
    private $distanceUptoFare    = 'distance-upto-rate';

    private $bookingModeType = array(1=>'distance_fares',2=>'hourly-fare',3=>'distance-hour-fare',4=>'distance-waiting-fare');
    /**
     * index
     * @return ViewModel
     */
    public function indexAction() {
        $addFareSession = new Container('addfaresession');
        $addFareSession->getManager()->getStorage()->clear('addfaresession');
        $sessionContainer = new Container('userlogin');
        $userData = $sessionContainer->userData;
        $userTypeId =  $userData['user_type_id'];
        $user_id = $sessionContainer->user_id;
        //$user_id = 6;

        FareAddSearchForm::$state = $this->getStateWiseListAction();
        FareAddSearchForm::$booking_type = $this->CommonModel->getPackageTypeList();
        FareAddSearchForm::$vehicle_type = $this->getVehicleTypeList();
        $clientList = $this->getVendorClientList($user_id);
        FareAddSearchForm::$client = $clientList['data'];
        $form = new FareAddSearchForm();
        $request = $this->getRequest();
        $finaldata = [];
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            //echo '<pre>';print_r($post);die();
            $city_ids   = str_replace(';',',',$post['city_search_id']);
            $form->setData($request->getPost());
            if ($post['fare_type'] == $this->publicFare) {
                $form->get('public_fare_selected')->setValue(1);
                $form->get('client_fare_selected')->setValue(0);
            }

            if ($post['fare_type'] == $this->clientFare) {
                $form->get('public_fare_selected')->setValue(0);
                $form->get('client_fare_selected')->setValue(1);
            }

            $data = [
                'client_id' => $post['client'],
                'city_id' => rtrim($city_ids,","),
                'master_package_id' => $post['booking_type'],
                'vehicle_type_id' => $post['vehicle_type'],
                'user_id'=>$user_id,
                'user_type_id'=>$userTypeId
            ];
            $finaldata = array_filter($data);
            $finaldata['status'] = $post['status'];
            //echo '<pre>';print_r($finaldata);die();
        }

        $finaldata['user_type_id'] = $userTypeId;
        $finaldata['company_id'] = $this->config()->getConfig()->company->companyId;
        //print_r($finaldata);exit;
        $fareList = $this->getFareListData($finaldata);
        $cabfareListing = $fareList['data']['responsedata'];
        if(!empty($cabfareListing)){
            $cabfareArr = [];
            foreach($cabfareListing as $key=>$val){
                $packageModeId = $val['master_package_mode_id'];
                $baseVehicleId = $val['base_vehicle_id'];
                $tableMode = $this->bookingModeType[$packageModeId];
                $fareData = $this->getFareData($baseVehicleId,$tableMode);
                $cabfareArr[$key] = $val;
                $cabfareArr[$key]['fare_data'] = isset($fareData[0])?$fareData[0]:'';
            }
        }

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

    /**
     * index
     * @return ViewModel
     */
    public function addFareAction() {

        $masterLocalPkg[]='';
        $fareDetails[]='';
        $cabfareData="";
        $viewModel = new ViewModel();
        $sessionContainer = new Container('userlogin');

        $userData = $sessionContainer->userData;
        $userTypeId = $userData['user_type_id'];
        $user_id = $sessionContainer->user_id;


        FareAddSearchForm::$country = $this->getCountryList();
        FareAddSearchForm::$booking_type = $this->CommonModel->getPackageTypeList();
        FareAddSearchForm::$booking_mode_type = $this->CommonModel->getPackageModeList();
        FareAddSearchForm::$vehicle_type = $this->getVehicleTypeList();
        //FareAddSearchForm::$state = $this->getStateWiseListAction();
        FareAddSearchForm::$currency = $this->getCurrencyList();
        FareAddPricePremiumForm::$masterextra = $this->getMasterExtraData();
        $clientList = $this->getVendorClientList($user_id);
        FareAddSearchForm::$client = $clientList['data'];
        $form = new FareAddSearchForm();
        $distanceform = new FareAddpriceDistanceForm();
        $hourform = new FareAddPriceHourForm();
        $distancehourform = new FareAddPriceDistanceHourForm();
        $distancewatingform = new FareAddPriceDistanceWaitingForm();
        $basicfareform = new FareAddBasicForm();
        $cancellationform = new FareAddCancellationFeesForm();
        $premiumform = new FareAddPricePremiumForm();
        $fixedrouteform = new FareAddPriceFixedRoutesForm();
        $shareform = new FareAddShareForm();
        $week_days = $this->getWeekDaysList();



        $addFareSession = new Container('addfaresession');


        $base_combination_id = $this->params('id');
        if($base_combination_id!=''){
            $addFareSession->getManager()->getStorage()->clear('addfaresession');

            //$fareData    = $this->getFareListData(['base_combination_id'=>$base_combination_id,'user_type_id'=>$userTypeId]);
            $fareData    = $this->getFareListData(['base_combination_id'=>$base_combination_id]);

            $cabfareData = $fareData['data']['responsedata'][0];
            //echo '<pre>';print_r($cabfareData);die();
            $fareId = $addFareSession->fareId = $cabfareData['base_combination_id'];
            $base_vehicle_id =  $addFareSession->baseVehicleId = $cabfareData['base_vehicle_id'];
            $bookingMode =  $addFareSession->bookingMode = $cabfareData['master_package_mode_id'];
            $bookingtype = $addFareSession->bookingtype = $cabfareData['master_package_id'];
        }else{
            $fareId = $addFareSession->fareId;
            $bookingMode = $addFareSession->bookingMode;
            $bookingtype = $addFareSession->bookingtype;
            $base_vehicle_id = $addFareSession->baseVehicleId;
            //$cabfareData="";
            $fareData    = $this->getFareListData(['base_combination_id'=>$fareId]);
            $cabfareData = $fareData['data']['responsedata'][0];
        }

         /** Get Fare details for Edit */

        if($fareId!=''){
            /*if($userTypeId==4){
                $tableMode=$this->bookingVndModeType[$bookingMode];
            }else{
                $tableMode=$this->bookingModeType[$bookingMode];
            }*/
            $tableMode=$this->bookingModeType[$bookingMode];
            $getFareData = ['base_vehicle_id'=>$base_vehicle_id, 'booking_mode'=>$tableMode,'user_type_id'=>$userTypeId];

            $fareDetails = $this->getFareDetailByBaseVehicleId($getFareData);
            //echo '<pre>';print_r($fareDetails);die();

            $url = $this->apiUrl() . "/city/stateCountryByCityName?cityid=" . $cabfareData['city_id'];
            $resp = $this->get($url);
            $cityJsonData = Json::decode($resp->getBody(), true);
            $cityData = $cityJsonData['response']['data'][0];
            //echo '<pre>';print_r();die();
            $form->get('fare_city')->setValue($cityData['citystatecountry']);
            $form->get('fare_state')->setValue($cityData['state_id']);
            $form->get('fare_city_id')->setValue($cityData['city_id']);
            if(!empty($cabfareData)){
            $fareDetails['cabfare_detail'] = $cabfareData;
            }
        }else{
            $fareDetails['cabfare_detail']="";
            $fareDetails['tax_fare']="";
            $fareDetails['fare_setting']="";
        }
        /* END */

        /** GET MASTER LOCAL PACKAGE MODE */
            if($fareId!=''){
               $masterLocalPkg  = $this->getMasterLocalPkg($bookingMode,$bookingtype);

            }
        /* END */


        $request = $this->getRequest();
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $form->setData($request->getPost());

            if ($post['fare_type'] == $this->publicFare) {
                $form->getInputFilter()->get('client')->setRequired(false);
                $form->get('public_fare_selected')->setValue(1);
                $form->get('client_fare_selected')->setValue(0);
            }

            if ($post['fare_type'] == $this->clientFare) {
                $form->getInputFilter()->get('client')->setRequired(true);
                $form->get('public_fare_selected')->setValue(0);
                $form->get('client_fare_selected')->setValue(1);
            }


            if ($post['dispatch_type'] == $this->pointDispatch) {
                $form->get('point_dispatch_selected')->setValue(1);
                $form->get('garage_dispatch_selected')->setValue(0);
            }

            if ($post['dispatch_type'] == $this->garageDispatch) {
                $form->get('point_dispatch_selected')->setValue(0);
                $form->get('garage_dispatch_selected')->setValue(1);
            }

            if(isset($post['dispatch_garage'])!=""){

            if ($post['dispatch_garage'] == $this->ownGarage) {
                $form->getInputFilter()->get('garage_own_address')->setRequired(true);
                $form->getInputFilter()->get('garage_own_state')->setRequired(true);
                $form->getInputFilter()->get('garage_own_city')->setRequired(true);
                $form->getInputFilter()->get('garage_own_pincode')->setRequired(true);
                $form->getInputFilter()->get('garage_comp_address')->setRequired(false);
                $form->getInputFilter()->get('garage_comp_state')->setRequired(false);
                $form->getInputFilter()->get('garage_comp_city')->setRequired(false);
                $form->getInputFilter()->get('garage_comp_pincode')->setRequired(false);
                $form->get('own_garage_selected')->setValue(1);
                $form->get('comp_garage_selected')->setValue(0);
            }

            if ($post['dispatch_garage'] == $this->compGarage) {
                $form->getInputFilter()->get('garage_comp_address')->setRequired(true);
                $form->getInputFilter()->get('garage_comp_state')->setRequired(true);
                $form->getInputFilter()->get('garage_comp_city')->setRequired(true);
                $form->getInputFilter()->get('garage_comp_pincode')->setRequired(true);
                $form->getInputFilter()->get('garage_own_address')->setRequired(false);
                $form->getInputFilter()->get('garage_own_state')->setRequired(false);
                $form->getInputFilter()->get('garage_own_city')->setRequired(false);
                $form->getInputFilter()->get('garage_own_pincode')->setRequired(false);
                $form->get('own_garage_selected')->setValue(0);
                $form->get('comp_garage_selected')->setValue(1);
            }
            }

            if ($post['commission_type'] == $this->netRate) {
                $form->getInputFilter()->get('commission_value')->setRequired(false);
                $form->get('net_rate_selected')->setValue(1);
                $form->get('garage_dispatch_selected')->setValue(0);
            }

            if ($post['commission_type'] == $this->commissionRate) {
                $form->getInputFilter()->get('commission_value')->setRequired(true);
                $form->get('net_rate_selected')->setValue(0);
                $form->get('commission_rate_selected')->setValue(1);
            }


            if ($form->isValid()) {
                //echo "Mohit"; die;

                if ($post['fare_type'] == $this->clientFare) {
                    $client_id = $post['client'];
                } else {
                    $client_id = "";
                }
                if ($post['dispatch_type'] == $this->garageDispatch) {
                    $dispatch_garage = $post['dispatch_garage'];
                } else {
                    $dispatch_garage = "";
                }


                if ($post['dispatch_type'] == $this->garageDispatch) {
                    $dispatch_garage = $post['dispatch_garage'];
                    if ($dispatch_garage == $this->compGarage) {
                        $address = $post['garage_comp_address'];
                        $state = $post['garage_comp_state'];
                        $city = $post['garage_comp_city'];
                        $pincode = $post['garage_comp_pincode'];
                    } else {
                        $address = $post['garage_own_address'];
                        $state = $post['garage_own_state'];
                        $city = $post['garage_own_city'];
                        $pincode = $post['garage_own_pincode'];
                    }
                } else {
                    $dispatch_garage = "";
                }

                if ($post['commission_type'] == $this->commissionRate) {
                    $rate_type = $post['comm_type'];
                    $rate_value = $post['commission_value'];
                } else {
                    $rate_type = "";
                    $rate_value = "";
                }

            //Debug::dump($post); //exit;
            $created_date = date('Y-m-d H:i:s');
            $ip = $_SERVER['REMOTE_ADDR'];
            $data = [];
            $data = [
                'company_id' => $this->config()->getConfig()->company->companyId,
                'vendor_id' => $user_id,
                'client_id' => $client_id,
                'country_id' => $post['fare_country'],
                'state_id' => $post['fare_state'],
                'city_id' => $post['fare_city_id'],
                'master_package_id' => $post['booking_type'],
                'master_package_mode_id' => $post['booking_mode_type'],
                'market_place'=>$post['market_place'],
                'created_date' => $created_date,
                'created_by' => $user_id,
                'ip' => $ip,
                'vehicle_type_id' => $post['vehicle_type'],
                'type_of_dispatch' => $post['dispatch_type'],
                'garage_type' => $dispatch_garage,
                'address' => isset($address)?$address:'',
                'state' => isset($state)?$state:'',
                'city' => isset($city)?$city:'',
                'pincode' => isset($pincode)?$pincode:'',
                'fare_date_from' => date('Y-m-d',strtotime($post['fare_date_from'])),
                'fare_date_to' => date('Y-m-d',strtotime($post['fare_date_to'])),
                'currency' => $post['currency'],
                'rate' => $post['commission_type'],
                'rate_type' => $rate_type,
                'rate_value' => $rate_value,
                'week_days' => implode(",", $post['weekend']),
                //'user_type_id'=>$userTypeId
            ];
            $finaldata = array_filter($data);
            //Debug::dump($finaldata); exit;
            $status = $this->insertCabFare($finaldata);
            //echo '<pre>';print_r($status);die();
            if ($status['responsedata'] == true) {
                //$this->redirect()->toRoute('cabfare', ['action' => 'index']);
                $addFareSession->getManager()->getStorage()->clear('addfaresession');

                $addFareSession->fareId = $status['responsedata']['fare_id'];
                $addFareSession->baseVehicleId = $status['responsedata']['base_vehicle_id'];
                $addFareSession->bookingMode = $post['booking_mode_type'];
                $addFareSession->bookingtype = $post['booking_type'];
                $result = ['result' => true,'fare_id'=>$status['responsedata']['fare_id'],'booking_mode'=>$post['booking_mode_type'],'displayTabActived'=>true,'currentUrlRedirect' => 'Y'];
            }

             }else{
                $result = ['result' => false, 'message' => $form->getMessages()];
            }

            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
             $viewModel->setVariables(['data' => $result]);
            return $viewModel;

        }
        else{

              //echo'<pre>';print_r($form->getMessages());die();
        }


        $viewModel->setVariables(['form' => $form, 'week_days' => $week_days, 'distanceform' => $distanceform, 'hourform' => $hourform, 'distancehourform' => $distancehourform, 'distancewatingform' => $distancewatingform, 'basicfareform' => $basicfareform, 'cancellationform' => $cancellationform, 'premiumform' => $premiumform, 'fixedrouteform' => $fixedrouteform, 'shareform' => $shareform, 'fareDetails' => $fareDetails, 'fareId' => $fareId, 'bookingMode' => $bookingMode, 'masterLocalPkg' => $masterLocalPkg]);
        return $viewModel;
    }

    /**
     * Add basic Tax
     * @return ViewModel
     */
    public function addPriceBasicFareAction() {
        $viewModel="";
        $sessionContainer = new Container('userlogin');
        $userData = $sessionContainer->userData;
        $userTypeId = $userData['user_type_id'];
        $user_id = $sessionContainer->user_id;
        //$user_id = 6;

        $addFareSession = new Container('addfaresession');
        $base_vehicle_id = $addFareSession->baseVehicleId;

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


        if ($request->isXmlHttpRequest()) {
            $postdata = $request->getPost()->toArray();
            $form->setData($postdata);
            $taxFareId = $postdata['tax_fare_id'];
            $taxFareSettingId = $postdata['tax_fare_setting_id'];
            $msg = "Basic Details Insert Successfully";
            if ($taxFareId > 0) {
                $msg = "Basic Details Updated Successfully";
            }
            if ($form->isValid()) {

                /* Tax Starts Here */
                $addBasicFare = [
                    'base_vehicle_id' => $base_vehicle_id,
                    'tax_type' => '%',
                    'sgst' => $postdata['sgst'],
                    'cgst' => $postdata['cgst'],
                    'igst' => $postdata['igst'],
                    'ip' => $_SERVER['REMOTE_ADDR'],
                    'status' => 1
                ];

                if ($taxFareId > 0) {
                    $addBasicFare['modified_by'] = $user_id;
                } else {
                    $addBasicFare['created_by'] = $user_id;
                    $addBasicFare['created_date'] = date('Y-m-d h:i:s');
                }

                $tableModelTax=$this->basicTax;
                $jsonresponseTaxData = $this->addUpdateFareData($taxFareId, $tableModelTax, $addBasicFare);

                /* Tax Ends Here */

                $basicfareSettings = [
                    'base_vehicle_id' => $base_vehicle_id,
                    'rounding' => $postdata['rounding'],
                    'level' => $postdata['level'],
                    'direction' => $postdata['direction'],
                    'ip' => $_SERVER['REMOTE_ADDR'],
                    'status' => 1
                ];

                if ($taxFareSettingId > 0) {
                    $basicfareSettings['modified_by'] = $user_id;
                } else {
                    $basicfareSettings['created_by'] = $user_id;
                    $basicfareSettings['created_date'] = date('Y-m-d h:i:s');
                }
                $tableModelFareSetting=$this->fareSetting;
                $jsonresponseSettingData = $this->addUpdateFareData($taxFareSettingId, $tableModelFareSetting, $basicfareSettings);
                $result = ['result' => true, 'message' => $msg];
            } else {
                $result = ['result' => false, 'message' => $form->getMessages()];
            }

            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }

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

    /**
     * index
     * @return ViewModel
     */
    public function addPriceCommonAction() {

        $viewModel = new ViewModel();
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /**
     * index
     * @return ViewModel
     */
    public function addPriceDistanceHourAction() {
        $viewModel = new ViewModel();
        $sessionContainer = new Container('userlogin');
        $userData = $sessionContainer->userData;
        $userTypeId = $userData['user_type_id'];
        $user_id = $sessionContainer->user_id;

        $addFareSession = new Container('addfaresession');
        $base_vehicle_id = $addFareSession->baseVehicleId;

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


        if ($request->isXmlHttpRequest()) {
            $postdata = $request->getPost()->toArray();
            $distanceHourId = $postdata['distancehourid'];
            $dist_hr_amount = isset($postdata['distance_hour_amount'])?$postdata['distance_hour_amount']:'';
            if($dist_hr_amount!=""){

            $localpkgId = $postdata['localpkgid'];
            if (isset($dist_hr_amount) && count($dist_hr_amount) > 0) {
                $addLocalPkgFare = array_combine($localpkgId, $dist_hr_amount);
                $this->addUpdateLocalpkgFare($base_vehicle_id, $addLocalPkgFare,$user_id,$userTypeId);
            }
            }

            $addDistanceHourFare = [
                'base_vehicle_id' => $base_vehicle_id,
                'minimum_charge' => $postdata['minimum_fare'],
                'minimum_hrs' => $postdata['ignore_first_hours'],
                'minimum_distance' => $postdata['ignore_first_km_after'],
                'per_km_charge' => $postdata['rate_per_km'],
                'per_hr_charge' => $postdata['rate_per_hour'],
                'created_date' => date('Y-m-d h:i:s'),
                'created_by' => $user_id,
                'ip' => $_SERVER['REMOTE_ADDR']
            ];
            $tableModel=$this->distanceHourFare;
            $jsonresponseData = $this->addUpdateFareData($distanceHourId, $tableModel, $addDistanceHourFare);
            //return $jsonModel = new JsonModel($jsonresponseData);

            $msg = ($distanceHourId > 0) ? "Data updated successfully..." : "Data added successfully";
            $result = ['result' => true, 'message' => $msg];

            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;

        }



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

    /**
     * @Desc Distance Waiting Fare
     */
    public function addPriceDistanceWaitingAction() {
        $viewModel = new ViewModel();
        $sessionContainer = new Container('userlogin');
        $userData = $sessionContainer->userData;
        $userTypeId = $userData['user_type_id'];
        $user_id = $sessionContainer->user_id;

        $addFareSession = new Container('addfaresession');
        $base_vehicle_id = $addFareSession->baseVehicleId;

        $request = $this->getRequest();

        $form = new FareAddPriceDistanceWaitingForm();


        if ($request->isXmlHttpRequest()) {
            $postdata = $request->getPost()->toArray();
            $distance_waiting_autoid = $postdata['distance_waiting_fare_id'];

            $dist_wait_amount = $postdata['distance_waiting_amount'];
            $localpkgId = $postdata['localpkgid'];

            if (isset($dist_wait_amount) && count($dist_wait_amount) > 0) {
                $addLocalPkgFare = array_combine($localpkgId, $dist_wait_amount);
                $this->addUpdateLocalpkgFare($base_vehicle_id, $addLocalPkgFare, $user_id, $userTypeId);
            }

            //$minutes_upto = $postdata['minutes_upto'];
            //$fees = $postdata['fee'];
            //$after_fees_per_minutes = $postdata['after_that_fees_per_minutes'];

            //$waiting_fees = $minutes_upto . '_' . $fees . '_' . $after_fees_per_minutes;

            $addDistanceWatingFare = [
                'base_vehicle_id' => $base_vehicle_id,
                'minimum_charge' => $postdata['minimum_fare'],
                'minimum_distance' => $postdata['ignore_first_km_after'],
                'per_km_charge' => $postdata['rate_per_km'],
                'minutes_upto' => $postdata['minutes_upto'],
                'fees' => $postdata['fee'],
                'fees_per_minute' => $postdata['after_that_fees_per_minutes'],
                'created_date' => date('Y-m-d h:i:s'),
                'created_by' => $user_id,
                'status' => 1,
                'ip' => $_SERVER['REMOTE_ADDR']
            ];
            $tableModel=$this->distanceWaitingFare;
            $this->addUpdateFareData($distance_waiting_autoid, $tableModel, $addDistanceWatingFare);
            $msg = ($distance_waiting_autoid > 0) ? "Data updated successfully..." : "Data added successfully";
            $result = ['result' => true, 'message' => $msg];

            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }



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

    /**
     *
     * @return ViewModel
     * @CreatedBy   : Mohit Verma
     * @createdDate : 22-Nov-2018
     * @Description : Add Distance Fare
     */
    public function addPriceDistanceAction() {
        $viewModel = new ViewModel();
        $sessionContainer = new Container('userlogin');
        $user_id = $sessionContainer->user_id;
        $userData = $sessionContainer->userData;
        $userTypeId = $userData['user_type_id'];

        $addFareSession = new Container('addfaresession');
        $base_vehicle_id = $addFareSession->baseVehicleId;

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


        if (($request->isXmlHttpRequest())) {
            $postdata = $request->getPost()->toArray();
            $distance_fare_autoid = $postdata['distance_fare_id'];
            $distance_km_upto = array_filter($postdata['package_km_upto_to']);
            $distance_rate_perkm = array_filter($postdata['package_rate_per_km']);

            /*if (!empty($distance_km_upto) && !empty($distance_rate_perkm)) {
                $combinedKmAndrate = array_map(function($a, $b) {
                    return $a . '_' . $b;
                }, $distance_km_upto, $distance_rate_perkm);
                $ratekmupto = json_encode($combinedKmAndrate);
            }*/

            if (!empty($distance_km_upto) && !empty($distance_rate_perkm)) {
                $addDisUptoFare = array_combine($distance_km_upto, $distance_rate_perkm);
                $this->addUpdateDistUptoFare($base_vehicle_id, $addDisUptoFare, $user_id, $userTypeId);
            }

            $dist_amount = isset($postdata['distance_amount'])?$postdata['distance_amount']:'';
            $localpkgId = isset($postdata['localpkgid'])?$postdata['localpkgid']:'';

            if (!empty($dist_amount) && count($dist_amount) > 0) {
                $addLocalPkgFare = array_combine($localpkgId, $dist_amount);
                $this->addUpdateLocalpkgFare($base_vehicle_id, $addLocalPkgFare, $user_id, $userTypeId);
            }

            $round_per_kms = ($postdata['round_per_kms'] > 0) ? 'on' : 'off';
            $accumulated_instances = ($postdata['accumulated_instances'] > 0) ? 'on' : 'off';

            $addDistanceFare = [
                'base_vehicle_id' => $base_vehicle_id,
                'per_km_charge' => $postdata['rate_per_km'],
                'minimum_distance' => $postdata['ignore_first_km_rate'],
                'minimum_charge' => $postdata['minimum_fare'],
                'round_up_km' => $round_per_kms,
                'accumulated_instance' => $accumulated_instances,
                //'rate_upto_distance' => $ratekmupto,
                'created_date' => date('Y-m-d h:i:s'),
                'created_by' => $user_id,
                'ip' => $_SERVER['REMOTE_ADDR']
            ];
            $tableModel=$this->distanceFare;
            $jsonresponseData = $this->addUpdateFareData($distance_fare_autoid, $tableModel, $addDistanceFare);
            $msg = ($distance_fare_autoid > 0) ? "Data updated successfully..." : "Data added successfully";
            $result = ['result' => true, 'message' => $msg];

            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }

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

    /**
     * index
     * @return ViewModel
     */
    public function addPriceFixedRoutesAction() {
        $viewModel = new ViewModel();
        $sessionContainer = new Container('userlogin');
        $userData = $sessionContainer->userData;
        $userTypeId = $userData['user_type_id'];
        $user_id = $sessionContainer->user_id;

        $addFareSession = new Container('addfaresession');
        $base_vehicle_id = $addFareSession->baseVehicleId;

        $request = $this->getRequest();
        $form = new FareAddPriceFixedRoutesForm();
        $tablefixRoute=$this->fixRoute;
        $tablePostalFare=$this->postalFare;

        if (($request->isXmlHttpRequest())) {
            $postdata = $request->getPost()->toArray();
            $fix_route_autoid = $postdata['fix_route_id'];



            /*if (!empty($pickup_postcode) && !empty($drop_off_postcode) && (!empty($value))) {
                $combinedpackagefare = array_map(function($a, $b, $c) {
                    return $a . '_' . $b . '_' . $c;
                }, $pickup_postcode, $drop_off_postcode, $value);
                $post_fair = json_encode($combinedpackagefare);
            }*/

            $addFixedRoute = [
                'base_vehicle_id' => $base_vehicle_id,
                'frequent_location' => $postdata['frequent_location'],
                'ip' => $_SERVER['REMOTE_ADDR'],
                'status' => 1
            ];

            if ($fix_route_autoid > 0) {
                $addFixedRoute['modified_by'] = $user_id;
            } else {
                $addFixedRoute['created_by'] = $user_id;
                $addFixedRoute['created_date'] = date('Y-m-d h:i:s');
            }

            $this->addUpdateFareData($fix_route_autoid, $tablefixRoute, $addFixedRoute);

                    $pickup_postcode = array_filter($postdata['pickup_postcode']);
                    $drop_off_postcode = array_filter($postdata['drop_off_postcode']);
                    $value = array_filter($postdata['value']);
             // Add peak time charge //
                    if (!empty($pickup_postcode) && !empty($drop_off_postcode)) {
                     // Delete local package fare details //
                        $url = $this->apiUrl() . "/".$tablePostalFare."/".$base_vehicle_id;
                        $resp2 = $this->delete($url);
                    //END //



                        if(count($pickup_postcode)>0){
                          for($i=0; $i<count($pickup_postcode); $i++){
                               $postalFareArr = [
                                   'base_vehicle_id' => $base_vehicle_id,
                                   'pickup_postcode' => $pickup_postcode[$i],
                                   'drop_postcode' => $drop_off_postcode[$i],
                                   'price' => $value[$i],
                                   'created_date' => date('Y-m-d h:i:s'),
                                   'created_by'   => $user_id,
                                   'status'       =>1,
                                   'ip' => $_SERVER['REMOTE_ADDR'],
                                   ];
                           $url = $this->apiUrl() . "/".$tablePostalFare;
                           $resp = $this->post($url, $postalFareArr);
                        }
                       }
                    }

                // END  //

            $msg = ($fix_route_autoid > 0) ? "Data updated successfully..." : "Data added successfully";
            $result = ['result' => true, 'message' => $msg];

            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }

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

    /**
     * index
     * @return ViewModel
     */
    public function addPriceHourAction() {
        $viewModel = new ViewModel();
        $sessionContainer = new Container('userlogin');
        $userData = $sessionContainer->userData;
        $userTypeId = $userData['user_type_id'];
        $user_id = $sessionContainer->user_id;

        $addFareSession = new Container('addfaresession');
        $base_vehicle_id = $addFareSession->baseVehicleId;

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



        if ($request->isXmlHttpRequest()) {
            $postdata = $request->getPost()->toArray();
            $hour_fare_autoid = $postdata['hour_fare_id'];

            $hour_amount = isset($postdata['hour_amount'])?$postdata['hour_amount']:'';

            if (!empty($hour_amount) && count($hour_amount) > 0) {
                $hour_amount = array_filter($postdata['hour_amount']);
                $localpkgId = $postdata['localpkgid'];
                $addLocalPkgFare = array_combine($localpkgId, $hour_amount);
                $this->addUpdateLocalpkgFare($base_vehicle_id, $addLocalPkgFare,$user_id,$userTypeId);
            }

            $addHourFare = [
                'base_vehicle_id' => $base_vehicle_id,
                'minimum_charge' => $postdata['minimum_fare'],
                'minimum_hrs' => $postdata['ignore_first_hours'],
                'per_hr_charge' => $postdata['rate_per_hour'],
                'created_date' => date('Y-m-d h:i:s'),
                'created_by' => $user_id,
                'ip' => $_SERVER['REMOTE_ADDR']
            ];
            $tableModel=$this->hourlyFare;
            $this->addUpdateFareData($hour_fare_autoid, $tableModel, $addHourFare);
            $msg = ($hour_fare_autoid > 0) ? "Data updated successfully..." : "Data added successfully";
            $result = ['result' => true, 'message' => $msg];

            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }

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

    /**
     * index
     * @return ViewModel
     */
    public function addPriceOptionsAction() {

        $viewModel = new ViewModel();
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /**
     * index
     * @return ViewModel
     */
    public function addPricePackageCalculationAction() {

        //echo 'niharika';die;
        $request = $this->getRequest();
        $form = new FaremanagementAddPricePackageCalculation();
        $typeSelect = 'select';
        $typeSubmit = 'submit';

//
//
//        //Call API here...
        $packages = [
            'local_hire_distance' => '0',
            'local_hire_hour' => '0',
            'local_hire_distance_hour' => '0',
            'local_hire_distance_waiting' => '0'
        ];
////
////        if(($request->isXmlHttpRequest() && $typeSubmit==$request->getPost()['submit_type'])){
////
////        }else if(($request->isXmlHttpRequest() && $typeSelect==$request->getPost()['type'])){
//
        $form->setData($packages);
////        }
//
        $viewModel = new ViewModel(['form' => $form]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /**
     * index
     * @Desc Add cancellation fees
     */
    public function addFeesFareAction() {
        $viewModel = new ViewModel();
        $sessionContainer = new Container('userlogin');
        $userData = $sessionContainer->userData;
        $userTypeId = $userData['user_type_id'];
        $user_id = $sessionContainer->user_id;

        $addFareSession = new Container('addfaresession');
        $base_vehicle_id = $addFareSession->baseVehicleId;

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


        if ($request->isXmlHttpRequest()) {
            $postdata = $request->getPost()->toArray();

            $cancellation_fees_autoid = $postdata['cancellation_fees_id'];
            $waiting_charge_autoid = $postdata['waiting_charge_id'];
            $pre_waiting_charge_autoid = $postdata['pre_waiting_charge_id'];

            /* Add cancellation fees */
            $addCancellationFare = [
                'base_vehicle_id' => $base_vehicle_id,
                'cancellation_type' => $postdata['cancellation_type'],
                'cancellation_value' => $postdata['cancellation_fees'],
                'ip' => $_SERVER['REMOTE_ADDR']
            ];

            if ($cancellation_fees_autoid > 0) {
                $addCancellationFare['modified_by'] = $user_id;
            } else {
                $addCancellationFare['created_by'] = $user_id;
                $addCancellationFare['created_date'] = date('Y-m-d h:i:s');
            }

            $tableCancelModel=$this->cancellationFare;
            $this->addUpdateFareData($cancellation_fees_autoid, $tableCancelModel, $addCancellationFare);

            /* END */
            /* Add Waiting Fees */
            $waiting_time_min_upto = array_filter($postdata['waiting_time_minutes_upto']);
            $waiting_time_fees = array_filter($postdata['waiting_time_fees']);
            if (!empty($waiting_time_min_upto) && !empty($waiting_time_fees)) {
                $addWaitingTimeFare = array_combine($waiting_time_min_upto, $waiting_time_fees);
                $this->addUpdateWatingTimeFare($base_vehicle_id, $addWaitingTimeFare, $user_id, $userTypeId);
            }

            /*if (!empty($waiting_time_min_upto) && !empty($waiting_time_fees)) {
                $combinedKmAndrate = array_map(function($a, $b) {
                    return $a . '_' . $b;
                }, $waiting_time_min_upto, $waiting_time_fees);
                $waitingFees = json_encode($combinedKmAndrate);
            }


            $addwaitingFare = [
                'base_vehicle_id' => $base_vehicle_id,
                'waiting_fee_upto_minutes' => $waitingFees,
                'ip' => $_SERVER['REMOTE_ADDR']
            ];

            if ($waiting_charge_autoid > 0) {
                $addwaitingFare['modified_by'] = $user_id;
            } else {
                $addwaitingFare['created_by'] = $user_id;
                $addwaitingFare['created_date'] = date('Y-m-d h:i:s');
            }*/

            //$url = $this->apiUrl() . "/waiting-charge";
            //$resp = $this->post($url, $addwaitingFare);

            //$this->addUpdateFareData($waiting_charge_autoid, $this->waitingCharge, $addwaitingFare);
            /* END */

            /* Add pre waiting charge */
            $pre_waiting_time_min_upto = array_filter($postdata['pre_waiting_minutes_upto']);
            $pre_waiting_time_fees = array_filter($postdata['pre_waiting_fee']);

            if (!empty($pre_waiting_time_min_upto) && !empty($pre_waiting_time_fees)) {
                $addprewaitingFare = array_combine($pre_waiting_time_min_upto, $pre_waiting_time_fees);
                $this->addUpdatePreWatingTimeFare($base_vehicle_id, $addprewaitingFare, $user_id, $userTypeId);
            }

            /*if (!empty($pre_waiting_time_min_upto) && !empty($pre_waiting_time_fees)) {
                $waitingchargefees = array_map(function($a, $b) {
                    return $a . '_' . $b;
                }, $pre_waiting_time_min_upto, $pre_waiting_time_fees);
                $prewaitingFees = json_encode($waitingchargefees);
            }

            $addprewaitingFare = [
                'base_vehicle_id' => $base_vehicle_id,
                'pre_waiting_fee_upto_minutes' => $prewaitingFees,
                'ip' => $_SERVER['REMOTE_ADDR']
            ];

            if ($pre_waiting_charge_autoid > 0) {
                $addprewaitingFare['modified_by'] = $user_id;
            } else {
                $addprewaitingFare['created_by'] = $user_id;
                $addprewaitingFare['created_date'] = date('Y-m-d h:i:s');
            }*/

            //$url = $this->apiUrl() . "/pre-waiting-charge";
            //$resp = $this->post($url, $addprewaitingFare);
            //$this->addUpdateFareData($pre_waiting_charge_autoid, $this->preWaitingCharge, $addprewaitingFare);
            /* END  */

            $msg = ($cancellation_fees_autoid > 0) ? "Data updated successfully..." : "Data added successfully";
            $result = ['result' => true, 'message' => $msg];
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }

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

    /**
     * index
     * @return ViewModel
     */
    public function addPricePremiumAction() {
        $viewModel = new ViewModel();
        $sessionContainer = new Container('userlogin');
        $userData = $sessionContainer->userData;
        $userTypeId = $userData['user_type_id'];
        $user_id = $sessionContainer->user_id;

        $addFareSession = new Container('addfaresession');
        $base_vehicle_id = $addFareSession->baseVehicleId;

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

        if ($request->isXmlHttpRequest()) {
            $postdata = $request->getPost()->toArray();
            $form->setData($postdata);
            $nightFareId = $postdata['night_premium_id'];
            $premiumsFareId = $postdata['premiums_id'];
            $msg = "Premium Details Insert Successfully";
            if ($nightFareId > 0) {
                $msg = "Premium Details Updated Successfully";
            }
            if ($form->isValid()) {

                $tablenightCharge=$this->nightCharge;
                $tablepremiumsCharge=$this->premiumsCharge;
                $tablepeaktimeFare=$this->peakTimeCharge;
                $tableextraFare=$this->extras;

                /// Night Fare STARTS HERE ///////////

                $nightFare = [
                    'base_vehicle_id' => $base_vehicle_id,
                    'night_rate_begins' => $postdata['night_rate_begins'],
                    'night_rate_ends' => $postdata['night_rate_ends'],
                    'night_rate_type' => $postdata['night_rate_type'],
                    'night_rate_value' => $postdata['night_rate_value'],
                    'ip' => $_SERVER['REMOTE_ADDR'],
                    'status' => 1
                ];

                if ($nightFareId > 0) {
                    $nightFare['modified_by'] = $user_id;
                } else {
                    $nightFare['created_by'] = $user_id;
                    $nightFare['created_date'] = date('Y-m-d h:i:s');
                }

                $this->addUpdateFareData($nightFareId, $tablenightCharge, $nightFare);

                /// PREMIUMS Fare STARTS HERE ///////////

                $premiumsFare = [
                    'base_vehicle_id' => $base_vehicle_id,
                    'premiums_type' => $postdata['premiums_type'],
                    'premiums_value' => $postdata['premiums_value'],
                    'ip' => $_SERVER['REMOTE_ADDR'],
                    'status' => 1
                ];

                if ($premiumsFareId > 0) {
                    $premiumsFare['modified_by'] = $user_id;
                } else {
                    $premiumsFare['created_by'] = $user_id;
                    $premiumsFare['created_date'] = date('Y-m-d h:i:s');
                }


                $this->addUpdateFareData($premiumsFareId,$tablepremiumsCharge,$premiumsFare);

                // Add peak time charge //
                    if($base_vehicle_id>0){
                     // Delete local package fare details //
                        $url = $this->apiUrl() . "/".$tablepeaktimeFare."/".$base_vehicle_id;
                        $resp2 = $this->delete($url);
                    //END //

                     $peakStartTimeArr  = array_filter($postdata['start_time']);
                     $peakEndTime = array_filter($postdata['end_time']);
                     $peakTimeValue = array_filter($postdata['peaktime_value']);
                        if(count($peakStartTimeArr)>0){
                          for($i=0; $i<count($peakStartTimeArr); $i++){
                               $peakTimeArr = [
                                   'base_vehicle_id' => $base_vehicle_id,
                                   'start_time' => $peakStartTimeArr[$i],
                                   'end_time' => $peakEndTime[$i],
                                   'peaktime_value' => $peakTimeValue[$i],
                                   'created_date' => date('Y-m-d h:i:s'),
                                   'created_by'   => $user_id,
                                   'status'       =>1,
                                   'ip' => $_SERVER['REMOTE_ADDR'],
                                   ];
                           $url = $this->apiUrl() . "/".$tablepeaktimeFare;
                           $resp = $this->post($url, $peakTimeArr);
                        }
                       }
                    }

                // END  //



                 // Add Extra charge //
                    if($base_vehicle_id>0){
                     // Delete Extra charges fare details //
                        $url = $this->apiUrl() . "/".$tableextraFare."/".$base_vehicle_id;
                        $resp2 = $this->delete($url);
                    //END //

                     $extra_value_1     = array_filter($postdata['extras_no_name1']);
                     $extra_value_2     = array_filter($postdata['extras_no_name2']);
                     $extraValueType    = array_filter($postdata['extrasvaluetype']);
                     $extraValueType = array_values($extraValueType);
                     //echo '<pre>';print_r($extraValueType);die();
                        if(count($extra_value_1)>0){
                          for($i=0; $i<count($extra_value_1); $i++){
                               $extrasArr = [
                                   'base_vehicle_id' => $base_vehicle_id,
                                   'extras_master_id' => $extra_value_1[$i],
                                   'extra_value_type' => $extraValueType[$i],
                                   'extra_value' => $extra_value_2[$i],
                                   'created_date' => date('Y-m-d h:i:s'),
                                   'created_by'   => $user_id,
                                   'status'       =>1,
                                   'ip' => $_SERVER['REMOTE_ADDR'],
                                   ];
                               //echo '<pre>';print_r($extrasArr);die();
                           $url = $this->apiUrl() . "/".$tableextraFare;
                           $resp = $this->post($url, $extrasArr);
                        }
                       }
                       //die;

                    }

                // END  //

                $result = ['result' => true, 'message' => $msg];
            } else {
                $result = ['result' => false, 'message' => $form->getMessages()];
            }

            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }

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

    /**
     * index
     * @return ViewModel
     */
    public function addPriceShareAction() {
        $viewModel = new ViewModel();
        $sessionContainer = new Container('userlogin');
        $userData = $sessionContainer->userData;
        $userTypeId = $userData['user_type_id'];
        $user_id = $sessionContainer->user_id;

        $addFareSession = new Container('addfaresession');
        $base_vehicle_id = $addFareSession->baseVehicleId;

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

        if ($request->isXmlHttpRequest()) {
            $postdata = $request->getPost()->toArray();
            $form->setData($postdata);
            $compShareId = $postdata['comp_share_id'];
            $partnerShareId = $postdata['partner_share_id'];
            $driverShareId = $postdata['driver_share_id'];
            $msg = "Share Details Insert Successfully";
            if ($compShareId > 0 || $partnerShareId > 0 || $driverShareId > 0) {
                $msg = "Share Details Updated Successfully";
            }
            //Debug::dump($postdata); exit;

            if ($form->isValid()) {
               $tableShareModel=$this->fareShare;
                /* Comp Starts Here */
                $compShare = [
                    'base_vehicle_id' => $base_vehicle_id,
                    'share_type_id' => $postdata['company_share_type_id'],
                    'share_value_type' => $postdata['company_share_type'],
                    'share_value' => $postdata['company_share'],
                    'status' => 1,
                    'ip' => $_SERVER['REMOTE_ADDR']
                ];

                if ($compShareId > 0) {
                    $compShare['modified_by'] = $user_id;
                } else {
                    $compShare['created_by'] = $user_id;
                    $compShare['created_date'] = date('Y-m-d h:i:s');
                }


                $this->addUpdateFareData($compShareId, $tableShareModel, $compShare);

                /* Partner Starts Here */
                $partnerShare = [
                    'base_vehicle_id' => $base_vehicle_id,
                    'share_type_id' => $postdata['partner_share_type_id'],
                    'share_value_type' => $postdata['partner_share_type'],
                    'share_value' => $postdata['partner_share'],
                    'status' => 1,
                    'ip' => $_SERVER['REMOTE_ADDR']
                ];

                if ($partnerShareId > 0) {
                    $partnerShare['modified_by'] = $user_id;
                } else {
                    $partnerShare['created_by'] = $user_id;
                    $partnerShare['created_date'] = date('Y-m-d h:i:s');
                }

                $this->addUpdateFareData($partnerShareId, $tableShareModel, $partnerShare);

                /* Driver Starts Here */
                $driverShare = [
                    'base_vehicle_id' => $base_vehicle_id,
                    'share_type_id' => $postdata['driver_share_type_id'],
                    'share_value_type' => $postdata['driver_share_type'],
                    'share_value' => $postdata['driver_share'],
                    'status' => 1,
                    'ip' => $_SERVER['REMOTE_ADDR']
                ];

                if ($driverShareId > 0) {
                    $driverShare['modified_by'] = $user_id;
                } else {
                    $driverShare['created_by'] = $user_id;
                    $driverShare['created_date'] = date('Y-m-d h:i:s');
                }

                $this->addUpdateFareData($driverShareId, $tableShareModel, $driverShare);
                $result = ['result' => true, 'message' => $msg];
            } else {
                $result = ['result' => false, 'message' => $form->getMessages()];
            }

            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }

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

    /**
     * index
     * @return ViewModel
     */
    public function middleLinksAction() {

        $viewModel = new ViewModel();
        return $viewModel;
    }

    /**
     * index
     * @return ViewModel
     */
    public function viewUpdateRecordsAction() {

        $viewModel = new ViewModel();
        return $viewModel;
    }

    public function getCountryList() {
        $countryJsonDataArray = [];
        $url = $this->apiUrl() . "/country";
        $resp = $this->get($url);
        $countryJsonData = Json::decode($resp->getBody(), true);
        foreach ($countryJsonData as $res) {
            $countryJsonDataArray[$res['id']] = $res['name'];
        }
        return $countryJsonDataArray;
    }

    public function getStateWiseListAction() {
        $stateJsonDataArray = [];
        $country_id = 101;
        $val = '{"where": {"country_id": "' . $country_id . '%"}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/state?&filter=" . $val;
        $resp = $this->get($url);
        $stateJsonData = Json::decode($resp->getBody(), true);
        foreach ($stateJsonData as $res) {
            $stateJsonDataArray[$res['id']] = $res['name'];
        }
        return $stateJsonDataArray;
    }

    public function getStateListAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $country_id = $postData['country_id'];
        $val = '{"where": {"country_id": "' . $country_id . '%"}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/state?&filter=" . $val;
        $resp = $this->get($url);
        $stateJsonData = Json::decode($resp->getBody(), true);
        if (!empty($stateJsonData)) {
            foreach ($stateJsonData as $value) {
                $data[] = ["id" => $value['id'], "name" => $value['name']];
            }
            $response = ["status" => true, "data" => $data];
        } else {
            $response = ["status" => false];
        }
        $view = new JsonModel($response);
        return $view;
    }

    public function getCityListAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $state_id = $postData['state_id'];
        $val = '{"where": {"state_id": "' . $state_id . '%"}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/city?&filter=" . $val;
        $resp = $this->get($url);
        $cityJsonData = Json::decode($resp->getBody(), true);
        if (!empty($cityJsonData)) {
            foreach ($cityJsonData as $value) {
                $data[] = ["id" => $value['id'], "name" => $value['name']];
            }
            $response = ["status" => true, "data" => $data];
        } else {
            $response = ["status" => false];
        }
        $view = new JsonModel($response);
        return $view;
    }


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

    public function getCurrencyList() {
        $currencyTypeJsonDataArray = [];
        $url = $this->apiUrl() . "/master-currency";
        $resp = $this->get($url);
        $currencyTypeJsonData = Json::decode($resp->getBody(), true);
        foreach ($currencyTypeJsonData as $res) {
            $currencyTypeJsonDataArray[$res['id']] = $res['name'];
        }
        return $currencyTypeJsonDataArray;
    }

    public function getWeekDaysList() {
        $data = [];
        $url = $this->apiUrl() . "/week-days-list";
        $resp = $this->get($url);
        $weekTypeJsonData = Json::decode($resp->getBody(), true);
        if (!empty($weekTypeJsonData)) {
            foreach ($weekTypeJsonData as $value) {
                $data[] = ["id" => $value['id'], "name" => $value['name']];
            }
            $response = ["status" => true, "data" => $data];
        } else {
            $response = ["status" => false];
        }
        return $response;
    }

    public function getVendorClientList($vendor_id) {
        $data = [];
        $url = $this->apiUrl() . "/user/getVendorClient?vendor_id=" . $vendor_id;
        $resp = $this->get($url);
        $clientJsonData = Json::decode($resp->getBody(), true);
        if (!empty($clientJsonData)) {
            foreach ($clientJsonData['responsedata'] as $value) {
                $data[$value['user_id']] = $value['clientname'];
            }
            $response = ["status" => true, "data" => $data];
        } else {
            $response = ["status" => false];
        }
        return $response;
    }

    public function insertCabFare($data) {
        $url = $this->apiUrl() . "/fare_management/addfare";
        $resp = $this->post($url, $data);
        $response = Json::decode($resp->getBody(), true);
        return $response;
    }

    public function getFareListData($data) {
        $url = $this->apiUrl() . "/fare_management/getFare";
        $resp = $this->post($url, $data);
        $fareList = Json::decode($resp->getBody(), true);
        if ($fareList['responsedata'] != "") {
            $val = ["status" => true, "data" => Json::decode($resp->getBody(), true)];
        } else {
            $val = ["status" => false, "data" => Json::decode($resp->getBody(), true)];
        }
        return $val;
    }

    public function getMasterExtraData(){
        $masterextraArray = [];
        $url = $this->apiUrl() . "/master-extra";
        $resp = $this->get($url);
        $masterExtraData = Json::decode($resp->getBody(), true);
        if (!empty($masterExtraData)) {
            foreach ($masterExtraData as $value) {
                 $masterextraArray[$value['id']] = $value['name'];
            }
        }
        return $masterextraArray;
    }

    /* Get Cab Fare Detail by base Vehicle Id */
    public function getFareDetailByBaseVehicleId($arrval=array()){
         $base_vehicle_id = $arrval['base_vehicle_id'];
         $booking_mode = $arrval['booking_mode'];
         $userTypeId = $arrval['user_type_id'];
         $finalvalue = [];

         if($base_vehicle_id!=''){
                $tablebasicTax=$this->basicTax;
                $tablefareSetting=$this->fareSetting;
                $tablelocalPkgFare=$this->localPkgFare;
                $tabledistUptoFare=$this->distanceUptoFare;
                $tablecancelFare=$this->cancellationFare;
                $tablewaitingFare=$this->waitingCharge;
                $tableprewaitingFare=$this->preWaitingCharge;
                $tablediswaitingFare=$this->distanceWaitingFare;
                $tablenightCharge= $this->nightCharge;
                $tablePremiumFare= $this->premiumsCharge;
                $tablepeakTimeFare= $this->peakTimeCharge;
                $tableextrasFare=$this->extras;
                $tablefixRoute=$this->fixRoute;
                $tablepostalFare=$this->postalFare;
                $tableshareFare=$this->fareShare;

                $bookingModeFareData   =   $this->getFareData($base_vehicle_id,$booking_mode);
                if(!empty($bookingModeFareData)){
                    $finalvalue['booking_mode_fare_data'] = $bookingModeFareData[0];
                }

            // START GET TAX //
            $taxFareData = $this->getFareData($base_vehicle_id, $tablebasicTax);
            if (!empty($taxFareData)) {
                $finalvalue['tax_fare'] = $taxFareData[0];
            }
            // End //
            // START ROUNDING LEVEL DIRECTION //
            $taxSettingData = $this->getFareData($base_vehicle_id, $tablefareSetting);
            if (!empty($taxSettingData)) {
                $finalvalue['fare_setting'] = $taxSettingData[0];
            }
            // End //
            // START LOCAL PACKAGE FARE //
            $localPackageFareData = $this->getFareData($base_vehicle_id, $tablelocalPkgFare);
            if (!empty($localPackageFareData)) {
                $finalvalue['local_package_fare'] = $localPackageFareData;
            }
            // End //

            // START PEAK TIME CHARGES FARE //
            $distUptoFareData = $this->getFareData($base_vehicle_id, $tabledistUptoFare);
            if(!empty($distUptoFareData)){
                $finalvalue['rate_upto_distance'] = $distUptoFareData;
            }
            // End //

            // START CANCELLATION FARE //
            $cancellationFareData = $this->getFareData($base_vehicle_id, $tablecancelFare);
            if(!empty($cancellationFareData)){
                $finalvalue['cancellation_fare'] = $cancellationFareData[0];
            }
            // End //

            // START WAITING CHARGE FARE //
            $waitingFareData = $this->getFareData($base_vehicle_id, $tablewaitingFare);
            if(!empty($waitingFareData)){
                $finalvalue['waiting_fare'] = $waitingFareData;
            }
            // End //

             // START PRE-WAITING CHARGE FARE //
            $prewaitingFareData = $this->getFareData($base_vehicle_id, $tableprewaitingFare);
            if(!empty($prewaitingFareData)){
                $finalvalue['pre_waiting_fare'] = $prewaitingFareData;
            }
            // End //

            // START DISTANCE WAITING FARE //
            $distanceWaitingFareData = $this->getFareData($base_vehicle_id, $tablediswaitingFare);
            if(!empty($distanceWaitingFareData)){
                $finalvalue['distance_waiting_fare'] = $distanceWaitingFareData[0];
            }
            // End //

             // START NIGHT CHARGE FARE //
            $nightChargeData = $this->getFareData($base_vehicle_id, $tablenightCharge);
            if(!empty($nightChargeData)){
                $finalvalue['night_charge'] = $nightChargeData[0];
            }
            // End //

            // START PREMIUMS CHARGE FARE //
            $premiumsChargeData = $this->getFareData($base_vehicle_id, $tablePremiumFare);
            if(!empty($premiumsChargeData)){
                $finalvalue['premiums_charge'] = $premiumsChargeData[0];
            }
            // End //

            // START FIX ROUTE FARE //
            $fixRouteData = $this->getFareData($base_vehicle_id, $tablefixRoute);
            if(!empty($fixRouteData)){
                $finalvalue['fix_route'] = $fixRouteData[0];
            }
            // End //

            // START POSTAL FARE //
            $postalFareData = $this->getFareData($base_vehicle_id, $tablepostalFare);
            if(!empty($postalFareData)){
                $finalvalue['postal_fare'] = $postalFareData;
            }
            // End //

             // START PEAK TIME CHARGES FARE //
            $peakTimeFareData = $this->getFareData($base_vehicle_id, $tablepeakTimeFare);
            if(!empty($peakTimeFareData)){
                $finalvalue['peak_time_fare'] = $peakTimeFareData;
            }
            // End //

            // START EXTRAS FARE //
            $extrasFareData = $this->getFareData($base_vehicle_id, $tableextrasFare);
            if(!empty($extrasFareData)){
                $finalvalue['extras_fare'] = $extrasFareData;
            }
            // End //

            // START COMPANY SHARE //
            $shareFareData = $this->getFareData($base_vehicle_id, $tableshareFare);
            if(!empty($shareFareData)){ $finalvalue['share_fare'] = $shareFareData; }
            // End //

        }
        //echo '<pre>';print_r($finalvalue);die();
        return $finalvalue;
    }

    /* GET Master Local package BY booking mode and booking type */

    public function getMasterLocalPkg($bookingMode, $bookingtype) {
        $val2 = '{"where":{ "and" :[{"booking_mode": "' . $bookingMode . '"},{"booking_type":"' . $bookingtype . '"}]}}';
        $val2 = rawurlencode($val2);
        $url = $this->apiUrl() . "/local-package?&filter=" . $val2;
        $resp2 = $this->get($url);
        return $data = Json::decode($resp2->getBody(), true);
    }

    /* END */

    /* ADD UPDATE BOOKING MODE FARE DATA */

    public function addUpdateFareData($autoid, $bookingmode, $dataArr) {
        if ($autoid > 0) {
            $val = '{"id": "' . $autoid . '"}';
            $val = rawurlencode($val);
            $url = $this->apiUrl() . "/" . $bookingmode . "/upsertWithWhere?where=" . $val;
            $resp = $this->post($url, $dataArr);
        } else {
            $url = $this->apiUrl() . "/" . $bookingmode;
            $resp = $this->post($url, $dataArr);
        }
        return $fareData = Json::decode($resp->getBody(), true);
    }

    /* END */

    /** @Desc :Get Local package action */
    public function localPackageFareAction() {
        LocalPackageFareForm::$country = $this->getCountryList();
        LocalPackageFareForm::$booking_type = $this->CommonModel->getPackageTypeList();
        LocalPackageFareForm::$booking_mode_type = $this->CommonModel->getPackageModeList();

        //Local Package Listing Start

        $url = $this->apiUrl() . "/local-package/getlocalpkg";
        $resp4 = $this->get($url);
        $localPackageData = Json::decode($resp4->getBody(), true);

        //Local Package Listing End

        $form = new LocalPackageFareForm();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();

            $form->setData($request->getPost());
            if ($form->isValid()) {
                $package_name = $postData['distance_package_name'];
                $booking_mode = $postData['booking_mode_type'];
                $booking_type = $postData['booking_type'];
                $localPkgArr = array();
                for ($i = 0; $i < count($package_name); $i++) {
                    $localPkgArr[$i]['booking_mode'] = $booking_mode;
                    $localPkgArr[$i]['booking_type'] = $booking_type;
                    $localPkgArr[$i]['name'] = $postData['distance_package_name'][$i];
                    $localPkgArr[$i]['km'] = $postData['distance_ignore_km'][$i];

                    $insertArr = $localPkgArr[$i];
                    $url = $this->apiUrl() . "/local-package";
                    $resp = $this->post($url, $insertArr);
                    $fareList = Json::decode($resp->getBody(), true);
                    //echo '<pre>';print_r($fareList);die();
                }
                $this->redirect()->toRoute('cabfare', ['action' => 'local-package-fare']);
            }
        }

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

    public function viewLocalPkgAction() {

        $url = $this->apiUrl() . "/local-package/getlocalpkg";
        $resp4 = $this->get($url);
        $localPackageData = Json::decode($resp4->getBody(), true);

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

    /* GET BOOKING MODE FARE DATA FOR EDIT */

    public function getFareData($base_vehicle_id, $booking_mode) {
        $val = '{"where": {"base_vehicle_id": "' . $base_vehicle_id . '"}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/" . $booking_mode . "?&filter=" . $val;
        $resp = $this->get($url);
        return $data = Json::decode($resp->getBody(), true);
    }

    /* END */

    /** Add-update local package fare */
    public function addUpdateLocalpkgFare($base_vehicle_id, $addLocalPkgFare,$user_id,$userTypeId) {
        $tableModel="local-package-fare";
        if ($base_vehicle_id > 0) {
            // Delete local package fare details //
            $url = $this->apiUrl() . "/".$tableModel."/" . $base_vehicle_id;
            $resp2 = $this->delete($url);
            //END //

            if (count($addLocalPkgFare) > 0) {
                foreach ($addLocalPkgFare as $key => $val) {
                    $addpriceArr = [
                        'base_vehicle_id' => $base_vehicle_id,
                        'local_pkg_id' => $key,
                        'local_pkg_fare' => $val,
                        'created_date' => date('Y-m-d h:i:s'),
                        'created_by'=>$user_id
                    ];
                    $url = $this->apiUrl() . "/".$tableModel;
                    $resp = $this->post($url, $addpriceArr);
                }
            }
        }
    }


    /** Add-update local package fare */
    public function addUpdateDistUptoFare($base_vehicle_id, $disUptoRateFare,$user_id,$userTypeId) {
        $tableModel="distance-upto-rate";
        if ($base_vehicle_id > 0) {
            // Delete Rate Km Upto fare details //

            $url = $this->apiUrl() . "/".$tableModel."/" . $base_vehicle_id;
            $resp2 = $this->delete($url);
            //END //

            if (count($disUptoRateFare) > 0) {
                foreach ($disUptoRateFare as $key => $val) {
                    $addRateArr = [
                        'base_vehicle_id' => $base_vehicle_id,
                        'km_upto' => $key,
                        'rate_per_km' => $val,
                        'created_date' => date('Y-m-d h:i:s'),
                        'created_by'=>$user_id,
                        'status'=>1,
                        'ip'=>$_SERVER['REMOTE_ADDR']
                    ];
                    $url = $this->apiUrl() . "/".$tableModel;
                    $resp = $this->post($url, $addRateArr);
                }
            }
        }
    }

     /** Add-update Waiting Time Fees fare */
    public function addUpdateWatingTimeFare($base_vehicle_id, $waitingFees,$user_id,$userTypeId) {
            $tableModel="waiting-charge";
        if ($base_vehicle_id > 0) {
            // Delete Rate Km Upto fare details //
            $url = $this->apiUrl() . "/waiting-charge/" . $base_vehicle_id;
            $resp2 = $this->delete($url);
            //END //

            if (count($waitingFees) > 0) {
                foreach ($waitingFees as $key => $val) {
                    $addRateArr = [
                        'base_vehicle_id' => $base_vehicle_id,
                        'waiting_minute_upto' => $key,
                        'waiting_fees' => $val,
                        'created_date' => date('Y-m-d h:i:s'),
                        'created_by'=>$user_id,
                        'status'=>1,
                        'ip'=>$_SERVER['REMOTE_ADDR']
                    ];
                    $url = $this->apiUrl() . "/".$tableModel;
                    $resp = $this->post($url, $addRateArr);
                }
            }
        }
    }

     /** Add-update Pre Waiting Time Fees fare */
    public function addUpdatePreWatingTimeFare($base_vehicle_id,$prewaitingFees,$user_id,$userTypeId) {
        $tableModel="pre-waiting-charge";
        if ($base_vehicle_id > 0) {
            // Delete Rate Km Upto fare details //
            $url = $this->apiUrl() . "/".$tableModel."/" . $base_vehicle_id;
            $resp2 = $this->delete($url);
            //END //

            if (count($prewaitingFees) > 0) {
                foreach ($prewaitingFees as $key => $val) {
                    $addRateArr = [
                        'base_vehicle_id' => $base_vehicle_id,
                        'pre_waiting_upto_minutes' => $key,
                        'pre_waiting_fees' => $val,
                        'created_date' => date('Y-m-d h:i:s'),
                        'created_by'=>$user_id,
                        'status'=>1,
                        'ip'=>$_SERVER['REMOTE_ADDR']
                    ];
                    $url = $this->apiUrl() . "/".$tableModel;
                    $resp = $this->post($url, $addRateArr);
                }
            }
        }
    }

    /* END */

    /** Function to change Fare STATUS */
    public function fareStatusAction() {
        $finaldata = [];
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $user_id = 6;
        $data = $this->getRequest()->getPost();
        //print_r($data); die;
        $id = implode(',', $data['selected']);
        $fare_status = $data['status'];
        $data = ['user_id' => $user_id, 'id' => $id, 'fare_status' => $fare_status];
        $this->updateFareStatus($data);
        $fareList = $this->getFareListData($finaldata);
        $cabfareListing = $fareList['data']['responsedata'];
        //Debug::dump($cabfareListing); exit;
        $viewModel = new ViewModel(['cabfareListing' => $cabfareListing]);
        $viewModel->setTemplate('dashboard/cab-fare/cab-fare-listing.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /** Function to Update Fare STATUS */
    public function updateFareStatus($data) {
        $url = $this->apiUrl() . "/fare_management/fareStatus"; //die;
        $resp = $this->put($url, $data);
        $data = Json::decode($resp->getBody(), true);
        return $data;
    }


    /**
     * Vendor Fare
     * @return ViewModel
     */

    public function vendorFareAction() {

        $addFareSession = new Container('addfaresession');
        $addFareSession->getManager()->getStorage()->clear('addfaresession');
        $sessionContainer = new Container('userlogin');
        $userData = $sessionContainer->userData;
        $userTypeId =  $userData['user_type_id'];
        $user_id = $sessionContainer->user_id;
        //$user_id = 6;

        FareAddSearchForm::$state = $this->getStateWiseListAction();
        FareAddSearchForm::$booking_type = $this->CommonModel->getPackageTypeList();
        FareAddSearchForm::$vehicle_type = $this->getVehicleTypeList();
        $clientList = $this->getVendorClientList($user_id);
        FareAddSearchForm::$client = $clientList['data'];
        $form = new FareAddSearchForm();
        $request = $this->getRequest();
        $finaldata = [];
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();

            $form->setData($request->getPost());
            if ($post['fare_type'] == $this->publicFare) {
                $form->get('public_fare_selected')->setValue(1);
                $form->get('client_fare_selected')->setValue(0);
            }

            if ($post['fare_type'] == $this->clientFare) {
                $form->get('public_fare_selected')->setValue(0);
                $form->get('client_fare_selected')->setValue(1);
            }

            $data = [
                'client_id' => $post['client'],
                'state_id' => $post['fare_state'],
                'city_id' => $post['fare_city'],
                'master_package_id' => $post['booking_type'],
                'vehicle_type_id' => $post['vehicle_type'],
            ];
            $finaldata = array_filter($data);
            $finaldata['status'] = $post['status'];
        }


        if($userTypeId==4){ //// Condition for only vendor///
        $finaldata['vendor_id'] = $user_id;
        }
        $finaldata['user_type_id'] = 4;
        $finaldata['company_id'] = $this->config()->getConfig()->company->companyId;
        $fareList = $this->getFareListData($finaldata);
        $cabfareListing = $fareList['data']['responsedata'];
        $viewModel = new ViewModel(['form' => $form, 'cabfareListing' => $cabfareListing]);
        return $viewModel;
    }

       /**
     * View Fare
     * @return ViewModel
     */
    public function viewVendorFareAction() {
        $masterLocalPkg[]='';
        $fareDetails[]='';
        $cabfareData="";
        $viewModel = new ViewModel();
        $sessionContainer = new Container('userlogin');
        $userData = $sessionContainer->userData;
        $userTypeId = $userData['user_type_id'];
        $user_id = $sessionContainer->user_id;
        //$user_id = 6;
        //$base_vehicle_id=6;

        FareAddSearchForm::$country = $this->getCountryList();
        FareAddSearchForm::$booking_type = $this->CommonModel->getPackageTypeList();
        FareAddSearchForm::$booking_mode_type = $this->CommonModel->getPackageModeList();
        FareAddSearchForm::$vehicle_type = $this->getVehicleTypeList();
        //FareAddSearchForm::$state = $this->getStateWiseListAction();
        FareAddSearchForm::$currency = $this->getCurrencyList();
        FareAddPricePremiumForm::$masterextra = $this->getMasterExtraData();
        $clientList = $this->getVendorClientList($user_id);
        FareAddSearchForm::$client = $clientList['data'];
        $form = new FareAddSearchForm();
        $distanceform = new FareAddpriceDistanceForm();
        $hourform = new FareAddPriceHourForm();
        $distancehourform = new FareAddPriceDistanceHourForm();
        $distancewatingform = new FareAddPriceDistanceWaitingForm();
        $basicfareform = new FareAddBasicForm();
        $cancellationform = new FareAddCancellationFeesForm();
        $premiumform = new FareAddPricePremiumForm();
        $fixedrouteform = new FareAddPriceFixedRoutesForm();
        $shareform = new FareAddShareForm();
        $week_days = $this->getWeekDaysList();



        $addFareSession = new Container('addfaresession');
        //$addFareSession->getManager()->getStorage()->clear('addfaresession');

        $base_combination_id = $this->params('id');
        if($base_combination_id!=''){
            $addFareSession->getManager()->getStorage()->clear('addfaresession');

            $fareData    = $this->getFareListData(['base_combination_id'=>$base_combination_id,'user_type_id'=>$userTypeId]);
            //echo '<pre>';print_r($fareData); //die();
            $cabfareData = $fareData['data']['responsedata'][0];

            $fareId = $addFareSession->fareId = $cabfareData['base_combination_id'];
            $base_vehicle_id =  $addFareSession->baseVehicleId = $cabfareData['base_vehicle_id'];
            $bookingMode =  $addFareSession->bookingMode = $cabfareData['master_package_mode_id'];
            $bookingtype = $addFareSession->bookingtype = $cabfareData['master_package_id'];
        }else{
            $fareId = $addFareSession->fareId;
            $bookingMode = $addFareSession->bookingMode;
            $bookingtype = $addFareSession->bookingtype;
            $base_vehicle_id = $addFareSession->baseVehicleId;
            $cabfareData="";
        }
        //echo "Mohit"; die;
         /** Get Fare details for Edit */

        if($fareId!=''){
            if($userTypeId==4){
                $tableMode=$this->bookingVndModeType[$bookingMode];
            }else{
                $tableMode=$this->bookingModeType[$bookingMode];
            }
            $getFareData = ['base_vehicle_id'=>$base_vehicle_id, 'booking_mode'=>$tableMode,'user_type_id'=>$userTypeId];

            //$getFareData = ['base_vehicle_id'=>$base_vehicle_id, 'booking_mode'=>$this->bookingModeType[$bookingMode]];
            //echo '<pre>';print_r($getFareData);die();
            $fareDetails = $this->getFareDetailByBaseVehicleId($getFareData);
            //echo '<pre>';print_r($fareDetails);die();
            if(!empty($cabfareData)){
            $fareDetails['cabfare_detail'] = $cabfareData;
            }
        }else{
            $fareDetails['cabfare_detail']="";
            $fareDetails['tax_fare']="";
            $fareDetails['fare_setting']="";
        }
        /* END */

        /** GET MASTER LOCAL PACKAGE MODE */
            if($fareId!=''){
               $masterLocalPkg  = $this->getMasterLocalPkg($bookingMode,$bookingtype);
               //echo '<pre>';print_r($masterLocalPkg);die();
            }
        /* END */


        $request = $this->getRequest();
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $form->setData($request->getPost());
            //echo '<pre>';print_r($post);die();
            //echo $post['market_place']; exit;
            //echo $post['dispatch_garage'];
            if ($post['fare_type'] == $this->publicFare) {
                $form->getInputFilter()->get('client')->setRequired(false);
                $form->get('public_fare_selected')->setValue(1);
                $form->get('client_fare_selected')->setValue(0);
            }

            if ($post['fare_type'] == $this->clientFare) {
                $form->getInputFilter()->get('client')->setRequired(true);
                $form->get('public_fare_selected')->setValue(0);
                $form->get('client_fare_selected')->setValue(1);
            }


            if ($post['dispatch_type'] == $this->pointDispatch) {
                $form->get('point_dispatch_selected')->setValue(1);
                $form->get('garage_dispatch_selected')->setValue(0);
            }

            if ($post['dispatch_type'] == $this->garageDispatch) {
                $form->get('point_dispatch_selected')->setValue(0);
                $form->get('garage_dispatch_selected')->setValue(1);
            }

            if(isset($post['dispatch_garage'])!=""){

            if ($post['dispatch_garage'] == $this->ownGarage) {
                $form->getInputFilter()->get('garage_own_address')->setRequired(true);
                $form->getInputFilter()->get('garage_own_state')->setRequired(true);
                $form->getInputFilter()->get('garage_own_city')->setRequired(true);
                $form->getInputFilter()->get('garage_own_pincode')->setRequired(true);
                $form->getInputFilter()->get('garage_comp_address')->setRequired(false);
                $form->getInputFilter()->get('garage_comp_state')->setRequired(false);
                $form->getInputFilter()->get('garage_comp_city')->setRequired(false);
                $form->getInputFilter()->get('garage_comp_pincode')->setRequired(false);
                $form->get('own_garage_selected')->setValue(1);
                $form->get('comp_garage_selected')->setValue(0);
                }

            if ($post['dispatch_garage'] == $this->compGarage) {
                $form->getInputFilter()->get('garage_comp_address')->setRequired(true);
                $form->getInputFilter()->get('garage_comp_state')->setRequired(true);
                $form->getInputFilter()->get('garage_comp_city')->setRequired(true);
                $form->getInputFilter()->get('garage_comp_pincode')->setRequired(true);
                $form->getInputFilter()->get('garage_own_address')->setRequired(false);
                $form->getInputFilter()->get('garage_own_state')->setRequired(false);
                $form->getInputFilter()->get('garage_own_city')->setRequired(false);
                $form->getInputFilter()->get('garage_own_pincode')->setRequired(false);
                $form->get('own_garage_selected')->setValue(0);
                $form->get('comp_garage_selected')->setValue(1);
            }
            }

            if ($post['commission_type'] == $this->netRate) {
                $form->getInputFilter()->get('commission_value')->setRequired(false);
                $form->get('net_rate_selected')->setValue(1);
                $form->get('garage_dispatch_selected')->setValue(0);
            }

            if ($post['commission_type'] == $this->commissionRate) {
                $form->getInputFilter()->get('commission_value')->setRequired(true);
                $form->get('net_rate_selected')->setValue(0);
                $form->get('commission_rate_selected')->setValue(1);
            }


            if ($form->isValid()) {
                //echo "Mohit"; die;

                if ($post['fare_type'] == $this->clientFare) {
                    $client_id = $post['client'];
                } else {
                    $client_id = "";
                }
                if ($post['dispatch_type'] == $this->garageDispatch) {
                    $dispatch_garage = $post['dispatch_garage'];
                } else {
                    $dispatch_garage = "";
                }


                if ($post['dispatch_type'] == $this->garageDispatch) {
                    $dispatch_garage = $post['dispatch_garage'];
                    if ($dispatch_garage == $this->compGarage) {
                        $address = $post['garage_comp_address'];
                        $state = $post['garage_comp_state'];
                        $city = $post['garage_comp_city'];
                        $pincode = $post['garage_comp_pincode'];
                    } else {
                        $address = $post['garage_own_address'];
                        $state = $post['garage_own_state'];
                        $city = $post['garage_own_city'];
                        $pincode = $post['garage_own_pincode'];
                    }
                } else {
                    $dispatch_garage = "";
                }

                if ($post['commission_type'] == $this->commissionRate) {
                    $rate_type = $post['comm_type'];
                    $rate_value = $post['commission_value'];
                } else {
                    $rate_type = "";
                    $rate_value = "";
                }

            //Debug::dump($post); //exit;
            $created_date = date('Y-m-d H:i:s');
            $ip = $_SERVER['REMOTE_ADDR'];
            $data = [];
            $data = [
                'company_id' => $this->config()->getConfig()->company->companyId,
                'vendor_id' => $user_id,
                'client_id' => $client_id,
                'country_id' => $post['fare_country'],
                'state_id' => $post['fare_state'],
                'city_id' => $post['fare_city'],
                'master_package_id' => $post['booking_type'],
                'master_package_mode_id' => $post['booking_mode_type'],
                'market_place'=>$post['market_place'],
                'created_date' => $created_date,
                'created_by' => $user_id,
                'ip' => $ip,
                'vehicle_type_id' => $post['vehicle_type'],
                'type_of_dispatch' => $post['dispatch_type'],
                'garage_type' => $dispatch_garage,
                'address' => isset($address)?$address:'',
                'state' => isset($state)?$state:'',
                'city' => isset($city)?$city:'',
                'pincode' => isset($pincode)?$pincode:'',
                'fare_date_from' => date('Y-m-d',strtotime($post['fare_date_from'])),
                'fare_date_to' => date('Y-m-d',strtotime($post['fare_date_to'])),
                'currency' => $post['currency'],
                'rate' => $post['commission_type'],
                'rate_type' => $rate_type,
                'rate_value' => $rate_value,
                'week_days' => implode(",", $post['weekend']),
            ];
            $finaldata = array_filter($data);
            //Debug::dump($finaldata); exit;
            $status = $this->insertCabFare($finaldata);
            //echo '<pre>';print_r($status);die();
            if ($status['responsedata'] == true) {
                //$this->redirect()->toRoute('cabfare', ['action' => 'index']);
                $addFareSession->getManager()->getStorage()->clear('addfaresession');

                $addFareSession->fareId = $status['responsedata']['fare_id'];
                $addFareSession->baseVehicleId = $status['responsedata']['base_vehicle_id'];
                $addFareSession->bookingMode = $post['booking_mode_type'];
                $addFareSession->bookingtype = $post['booking_type'];
                $result = ['result' => true,'fare_id'=>$status['responsedata']['fare_id'],'booking_mode'=>$post['booking_mode_type'],'displayTabActived'=>true,'currentUrlRedirect' => 'Y'];
            }

             }else{
                $result = ['result' => false, 'message' => $form->getMessages()];
            }

            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
             $viewModel->setVariables(['data' => $result]);
            return $viewModel;

        }
        else{

              //echo'<pre>';print_r($form->getMessages());die();
        }


        $viewModel->setVariables(['form' => $form, 'week_days' => $week_days, 'distanceform' => $distanceform, 'hourform' => $hourform, 'distancehourform' => $distancehourform, 'distancewatingform' => $distancewatingform, 'basicfareform' => $basicfareform, 'cancellationform' => $cancellationform, 'premiumform' => $premiumform, 'fixedrouteform' => $fixedrouteform, 'shareform' => $shareform, 'fareDetails' => $fareDetails, 'fareId' => $fareId, 'bookingMode' => $bookingMode, 'masterLocalPkg' => $masterLocalPkg,'VndViewFare' => 'true']);
        return $viewModel;
    }

    public function getCityDataAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $term = $postData['term'];
        $url = $this->apiUrl() . "/city/stateCountryByCityName?city_name=" . $term;
        $resp = $this->get($url);
        $cityJsonData = Json::decode($resp->getBody(), true);
        $cityData = $cityJsonData['response']['data'];
        if ($cityJsonData['response']['status']=="success") {
            foreach ($cityData as $value) {
                $data[] = ["country_id" => $value['country_id'],"state_id" => $value['state_id'],"city_id" => $value['city_id'], "label" => $value['citystatecountry']];
            }
        } else {
            $data[] = ["label" => 'Not Exist'];
        }
        $view = new JsonModel($data);
        return $view;
    }


}
