<?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;
use Dashboard\Model\User;
use Dashboard\Model\Bid;
use Dashboard\Model\Vehicle;



class CabFareController extends RestAPIClientController {


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

    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() {
        $status=1;
        $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;
        $cabfareArr = [];
        FareAddSearchForm::$state = $this->getStateWiseListAction();
        FareAddSearchForm::$booking_type = $this->CommonModel->getPackageTypeList();
        FareAddSearchForm::$vehicle_type = $this->vehicleModel->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'],
                'vendor_id'=>$user_id,
                'user_type_id'=>$userTypeId
            ];
            $status=$post['status'];
            $finaldata = array_filter($data);
            $finaldata['status'] = $post['status'];
        }

        $finaldata['vendor_id'] = $user_id;
        //$finaldata['user_type_id'] = $userTypeId;
        $finaldata['company_id'] = $this->config()->getConfig()->company->companyId;

        $fareList = $this->getFareListData($finaldata);
        $cabfareListing = $fareList['data'];

        if(!empty($cabfareListing)){

            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,'status'=>$status]);
        return $viewModel;
    }

    /**
     * @Description : Add fare Action
     * @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;
        if($userTypeId!='10'){
            $data['created_by']=$user_id;
        }

        FareAddSearchForm::$country = $this->getCountryList();
        FareAddSearchForm::$booking_type = $this->CommonModel->getPackageTypeList();
        FareAddSearchForm::$booking_mode_type = $this->CommonModel->getPackageModeList();
        FareAddSearchForm::$vehicle_type = $this->vehicleModel->getVehicleTypeList();
        FareAddSearchForm::$vehicle_list = $this->vehicleModel->getAllVehicleList($data);
        //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'][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="";
            if($fareId!=''){
                $fareData    = $this->getFareListData(['base_combination_id'=>$fareId]);
                $cabfareData = $fareData['data'][0];
                $kilometerArr = [ 'source_name' => $cabfareData['city_name'],
                             'destination_name' => $cabfareData['destination_city_name'],
                              'source_id' => $cabfareData['city_id'],
                             'destination_id' => $cabfareData['destination_city']
                ];
                $cityJsonData = $this->bid->kiloMeter($kilometerArr);
                if(!empty($cityJsonData)){
                   $distance_km =  $cityJsonData['distance_km'];
                   $form->get('kilo_metor')->setValue($distance_km);
                }
            }
        }

         /** 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);
            if($cabfareData['city_id']!=''){
            $cityData=$this->CommonModel->getCitydetail($cabfareData['city_id']);
            $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($cabfareData['destination_city']!=''){
                $destinationcityData=$this->CommonModel->getCitydetail($cabfareData['destination_city']);
                $form->get('destination_city')->setValue($destinationcityData['citystatecountry']);
                $form->get('fare_state')->setValue($destinationcityData['state_id']);
                $form->get('destination_city_id')->setValue($destinationcityData['city_id']);
                $form->get('city_distance_id')->setValue($cabfareData['city_distance_id']);
            }
            if($cabfareData['city']!=''){
            $cityData=$this->CommonModel->getCitydetail($cabfareData['city']);

            $form->get('garage_city')->setValue($cityData['citystatecountry']);
            $form->get('garage_state')->setValue($cityData['state_id']);
            $form->get('garage_country')->setValue($cityData['country_id']);
            $form->get('garage_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($userTypeId!=10){ 
                $form->getInputFilter()->get('vehicle_type')->setRequired(false);               
             }
             
            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_address')->setRequired(true);
                $form->getInputFilter()->get('garage_city')->setRequired(true);
                $form->getInputFilter()->get('garage_pincode')->setRequired(true);

                $form->get('own_garage_selected')->setValue(1);
                $form->get('comp_garage_selected')->setValue(0);
            }

            if ($post['dispatch_garage'] == $this->compGarage) {

                $form->getInputFilter()->get('garage_address')->setRequired(true);
                $form->getInputFilter()->get('garage_city')->setRequired(true);
                $form->getInputFilter()->get('garage_pincode')->setRequired(true);

                $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()) {

                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'];
                        $address = $post['garage_address'];
                        $city = $post['garage_city_id'];
                        $pincode = $post['garage_pincode'];
                        $addressData = $this->fetchGoogleApiData($address);
                        $addressData = Json::decode($addressData);
                        if ($addressData->status == 'OK') {
                            $latitude = $addressData->results[0]->geometry->location->lat;
                            $longitude = $addressData->results[0]->geometry->location->lng;
                        } else {
                            $latitude  = "";
                            $longitude = "";
                        }
                  } else {
                            $dispatch_garage = "";
                            $address = "";
                            $city = "";
                            $pincode = "";
                            $latitude  = "";
                            $longitude = "";
                        }

                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;
                //echo '<pre>';print_r($post['weekend']);die();
            $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:'',
                'latitude'=> isset($latitude)?$latitude:'',
                'longitude'=> isset($longitude)?$longitude:'',
                'fare_date_from' => $this->userModel->changeDateFormat($post['fare_date_from']),
                'fare_date_to' => $this->userModel->changeDateFormat($post['fare_date_to']),
                'currency' => $post['currency'],
                'rate' => $post['commission_type'],
                'rate_type' => $rate_type,
                'rate_value' => $rate_value,
                'week_days' => implode(",", $post['weekend']),
                'id'=> isset($fareId)?$fareId:'',
                'user_id'=> $user_id,
                'city_distance_id'=> $post['city_distance_id'],
                'vehicle_list'  => $post['vehicle_list']
                //'user_type_id'=>$userTypeId
            ];
            //$finaldata = array_filter($data);
            $finaldata = $data;
            //Debug::dump($finaldata); exit;

            //for mode validation check start

            $data2 = [];
            $data2 = [
                'city_id' => $post['fare_city_id'],
                'vehicle_type_id' => $post['vehicle_type'],
                'master_package_id' => $post['booking_type'],
                'master_package_mode_id' => $post['booking_mode_type'],
                'user_id' => $user_id,
                //'user_type_id' => $userTypeId,
                'company_id' => $this->config()->getConfig()->company->companyId,
            ];
//echo '<pre>';print_r($data2);die();
            $getExistFare = $this->getFareListData($data2);
           //echo '<pre>';print_r($getExistFare);die();

            $cabFareExit = $getExistFare['data'];
            if(empty($cabFareExit))

           {
            $status = $this->insertCabFare($finaldata);

            //for mode validation check start end

            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{
                $base_combination_id =  $cabFareExit[0]['base_combination_id'];
               if(isset($base_combination_id) && $base_combination_id!=''){
                   $status = $this->updateCabFare($finaldata);
                   $result = ['result' => 'update'];
               }else{
                   //echo '<pre>';print_r($status);die();
                    $result = ['result' => 'exist'];
               }

            }

             }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,
                'usertype'=>$userTypeId,
                'google_map_url' => $this->config()->getConfig()->google_map->url,
                'google_map_key' => $this->config()->getConfig()->google_map->key,]);
        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');
                }

                /*if($userTypeId==4){
                    $tableModelTax=$this->vndbasicTax;
                }else{
                    $tableModelTax=$this->basicTax;
                }*/
                $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');
                }

                /*if($userTypeId==4){
                    $tableModelFareSetting=$this->vndfareSetting;
                }else{
                    $tableModelFareSetting=$this->fareSetting;
                }*/
                $tableModelFareSetting=$this->fareSetting;
                $jsonresponseSettingData = $this->addUpdateFareData($taxFareSettingId, $tableModelFareSetting, $basicfareSettings);
                $result = ['result' => true, 'message' => $msg , 'displayTabActived'=>'fees-tab' , 'hideTabActived'=>'basic'];
            } 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);
                $addLocalPkgFare = array_filter($addLocalPkgFare);
                $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, 'displayTabActived'=>'basic' , 'hideTabActived'=>'distance-hour'];

            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 = isset($postdata['distance_waiting_amount'])?$postdata['distance_waiting_amount']:'';
            $localpkgId = isset($postdata['localpkgid'])?$postdata['localpkgid']:'';
            if($dist_wait_amount!=""){
            if (isset($dist_wait_amount) && count($dist_wait_amount) > 0) {
                $addLocalPkgFare = array_combine($localpkgId, $dist_wait_amount);
                $addLocalPkgFare = array_filter($addLocalPkgFare);
                $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, 'displayTabActived'=>'basic' , 'hideTabActived'=>'distance-waiting'];

            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();
            //echo '<pre>';print_r($postdata);die();
            $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);
                $addLocalPkgFare = array_filter($addLocalPkgFare);
                $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, 'displayTabActived'=>'basic' , 'hideTabActived'=>'distance'];

            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, 'displayTabActived'=>'share-tab' , 'hideTabActived'=>'fixed-route-tab'];

            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']:'';
            //echo '<pre>';print_r($hour_amount);die();
            if (!empty($hour_amount) && count($hour_amount) > 0) {
                //$hour_amount = array_filter($postdata['hour_amount']);
                //echo '<pre>';print_r($hour_amount);//die();
                $localpkgId = $postdata['localpkgid'];
                //echo '<pre>';print_r($localpkgId);die();
                $addLocalPkgFare = array_combine($localpkgId, $hour_amount);
                $addLocalPkgFare = array_filter($addLocalPkgFare);
                //$addLocalPkgFare = array_intersect_key($hour_amount,$localpkgId);
               // echo '<pre>';print_r($addLocalPkgFare);die();
                $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, 'displayTabActived'=>'basic' , 'hideTabActived'=>'hour'];

            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 = ($postdata['pre_waiting_minutes_upto']);
            $pre_waiting_time_fees = ($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, 'displayTabActived'=>'premium-tab' , 'hideTabActived'=>'fees-tab'];
            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 , 'displayTabActived'=>'fixed-route-tab' , 'hideTabActived'=>'premium-tab'];
            } 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;
        $uri = $this->getRequest()->getUri();
        $baseUrl = sprintf('%s://%s/', $uri->getScheme(), $uri->getHost());

        $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);

                $redPath = $baseUrl . 'cabfare';

                if($userTypeId==4){
                $redPath = $baseUrl . 'cabfare/vendor-fare';
                }
                $result = ['result' => true, 'message' => $msg,'redirectUrl'=>$redPath];
            } 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);
        if($vehicleTypeJsonData['status']=="success"){
        foreach ($vehicleTypeJsonData['data'] 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/newaddfare";
        $resp = $this->post($url, $data);
        $response = Json::decode($resp->getBody(), true);
        return $response;
    }

    public function updateCabFare($data) {
        $url = $this->apiUrl() . "/fare_management/updatecabfare";
        $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']['status'] == "success") {
            $val = ["status" => true, "data" => $fareList['responsedata']['data']];
        } else {
            $val = ["status" => false, "data" => $fareList['responsedata']['data'],'msg'=>$fareList['responsedata']['msg']];
        }
        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 . '"},{"status":"1"}]}}';
        $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) {
        $val = '{"where":{"base_vehicle_id": "' . $dataArr['base_vehicle_id'] .'"}}';
        if($bookingmode=='company-share'){
            $val = '{"where":{"and": [{"id":"'.$autoid.'"},{"base_vehicle_id": "' . $dataArr['base_vehicle_id'] .'"}]} }';
        }

        $val = rawurlencode($val);
        $urlFare = $this->apiUrl() . "/" . $bookingmode . "?&filter=" . $val;
        $respFare = $this->get($urlFare);
        $fareDataExist = Json::decode($respFare->getBody(), true);

        if(!empty($fareDataExist)){

            $val = '{"base_vehicle_id": "' . $dataArr['base_vehicle_id'] . '"}';
            if($bookingmode=='company-share'){
                $val = '{"id": "' . $autoid . '"}';
            }
            $val = rawurlencode($val);
            $url = $this->apiUrl() . "/" . $bookingmode . "/update?where=" . $val;
            $resp = $this->post($url, $dataArr);
        }else{
            $url = $this->apiUrl() . "/" . $bookingmode;
            $resp = $this->post($url, $dataArr);
        }
        //die;
        /*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() {
        $finalData=[];
        LocalPackageFareForm::$country = $this->getCountryList();
        LocalPackageFareForm::$booking_type = $this->CommonModel->getPackageTypeList();
        LocalPackageFareForm::$booking_mode_type = $this->CommonModel->getPackageModeList();

        //Local Package Listing Start
        $localPackageData= $this->CommonModel->getLocalPkg();
        //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'];
               //$package_name=array_filter($package_name);
                $booking_mode = $postData['booking_mode_type'];
                $booking_type = $postData['booking_type'];
                $localPkgArr = array();
                for ($i = 0; $i < count($package_name); $i++) {
                    if($postData['distance_package_name'][$i]!=''){
                    $localPkgArr[$i]['booking_mode'] = $booking_mode;
                    $localPkgArr[$i]['booking_type'] = $booking_type;
                    $localPkgArr[$i]['name'] = $postData['distance_package_name'][$i];
                    if($booking_mode != 2){
                     $localPkgArr[$i]['km'] = $postData['distance_ignore_km'][$i];
                    }
                    if($booking_mode==2 || $booking_mode==3){
                    $localPkgArr[$i]['hrs'] = $postData['distance_ignore_hr'][$i];
                    }

                    $insertArr = $localPkgArr[$i];

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

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

    public function viewLocalPkgAction() {
        $localPackageData= $this->CommonModel->getLocalPkg();
        $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 //
            //echo '<pre>';print_r($addLocalPkgFare);die();
            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) {
                    if($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 = [];
        $cabfareArr = [];
        $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'];

        if(!empty($cabfareListing)){

            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(['cabfareListing' => $cabfareArr]);
        $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() {
        $status=1;
        $cabfareArr = [];
        $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->vehicleModel->getVehicleTypeList();
        $clientList = $this->getVendorClientList($user_id);
        FareAddSearchForm::$client = $clientList['data'];
        $form = new FareAddSearchForm();
        $request = $this->getRequest();
        $finaldata = [];
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $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 = [
                'city_id' => rtrim($city_ids,","),
                'master_package_id' => $post['booking_type'],
                'vehicle_type_id' => $post['vehicle_type'],
            ];
            $status=$post['status'];
            $finaldata = array_filter($data);
            $finaldata['status'] = $post['status'];
        }


        if($userTypeId==4){ //// Condition for only vendor///
            $finaldata['user_id'] = $user_id;
        }
        $finaldata['user_type_id'] = 4;
        $finaldata['company_id'] = $this->config()->getConfig()->company->companyId;
        $fareList = $this->getFareListData($finaldata);
        $cabfareListing = $fareList['data'];
        if(!empty($cabfareListing)){

            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,'status'=>$status]);
        return $viewModel;
    }

       /**
     * View Fare
     * @return ViewModel
     */
    public function viewVendorFareAction() {
        $VndViewFare=[];
        $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->vehicleModel->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]);
            $cabfareData = $fareData['data'][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="";
            $fareData    = $this->getFareListData(['base_combination_id'=>$fareId]);
            $cabfareData = $fareData['data'][0];
        }

         /** Get Fare details for View */

        if($fareId!=''){

            $tableMode=$this->bookingModeType[$bookingMode];
            $getFareData = ['base_vehicle_id'=>$base_vehicle_id, 'booking_mode'=>$tableMode,'user_type_id'=>$userTypeId];
            $fareDetails = $this->getFareDetailByBaseVehicleId($getFareData);
            if($cabfareData['city_id']!=''){
            $cityData=$this->CommonModel->getCitydetail($cabfareData['city_id']);
            $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($cabfareData['city']!=''){
            $cityData=$this->CommonModel->getCitydetail($cabfareData['city']);

            $form->get('garage_city')->setValue($cityData['citystatecountry']);
            $form->get('garage_state')->setValue($cityData['state_id']);
            $form->get('garage_country')->setValue($cityData['country_id']);
            $form->get('garage_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 */

$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'=>$VndViewFare]);
        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;
    }


    /** @Desc :Get Local package action */
    public function editPackageFareAction() {
        LocalPackageFareForm::$country = $this->getCountryList();
        $masterBookType= $this->config()->getConfig()->masterBookType->cab;
        LocalPackageFareForm::$booking_type = $this->CommonModel->getPackageListAction($masterBookType);
        LocalPackageFareForm::$booking_mode_type = $this->CommonModel->getPackageModeList();

        //Local Package Listing Start

        $localPkgId = $this->params('id');

        $url = $this->apiUrl() . "/local-package/getlocalpkg?id=".$localPkgId;
        $resp4 = $this->get($url);
        $localPackageData = Json::decode($resp4->getBody(), true);
        $localPackageData = $localPackageData['data'][0];

        //Local Package Listing End

        $form = new LocalPackageFareForm();
        $request = $this->getRequest();
        $form->get('id')->setValue($localPackageData['local_package_id']);
        $form->getInputFilter()->get('booking_mode_type')->setRequired(false);
        $form->get('booking_type')->setValue($localPackageData['package_type']);
        $form->get('distance_package_name')->setValue($localPackageData['package_name']);
        $form->get('distance_ignore_hr')->setValue($localPackageData['hrs']);
        $form->get('distance_ignore_km')->setValue($localPackageData['km']);
        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();
            //echo '<pre>';print_r($postData);die();
            $form->setData($request->getPost());
            if ($form->isValid()) {

                $data=[
                    'booking_type'=>$postData['booking_type'],
                    'name'=>$postData['distance_package_name'],
                    'hrs'=>$postData['distance_ignore_hr'],
                    'km'=>$postData['distance_ignore_km'],
                    'status'=>1,
                    'id'=>$postData['id']
                ];
                //echo '<pre>';print_r($data);die();

                $val = '{"id": "' . $postData['id'] . '"}';
                $val = rawurlencode($val);
                $url = $this->apiUrl() . "/local-package/upsertWithWhere?where=" . $val;
                $resp = $this->post($url, $data);
                $fareList = Json::decode($resp->getBody(), true);
                //echo '<pre>';print_r($fareList);die();

                $this->redirect()->toRoute('cabfare', ['action' => 'view-local-pkg']);
            }else{
                $msg= $form->getMessages();
            }
        }

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

     public function localPackageStatusAction($data = null) {
        $id=[];
        $package_status=[];
        $data=[];
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];

        $data = $this->getRequest()->getPost();
        $id = implode(',', $data['selected']);
        $package_status = $data['status'];
        $data = ['user_id' => $user_id, 'id' => $id, 'package_status' => $package_status];
        $this->packageStatus($data);
        $localPackageData= $this->CommonModel->getLocalPkg();

        $viewModel = new ViewModel(['localPackageData' => $localPackageData]);
        $viewModel->setTemplate('/dashboard/cab-fare/view-local-pkg');
        $viewModel->setTerminal(true);
        return $viewModel;

    }

     /** Function to Update local Package STATUS */
    public function packageStatus($data) {
        $url = $this->apiUrl() . "/local-package/updateStatus";
        $resp = $this->put($url, $data);
        $data = Json::decode($resp->getBody(), true);
        return $data;
    }

    public function deleteLocalPackageAction()
    {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];
        $id = $this->params()->fromQuery('id');

        if(!empty($id)){
        $data = ['user_id' => $user_id, 'id' => $id, 'package_status' => 2];
        $response=$this->packageStatus($data);
        if ($response['response']['changedRows']==1) {
                    $msg = "Local Package Deleted Successfully..";
                    $this->redirect()->toRoute('cabfare', ['action' => 'local-package-fare']);
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                }
                else{
                    $msg = "Could Not Deleted..";
                   $this->redirect()->toRoute('cabfare', ['action' => 'local-package-fare']);
                   $this->flashMessenger()->addMessage(array('success' => $msg));
                }
        }


    }

    public function fetchGoogleApiData($address) {
        $url = $this->config()->getConfig()->google_map->apiData . "?address=" . urlencode($address) . '&key=' . $this->config()->getConfig()->google_map->key;
        $curl_handle = curl_init();
        curl_setopt($curl_handle, CURLOPT_URL, $url);
        curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl_handle);
        $result = curl_exec($curl_handle);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($curl_handle));
        }
        curl_close($curl_handle);
        return $result;
    }
    



}
