<?php

namespace Outstation\Controller;

use Application\Controller\RestAPIClientController;
use Outstation\Model\Outstation;
use Application\Model\CommonModel;
use Dashboard\Model\Booking;
use Outstation\Form\{
    OneWaySearchForm,
    RoundTripSearchForm,
    MultiCitySearchForm,
    TravellerForm,
    GuestForm,
    ProductForm,
    LoginForm
};
use Zend\View\Model\{
    ViewModel,
    JsonModel
};
use Zend\Debug\Debug;
use Outstation\Service\{
    CategoryManager,
    AttributeManager
};
use Zend\Session\Container;
use Zend\Json\Json;

class IndexController extends RestAPIClientController {

    public function __construct() {
        $this->outstationModel = new Outstation();
        $this->CommonModel = new CommonModel();
        $this->bookingModel = new Booking();
    }

    private $itemCount = 2;
    //private $onWayType = 1;
    private $roundTripType = 1;
    private $multiCityType = 2;
    private $flightModeOff = 0;
    private $flightModeOn = 1;
    private $masterPackageType = 4;
    private $oneWayPackageType = 5;
    private $pickupAreaMsg = "Please enter valid Pickup City";
    private $dropAreaMsg = "Please enter valid Drop City";
    private $pickupAddressMsg = "Please enter valid Pickup Address";
    private $extras = 'extras';
    private $peakTimeCharge = 'peak_time_charges';
    private $extraDays = 1;

    public function indexActionOld() {

        // Add 3 categories :
        $categoryManager = new CategoryManager();

        $data['id'] = 1;
        $data['title'] = 'Main course';

        $categoryManager->addCategory($data);

        $data['id'] = 2;
        $data['title'] = 'Cake';

        $categoryManager->addCategory($data);
        $data['id'] = 3;
        $data['title'] = 'Aperitif';

        $categoryManager->addCategory($data);


        // Add 3 attributes :
        $attributeManager = new AttributeManager();
        $data['id'] = 1;
        $data['title'] = 'Color';

        $attributeManager->addAttribute($data);

        $data['id'] = 2;
        $data['title'] = 'Energy';

        $attributeManager->addAttribute($data);


        $form = new ProductForm('product-form', null, $categoryManager, $attributeManager);
        //$form->bind($data);
        $data = '';

        // Check if user has submitted the form
        if ($this->getRequest()->isPost()) {

            // Fill in the form with POST data
            $data = $this->params()->fromPost();
            //Debug::dump($data);exit;

            $form->setData($data);

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

                // Get filtered and validated data
                $data = $form->getData();
            }
        }


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

    /**
     *
     * @return ViewModel
     */
    public function oneWayAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $userId = $loginData['user_id'];
        $city_name = '';
        $cityData = $this->getRequest()->getQuery()->toArray();
        //echo '<pre>';print_r($cityData);die();
        //create form object
        $form = new OneWaySearchForm();
        $sessionCityContainer = new Container('vehicleCityData');
        //get request object
        if(!empty($sessionCityContainer->pickup_city)){
            $pickupCity    =   $sessionCityContainer->pickup_city;
            $cityId        =   $sessionCityContainer->city_id;
            $drop_city     =   $sessionCityContainer->drop_city;
            $dropcity_id   =   $sessionCityContainer->dropcity_id;
            $form->get('pickup_city')->setValue($pickupCity);
            $form->get('pickcity_id')->setValue($cityId);
            if(!empty($drop_city)){
            $form->get('drop_city')->setValue($drop_city);
            $form->get('dropcity_id')->setValue($dropcity_id);
            }
            $boundData = $this->getLatLngData($pickupCity);
            //echo '<pre>';print_r($boundData);die();
            if ($boundData['status'] == 1) {
                $form->get('city_latitude')->setValue($boundData['data']['lat']);
                $form->get('city_longitude')->setValue($boundData['data']['lng']);
                $form->get('city_northeast_latitude')->setValue($boundData['data']['north_east_lat']);
                $form->get('city_northeast_longitude')->setValue($boundData['data']['north_east_lng']);
                $form->get('city_southwest_latitude')->setValue($boundData['data']['south_west_lat']);
                $form->get('city_southwest_longitude')->setValue($boundData['data']['south_west_lng']);
            }
            $sessionVehContainer = new Container('vehicleSearchData');
            $data = $sessionVehContainer->vehicleSearchData;
            if($data!=""){
                $form->setData($data);
            }
        }

        if (!empty($cityData)) {
            //$sessionVehContainer = new Container('vehicleSearchData');
            //unset($sessionVehContainer->vehicleSearchData);

            $sessionCityContainer->pickup_city = $cityData['city'];
            $sessionCityContainer->city_id = $cityData['city_id'];
            if(!empty($cityData['drop_city'])){
            $sessionCityContainer->drop_city = $cityData['drop_city'];
            $sessionCityContainer->dropcity_id = $cityData['drop_city_id'];
            }
            $form->get('pickup_city')->setValue($cityData['city']);
            $form->get('pickcity_id')->setValue($cityData['city_id']);
            $form->get('pickup_date')->setValue(isset($cityData['start_date'])?$cityData['start_date']:'');
            $form->get('pickup_time')->setValue(isset($cityData['start_time'])?$cityData['start_time']:'');
            if(!empty($cityData['drop_city'])){
            $form->get('drop_city')->setValue($cityData['drop_city']);
            $form->get('dropcity_id')->setValue($cityData['drop_city_id']);
            }
            $city_name = $cityData['city'];
            $boundData = $this->getLatLngData($city_name);
            //echo '<pre>';print_r($boundData);die();
            if ($boundData['status'] == 1) {
                $form->get('city_latitude')->setValue($boundData['data']['lat']);
                $form->get('city_longitude')->setValue($boundData['data']['lng']);
                $form->get('city_northeast_latitude')->setValue($boundData['data']['north_east_lat']);
                $form->get('city_northeast_longitude')->setValue($boundData['data']['north_east_lng']);
                $form->get('city_southwest_latitude')->setValue($boundData['data']['south_west_lat']);
                $form->get('city_southwest_longitude')->setValue($boundData['data']['south_west_lng']);
            }

        }else{
            $sessionVehContainer = new Container('vehicleSearchData');
            $data = $sessionVehContainer->vehicleSearchData;
            //echo '<pre>';print_r($data);die();
            if($data!=""){
                if(isset($data['city_id']) && !empty($data['city_id']))
                {
                    $form->get('pickcity_id')->setValue($data['city_id']);
                }
                if(isset($data['pickcity_id']) && !empty($data['pickcity_id']))
                {
                    $form->get('pickcity_id')->setValue($data['pickcity_id']);
                }
            $form->setData($data);
            }
        }
        $form->get('module_type')->setValue('');
        $form->get('master_package_type')->setValue($this->oneWayPackageType);
        $request = $this->getRequest();
        //if request will be post
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();

            $form->setData($request->getPost());
            if ($post['flight_mode'] == $this->flightModeOn) {
                $form->getInputFilter()->get('flight_number')->setRequired(true);
                $form->getInputFilter()->get('flight_time')->setRequired(true);
                $form->get('flight_mode_selected')->setValue($this->flightModeOn);
            }

            if ($post['flight_mode'] == $this->flightModeOff) {
                $form->getInputFilter()->get('flight_number')->setRequired(false);
                $form->getInputFilter()->get('flight_time')->setRequired(false);
                $form->get('flight_mode_selected')->setValue($this->flightModeOff);
            }

            if ($form->isValid()) {

                $pickAreaData = $this->fetchGoogleApiData($post['pickup_city']);
                $pickAreaData = json_decode($pickAreaData);

                $dropAreaData = $this->fetchGoogleApiData($post['drop_city']);
                $dropAreaData = json_decode($dropAreaData);

                $pickupAddressData = $this->fetchGoogleApiData($post['pickup_address']);
                $pickupAddressData = Json::decode($pickupAddressData);

                if ($pickAreaData->status == 'OK' && $dropAreaData->status == 'OK' && $pickupAddressData->status == 'OK') {

                    $pickAreaLat = $pickAreaData->results[0]->geometry->location->lat;
                    $pickAreaLng = $pickAreaData->results[0]->geometry->location->lng;

                    $dropAreaLat = $dropAreaData->results[0]->geometry->location->lat;
                    $dropAreaLng = $dropAreaData->results[0]->geometry->location->lng;

                    $dataDistance = $this->fetchGoogleApiDistance($pickAreaLat, $pickAreaLng, $dropAreaLat, $dropAreaLng);
                    $res = json_decode($dataDistance);
                    if ($res->status == 'OK') {
                        $res = $res->routes[0];
                        $distance = round((($res->legs[0]->distance->value) / 1000), 1);
                        $distance = round($distance);
                        $duration = $res->legs[0]->duration->text;
                    }

                    $dropTime = strtotime("+" . $duration, strtotime($post['pickup_date'] . ' ' . $post['pickup_time']));
                    $dropTime = date('Y-m-d H:i:s', $dropTime);
                    $drop = explode(' ', $dropTime);
                    $cityDistance = $this->getCityDistance($post['pickup_city'], $post['drop_city']);
                    if ($cityDistance > $distance) {
                        $distance = $cityDistance;
                    }
                    $sessionVehContainer = new Container('vehicleSearchData');
                    unset($sessionVehContainer->vehicleSearchData);
                    $sessionVehContainer->vehicleSearchData = $post;
                    
                    $recentData = [
                        'user_id'=>$userId,
                        'ip'=>$_SERVER['REMOTE_ADDR'],
                        'booking_stage'=>$this->config()->getConfig()->bookingSteps->step1,
                        'booking_data'=>$post
                    ];
                    $this->CommonModel->addRecentViewedItems($recentData);
                    
                    $this->redirect()->toRoute('outstation', [
                        'action' => 'one-way-vehicle-listing'
                            ], ['query' => [
                            'pickup_city' => $post['pickup_city'],
                            'drop_city' => $post['drop_city'],
                            'pickup_date' => $post['pickup_date'],
                            'pickup_time' => $post['pickup_time'],
                            'flight_mode' => $post['flight_mode'],
                            'flight_number' => $post['flight_number'],
                            'flight_time' => $post['flight_time'],
                            'pickup_address' => $post['pickup_address'],
                            'adults' => $post['adults'],
                            'childs' => $post['childs'],
                            'luggages' => $post['luggages'],
                            'no_of_vehicles' => $post['no_of_vehicles'],
                            'agree_terms' => $post['agree_terms'],
                            'distance' => $distance,
                            'duration' => $duration,
                            'drop_date' => $drop[0],
                            'drop_time' => $drop[1],
                            'pickcity_id' => $post['pickcity_id'],
                            'dropcity_id' => $post['dropcity_id'],
                            'master_package_type' => $post['master_package_type'],
                            'module_type' => $post['module_type'],
                            'city_latitude' => $post['city_latitude'],
                            'city_longitude' => $post['city_longitude'],
                            'city_northeast_latitude' => $post['city_northeast_latitude'],
                            'city_northeast_longitude' => $post['city_northeast_longitude'],
                            'city_southwest_latitude' => $post['city_southwest_latitude'],
                            'city_southwest_longitude' => $post['city_southwest_longitude'],
                            'nationality' => $post['nationality']
                        ]]
                    );
                } else {
                    if ($pickAreaData->status != 'OK') {
                        $form->get('pickup_area')->setMessages([$this->pickupAreaMsg]);
                    }if ($dropAreaData->status != 'OK') {
                        $form->get('drop_area')->setMessages([$this->dropAreaMsg]);
                    }if ($pickupAddressData->status != 'OK') {
                        $form->get('pickup_address')->setMessages([$this->pickupAddressMsg]);
                    }
                }
            }
        }

        //This is for Tarrif for Outstation Booking
        $vehicleTariff = [
            "0" => [
                "vehicle_type_packages" => [
                    'vehicle_type' => 'Economy',
                    'vehicle_image' => '/images/economycar.png',
                    'package_name' => '4 Hrs - 40 KM',
                    'price' => '800',
                    'extra_km' => '10',
                    'extra_hr' => '100',
                    'package_id' => '1'
                ],
                "packages" => [
                    "0" => [
                        'package_name' => '8 Hrs - 80 KM',
                        'price' => '1500',
                        'extra_km' => '10',
                        'extra_hr' => '100',
                        'package_id' => '2'
                    ],
                    "1" => [
                        'package_name' => '12 Hrs - 120 KM',
                        'price' => '2000',
                        'extra_km' => '10',
                        'extra_hr' => '100',
                        'package_id' => '3'
                    ],
                ],
            ],
            "1" => [
                "vehicle_type_packages" => [
                    'vehicle_type' => 'Sedan',
                    'vehicle_image' => '/images/sedancar.png',
                    'package_name' => '4 Hrs - 40 KM',
                    'price' => '800',
                    'extra_km' => '15',
                    'extra_hr' => '100',
                    'package_id' => '1'
                ],
                "packages" => [
                    "0" => [
                        'package_name' => '8 Hrs - 8 KM',
                        'price' => '1300',
                        'extra_km' => '15',
                        'extra_hr' => '100',
                        'package_id' => '2'
                    ],
                    "1" => [
                        'package_name' => '12 Hrs - 120 KM',
                        'price' => '2400',
                        'extra_km' => '15',
                        'extra_hr' => '100',
                        'package_id' => '3'
                    ],
                ],
            ],
            "2" => [
                "vehicle_type_packages" => [
                    'vehicle_type' => 'Prime',
                    'vehicle_image' => '/images/primecar.png',
                    'package_name' => '4 Hrs - 40 KM',
                    'price' => '1000',
                    'extra_km' => '15',
                    'extra_hr' => '120',
                    'package_id' => '1'
                ],
                "packages" => [
                    "0" => [
                        'package_name' => '8 Hrs - 80 KM',
                        'price' => '1800',
                        'extra_km' => '15',
                        'extra_hr' => '120',
                        'package_id' => '2'
                    ],
                    "1" => [
                        'package_name' => '4 Hrs - 40 KM',
                        'price' => '2600',
                        'extra_km' => '15',
                        'extra_hr' => '120',
                        'package_id' => '3'
                    ],
                ],
            ],
        ];

        $viewModel = new ViewModel([
            'form' => $form,
            'vehicleTariff' => $vehicleTariff,
            'google_map_url' => $this->config()->getConfig()->google_map->url,
            'google_map_key' => $this->config()->getConfig()->google_map->key,
        ]);
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
    public function oneWayVehicleListingAction() {
        $sessionVehContainer = new Container('vehicleSearchData');
        $data = $sessionVehContainer->vehicleSearchData;
        $estimated_time = "";
        $data = [];
        $form = new OneWaySearchForm();
        $guestForm = new GuestForm();
        $data = $this->params()->fromQuery();
        $total_days = $this->calculateDays(isset($data['pickup_date']) ? $data['pickup_date'] : '', isset($data['drop_date']) ? $data['drop_date'] : '');
        $form->setData($data);
        $form->get('module_type')->setValue('');
        $form->get('master_package_type')->setValue($this->oneWayPackageType);
        if (isset($data['flight_mode']) && $data['flight_mode'] == $this->flightModeOn) {
            $form->get('flight_number')->setValue($data['flight_number']);
            $form->get('flight_time')->setValue($data['flight_time']);
            $form->get('flight_mode_selected')->setValue($this->flightModeOn);
        }

        if (isset($data['flight_mode']) && $data['flight_mode'] == $this->flightModeOff) {
            $form->get('flight_number')->setValue('');
            $form->get('flight_time')->setValue('');
            $form->get('flight_mode_selected')->setValue($this->flightModeOff);
        }
        $currency_id = 1;
        $data['currency_id']= $currency_id;
        $request = $this->getRequest();
        if ($request->isPost()) {
            $data = "";
            $data = $request->getPost()->toArray();
            $currency_id = (isset($data['currency_id']) && $data['currency_id']!='')?$data['currency_id']:1;
            $form->setData($request->getPost());

            if ($data['flight_mode'] == $this->flightModeOn) {
                $form->getInputFilter()->get('flight_number')->setRequired(true);
                $form->getInputFilter()->get('flight_time')->setRequired(true);
                $form->get('flight_mode_selected')->setValue($this->flightModeOn);
            }

            if ($data['flight_mode'] == $this->flightModeOff) {
                $form->getInputFilter()->get('flight_number')->setRequired(false);
                $form->getInputFilter()->get('flight_time')->setRequired(false);
                $form->get('flight_number')->setValue('');
                $form->get('flight_time')->setValue('');
                $form->get('flight_mode_selected')->setValue($this->flightModeOff);
            }

            if ($form->isValid()) {

                $pickAreaData = $this->fetchGoogleApiData($data['pickup_city']);
                $pickAreaData = json_decode($pickAreaData);

                $dropAreaData = $this->fetchGoogleApiData($data['drop_city']);
                $dropAreaData = json_decode($dropAreaData);

                $pickupAddressData = $this->fetchGoogleApiData($data['pickup_address']);
                $pickupAddressData = Json::decode($pickupAddressData);

                if ($pickAreaData->status == 'OK' && $dropAreaData->status == 'OK' && $pickupAddressData->status == 'OK') {

                    $pickAreaLat = $pickAreaData->results[0]->geometry->location->lat;
                    $pickAreaLng = $pickAreaData->results[0]->geometry->location->lng;

                    $dropAreaLat = $dropAreaData->results[0]->geometry->location->lat;
                    $dropAreaLng = $dropAreaData->results[0]->geometry->location->lng;

                    $dataDistance = $this->fetchGoogleApiDistance($pickAreaLat, $pickAreaLng, $dropAreaLat, $dropAreaLng);
                    $res = json_decode($dataDistance);
                    if ($res->status == 'OK') {
                        $res = $res->routes[0];
                        $distance = round((($res->legs[0]->distance->value) / 1000), 1);
                        $data['distance'] = round($distance);
                        $data['duration'] = $res->legs[0]->duration->text;
                        $estimated_time = $res->legs[0]->duration->value;
                    }

                    $dropTime = strtotime("+" . $data['duration'], strtotime($data['pickup_date'] . ' ' . $data['pickup_time']));
                    $data['drop_time'] = date('d-m-Y H:i:s', $dropTime);
                    $drop = explode(' ', $data['drop_time']);
                    $data['drop_time'] = $drop[1];
                    $form->get('drop_date')->setValue($drop[0]);
                    $form->get('drop_time')->setValue($drop[1]);
                    $total_days = $this->calculateDays($data['pickup_date'], $data['drop_date']);
                    $cityDistance = $this->getCityDistance($data['pickup_city'], $data['drop_city']);
                    if ($cityDistance > $data['distance']) {
                        $data['distance'] = $cityDistance;
                    }
                } else {
                    if ($pickAreaData->status != 'OK') {
                        $form->get('pickup_city')->setMessages([$this->pickupAreaMsg]);
                    }if ($dropAreaData->status != 'OK') {
                        $form->get('drop_city')->setMessages([$this->dropAreaMsg]);
                    }if ($pickupAddressData->status != 'OK') {
                        $form->get('pickup_address')->setMessages([$this->pickupAddressMsg]);
                    }
                }
                $sessionVehContainer = new Container('vehicleSearchData');
                unset($sessionVehContainer->vehicleSearchData);
                $sessionVehContainer->vehicleSearchData = $data;
            }
            if ($request->getPost()['form_type'] == "guest_form") {
                $result = [];
                if ($request->isXmlHttpRequest()) {
                    $guestForm->setData($request->getPost());
                    $postGuest = $request->getPost()->toArray();
                    if ($postGuest['gst'] == "1") {
                        $guestForm->getInputFilter()->get('gst_registration_number')->setRequired(true);
                        $guestForm->getInputFilter()->get('gst_registered_company_name')->setRequired(true);
                    }
                    if ($guestForm->isValid()) {
                        $result = array('status' => 'success', 'form_type' => $this->onWayType);
                        $view = new JsonModel($result);
                        return $view;
                    } else {
                        $result = array('status' => 'error', 'msg' => $guestForm->getMessages());
                        $view = new JsonModel($result);
                        return $view;
                    }
                }
            }
        }

        $sessionVehContainer = new Container('vehicleSearchData');
        unset($sessionVehContainer->vehicleSearchData);
        $sessionVehContainer->vehicleSearchData = $data;

        $searchvehicleResp = $this->fetchFareDetails($data['pickcity_id'], $data['master_package_type'], date('H:i:s', strtotime($data['pickup_time'])), isset($data['distance']) ? $data['distance'] : 0, isset($data['duration']) ? $data['duration'] : 0, $estimated_time, $total_days, '', $data['adults'], $data['childs'], $data['luggages'],$data['pickup_date'],$currency_id);
        //Debug::dump($vehicleList); exit;
         $vehicleList        =  $searchvehicleResp['response'];
        $leftside_filter_Arr =  $searchvehicleResp['filter_data'];
        $vehicleType = $this->forward()->dispatch(IndexController::class, array('action' => 'getVehicleType'));
        $fuelType = $this->forward()->dispatch(IndexController::class, array('action' => 'getFuelType'));
        $currencyList = $this->forward()->dispatch(IndexController::class, array('action' => 'getCurrencyList'));
        $viewModel = new ViewModel([
            'data' => $data,
            'form' => $form,
            'vehicleList' => $vehicleList,
            'vehicle_type' => $vehicleType,
            'fuel_type' => $fuelType,
            'currency_list' => $currencyList,
            'guestForm' => $guestForm,
            'outstation_type' => 'one-way',
            'google_map_url' => $this->config()->getConfig()->google_map->url,
            'google_map_key' => $this->config()->getConfig()->google_map->key,
            'filter_Arr' => $leftside_filter_Arr
        ]);
        return $viewModel;
    }

    public function continueSubmitAction() {
        $result = [];
        $result = ['status' => 'success'];
        $view = new JsonModel($result);
        return $view;
    }

    /**
     *
     * @return ViewModel
     */
    public function oneWayFilteredVehicleListingAction() {
        $packageId = '1';
        $vehicleList = [
            "0" => [
                "vehicle_id" => 1,
                "vehicle_type" => "Economy",
                "vehicle_capacity" => 2,
                "vehicle_baggage" => 2,
                "vehicle_ignition_type" => "AC",
                "vehicle_duration" => "4h 5m",
                "approx_distance" => "120",
                "base_fare" => "500",
                "per_km_price" => "10",
                "min_distance" => "5",
                "running_amt" => "550",
                "peak_time_price" => "50",
                "night_charge" => "50",
                "extra_charge" => "50",
                "tax_percentage" => "18",
                "tax_price" => "200",
                "total_price" => "1500",
            ],
            "1" => [
                "vehicle_id" => 2,
                "vehicle_type" => "Sedan",
                "vehicle_capacity" => 3,
                "vehicle_baggage" => 4,
                "vehicle_ignition_type" => "AC",
                "vehicle_duration" => "5h 5m",
                "approx_distance" => "150",
                "base_fare" => "700",
                "per_km_price" => "15",
                "min_distance" => "10",
                "running_amt" => "850",
                "peak_time_price" => "50",
                "night_charge" => "50",
                "extra_charge" => "50",
                "tax_percentage" => "18",
                "tax_price" => "500",
                "total_price" => "1800",
            ],
            "2" => [
                "vehicle_id" => 3,
                "vehicle_type" => "Prime",
                "vehicle_capacity" => 4,
                "vehicle_baggage" => 5,
                "vehicle_ignition_type" => "NO-AC",
                "vehicle_duration" => "6h 5m",
                "approx_distance" => "180",
                "base_fare" => "800",
                "per_km_price" => "20",
                "min_distance" => "15",
                "running_amt" => "1100",
                "peak_time_price" => "50",
                "night_charge" => "50",
                "extra_charge" => "50",
                "tax_percentage" => "18",
                "tax_price" => "800",
                "total_price" => "2000",
            ]
        ];

        $view = new ViewModel([
            'vehicleList' => $vehicleList,
        ]);
        $view->setTerminal(true);
        return $view;
    }

    /**
     *
     * @return ViewModel
     */
    public function onewayTravellerAction() {
        $sessionUser = new Container('userlogin');
        $userData = $sessionUser->userData;
        $userTypeId = $userData['user_type_id'];
        $userId  = $userData['user_id'];
        
        $sessionContainer = new Container('vehicle');
        $paymentData = $this->getRequest()->getPost();
        $sessionContainer->vehicleData = $paymentData;
        
        $sessionContainer1 = new Container('vehiclePayData');
        $payData = $sessionContainer1->vehiclePaymentData;
        $vehcilePaymentData = $payData[$paymentData['vehicle_id']];
        
        //echo '<pre>';print_r($paymentData);die();
        $currencyType = $paymentData['currency_type'];
        $currData = $this->outstationModel->getCurrencyDetails($currencyType);
        $currIcon = $currData['fa_icon'];
        
        
        $company_details = $this->outstationModel->getCompanyDetail($userId);
        $company_logo    = (isset($company_details['company_logo']))?$company_details['company_logo']:'';        
        if($company_logo){            
            $companyLogoPath = $this->config()->getConfig()->base_url->b2burl."/" . $userId . "/" . $company_logo;
        }
        
        $holdBookingUser = $this->config()->getConfig()->holdBookingUserAccess;
        $holdBookingUserArr = $holdBookingUser->toArray();
        $userCanHoldBooking =false;
        if (in_array($userTypeId, $holdBookingUserArr)){
            $userCanHoldBooking = true;
        }
        
        $creditBalance = $this->outstationModel->checkCreditLimit($userId);   // Get User Credit Balance //  
        
        $recentData = [
            'user_id'=>$userData['user_id'],
            'ip'=>$_SERVER['REMOTE_ADDR'],
            'booking_stage'=>$this->config()->getConfig()->bookingSteps->step2,
            'booking_data'=>$paymentData
        ];
        $this->CommonModel->addRecentViewedItems($recentData);
        
        $form = new TravellerForm();
        $form->get('first_name')->setValue($userData['first_name']);
        $form->get('first_name')->setAttribute('readonly', 'true');
        $form->get('last_name')->setValue($userData['last_name']);
        $form->get('last_name')->setAttribute('readonly', 'true');
        $form->get('mobile')->setValue($userData['mobile']);
        $form->get('mobile')->setAttribute('readonly', 'true');
        $form->get('alt_mobile_number')->setValue($userData['alternate_mobile']);
        $form->get('alt_mobile_number')->setAttribute('readonly', 'true');
        $form->get('email')->setValue($userData['email']);
        $form->get('email')->setAttribute('readonly', 'true');
        $form->get('nationality')->setValue($paymentData['nationality']);
        $form->get('agree_terms')->setValue(1);
        $viewModel = new ViewModel([
            'form' => $form,
            'paymentData' => $paymentData,
            'vehcilePaymentData' => $vehcilePaymentData,
            'currIcon' => $currIcon,
            'captchaKey' => $this->config()->getConfig()->googleCaptcha->siteKey,
            'userCanHoldBooking'=>$userCanHoldBooking,
            'company_logo' =>  (isset($companyLogoPath))?$companyLogoPath:'',
            'creditBalance' =>  $creditBalance
        ]);
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
   /* public function oneWaytravellerSaveOldAction() {
        $sessionContainer = new Container('vehicle');
        $paymentData = $sessionContainer->vehicleData;

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

        $viewModel = new ViewModel([
            'form' => $form,
            'paymentData' => $paymentData
        ]);
        $viewModel->setTemplate('outstation/index/one-way-traveller.phtml');
        return $viewModel;
    }*/

    /**
     *
     * @return ViewModel
     */
    public function oneWayTravellerSaveAction() {
        $finalData = "";
        $recaptcha_error = '';
        $sessionUser = new Container('userlogin');
        $userData = $sessionUser->userData;
        $userId  = $userData['user_id'];
        $userTypeId = $userData['user_type_id'];
        if (!empty($userData)) {
            $guest_id = $userData['user_id'];
        } else {
            $guest_id = "";
        }

        $sessionContainer = new Container('vehicle');
        $paymentData = $sessionContainer->vehicleData;
        unset($sessionContainer->booking_id);
         
        $currencyType = $paymentData['currency_type'];
        $currData = $this->outstationModel->getCurrencyDetails($currencyType);
        $currIcon = $currData['fa_icon'];
        //echo '<pre>';print_r($paymentData);die();
        $sessionContainer1 = new Container('vehiclePayData');
        $payData = $sessionContainer1->vehiclePaymentData;
        $vehcilePaymentData = $payData[$paymentData['vehicle_id']];
        $vehcilePaymentData = array_filter($vehcilePaymentData);
        //echo '<pre>';print_r($vehcilePaymentData);die();
        //Debug::dump($paymentData); exit;
        //////////// Session Data /////////////////

        /*if ($paymentData['local_pickup'] == 2) {
            $getDate = $this->getDate($paymentData['local_pickup'], $paymentData['pickup_date']);
            $getTime = $this->getTime($paymentData['local_pickup'], $paymentData['pickup_time']);
            $paymentData['pickup_date'] = date("Y-m-d", strtotime($getDate));
            $paymentData['pickup_time'] = $getTime;
        } else if ($paymentData['local_pickup'] == 3) {
            $getTime = $this->getTime($paymentData['local_pickup'], $paymentData['pickup_time']);
            $paymentData['pickup_time'] = $getTime;
        }*/

        $paymentData['pickup_date'] = date("Y-m-d", strtotime($paymentData['pickup_date']));
        $paymentData['pickup_city'] = $paymentData['pickcity_id'];
        $paymentData['drop_city'] = $paymentData['dropcity_id'];

        $pickAreaData = $this->fetchGoogleApiData($paymentData['pickup_address']);
        $pickAreaData = Json::decode($pickAreaData);
        //Debug::dump($pickAreaData); exit;

        $pickAreaLat = $pickAreaData->results[0]->geometry->location->lat;
        $pickAreaLng = $pickAreaData->results[0]->geometry->location->lng;
        $pickUpZone = isset($pickAreaData->results[0]->address_components[5]->long_name) ? $pickAreaData->results[0]->address_components[5]->long_name : '';


        $data = $this->getStateCountry($paymentData['pickcity_id']);
        $data1 = $this->getStateCountry($paymentData['dropcity_id']);

        $dropAreaData = $this->fetchGoogleApiData($paymentData['drop_city']);
        $dropAreaData = json_decode($dropAreaData);
        //Debug::dump($dropAreaData); exit;


        $dropAreaLat = $dropAreaData->results[0]->geometry->location->lat;
        $dropAreaLng = $dropAreaData->results[0]->geometry->location->lng;
        $dropZone = $dropAreaData->results[0]->address_components[5]->long_name;
        //$dropTime = strtotime("+" . $paymentData['duration'], strtotime($paymentData['pickup_date'] . ' ' . $paymentData['pickup_time']));
        //$dropDate = date('Y-m-d', $dropTime);
        //$dropTime = date('H:i:s', $dropTime);

        $paymentData['pickup_latitude'] = $pickAreaLat;
        $paymentData['pickup_longitude'] = $pickAreaLng;
        $paymentData['pickup_zone'] = $pickUpZone;
        $paymentData['pickup_landmark'] = '';
        $paymentData['pickup_country'] = $data['response'][0]['country_id'];
        $paymentData['pickup_state'] = $data['response'][0]['state_id'];
        $paymentData['drop_date'] = $paymentData['drop_date'];
        $paymentData['drop_time'] = $paymentData['drop_time'];
        $paymentData['drop_country'] = $data1['response'][0]['country_id'];
        $paymentData['drop_state'] = $data1['response'][0]['state_id'];
        $paymentData['drop_landmark'] = '';
        $paymentData['drop_latitude'] = $dropAreaLat;
        $paymentData['drop_longitude'] = $dropAreaLng;
        $paymentData['drop_zone'] = $dropZone;
        $paymentData['device_type'] = "Web";
        $paymentData['flight_number'] = '';
        $paymentData['airport'] = '';
        $paymentData['package_id'] = '';


        //exit;

        $paymentData['guest_first_name'] = $paymentData['first_name'];
        $paymentData['guest_last_name'] = $paymentData['last_name'];
        $paymentData['guest_email'] = $paymentData['email'];
        $paymentData['guest_mobile'] = $paymentData['mobile'];
        $paymentData['guest_alt_mobile'] = $paymentData['alt_mobile_no'];
        $paymentData['guest_gender'] = $paymentData['gender'];
        $paymentData = $paymentData->toArray();
        //$paymentData = array_filter($paymentData);
        //Debug::dump($paymentData); exit;
        
        $currencyType = $paymentData['currency_type'];
        $currencyData = $this->outstationModel->getCurrencyDetails($currencyType);
        $company_details = $this->outstationModel->getCompanyDetail($userId);
        $company_logo    = (isset($company_details['company_logo']))?$company_details['company_logo']:'';        
        if($company_logo){            
            $companyLogoPath = $this->config()->getConfig()->base_url->b2burl."/" . $userId . "/" . $company_logo;
        }
        
        $holdBookingUser = $this->config()->getConfig()->holdBookingUserAccess;
        $holdBookingUserArr = $holdBookingUser->toArray();
        $userCanHoldBooking =false;
        if (in_array($userTypeId, $holdBookingUserArr)){
            $userCanHoldBooking = true;
        }

        $form = new TravellerForm();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->getPost());
            $post = $request->getPost()->toArray();
            
            $creditBalance = $this->outstationModel->checkCreditLimit($userId);  
            $total_booking_price = $paymentData['total_price'];           
            $balance_error = '';
            if($post['voucher']!='' && ($creditBalance < $total_booking_price)){
                   $balance_error = 'Credit Balance is not available for create voucher'; 
            }
//            if ($post['g-recaptcha-response'] == '') {
//                $recaptcha_error = 'Please check the captcha';
            //}
            if ($form->isValid() && $balance_error=='') {
                if ($guest_id == "") {
                    $guestArray['user_type_id'] = 1;
                    $guestArray['first_name'] = $paymentData['guest_first_name'];
                    $guestArray['last_name'] = $paymentData['guest_last_name'];
                    $guestArray['mobile'] = $paymentData['guest_mobile'];
                    $guestArray['email'] = $paymentData['guest_email'];
                    $guestArray['password'] = md5($paymentData['guest_mobile']);
                    $guestArray['gender'] = $paymentData['guest_gender'];
                    $guestArray['user_grade'] = $this->config()->getConfig()->userGrade->defaultGrade;
                    $guestData = $this->getUserId($guestArray);
                    $paymentData['user_id'] =  $guestData['data']['user_id'];
                } else {
                    $paymentData['user_id'] = $guest_id;
                }

                $userArray['user_type_id'] = 2;
                $userArray['company_id'] = $this->config()->getConfig()->company->companyId;
                $userArray['first_name'] = $post['first_name'];
                $userArray['last_name'] = $post['last_name'];
                $userArray['mobile'] = $post['mobile'];
                $userArray['email'] = $post['email'];
                $userArray['password'] = md5($post['mobile']);
                //$userArray['gender'] = $post['gender'];
                $userArray['nationality'] = $this->getCountryId($paymentData['nationality']);
                $userArray['gst_no'] = $post['gst_no'];
                $userArray['alt_mobile_no'] = $post['alt_mobile_number'];
                $userArray['user_grade'] = $this->config()->getConfig()->userGrade->defaultGrade;

                if($post['book_vehicle_user']==1){
                $clientData = $this->getUserId($userArray);
                $paymentData['client_id'] = $clientData['data']['user_id'];
                } else {
                $paymentData['client_id'] = $guest_id;
                }
                $paymentData['vehicle_type_id'] = $vehcilePaymentData['vehicle_type_id'];
                //exit;
                //Debug::dump($paymentData);
                //Debug::dump($post);
                //Debug::dump($vehcilePaymentData);
                //exit;

                $finalData = [];
                $finalData = array_merge($paymentData, $post, $vehcilePaymentData);
                //$finalData = array_merge($paymentData, $post);
                //Debug::dump($finalData); exit;
                unset($sessionContainer->vehicleData);
                $sessionContainer->vehicleData = $finalData;
                
                 $recentData = [
                    'user_id'=>$userData['user_id'],
                    'ip'=>$_SERVER['REMOTE_ADDR'],
                    'booking_stage'=>$this->config()->getConfig()->bookingSteps->step3,
                    'booking_data'=>$finalData
                ];
                $this->CommonModel->addRecentViewedItems($recentData);
                
                if ($guest_id == "") {
                    $this->redirect()->toRoute('outstation', ['action' => 'login']);
                } else {
                    if($post['hold_booking']!=''){
                        $this->redirect()->toRoute('outstation', ['action' => 'hold-booking']);
                    }else{
                        $this->redirect()->toRoute('outstation', ['action' => 'checkout']);
                    }
                }
            }
        }

        //echo '<pre>';print_r($paymentData);die();

        $viewModel = new ViewModel([
            'form' => $form,
            'paymentData' => $paymentData,
            //'error' => $recaptcha_error,
            'currIcon' => $currIcon,
            'captchaKey' => $this->config()->getConfig()->googleCaptcha->siteKey,
            'balance_error' => $balance_error,            
            'vehcilePaymentData' => $vehcilePaymentData,
            'currencyData' => $currencyData,
            'userCanHoldBooking'=>$userCanHoldBooking,
            'company_logo' =>  (isset($companyLogoPath))?$companyLogoPath:''
        ]);
        $viewModel->setTemplate('outstation/index/one-way-traveller.phtml');
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
    public function loginAction() {
        $sessionContainer = new Container('vehicle');
        $paymentData = $sessionContainer->vehicleData;
        //$sessionContainer = new Container('vehicle');
        //$paymentData = $sessionContainer->oneWayvehicleData;
        //Debug::dump($paymentData);
        //echo "Mohit"; die;
        $form = new LoginForm();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->getPost());
            if ($form->isValid()) {
                $post = $request->getPost()->toArray();
                //Debug::dump($post);
                $post['password'] = md5($post['password']);
                $data = $this->userLogin($post);
                if ($data['data']['responsedata']['status'] == true) {
                    $sessionUser = new Container('userlogin');
                    $sessionUser->userData = $data['data']['responsedata'];
                    $errorMsg = "Login Successfully";
                    $this->redirect()->toRoute('outstation', ['action' => 'checkout']);
                } else {
                    $errorMsg = $data['data']['responsedata']['error'];
                }
                //Debug::dump($data);
                //exit;
            }
        }
        if (empty($errorMsg)) {
            $errorMsg = '';
        }
        $viewModel = new ViewModel([
            'form' => $form,
            'paymentData' => $paymentData,
            'errorMsg' => $errorMsg
        ]);
        $viewModel->setTemplate('outstation/index/book-now.phtml');
        return $viewModel;
    }

    public function checkoutAction() {
        $sessionItems = new Container('multivehicledata');
        $sessionContainer = new Container('vehicle');
        $paymentData = $sessionContainer->vehicleData;
        //echo '<pre>';print_r($paymentData);die();

        $sessionUser = new Container('userlogin');
        $user_id = $sessionUser->userData['user_id'];
        $login_email = $sessionUser->userData['email'];
        $login_mobile = $sessionUser->userData['mobile'];
        $walletData = $this->getWalletAmt($user_id);

        $twentyFivePercent = $paymentData['total_charge'] * 25 / 100;
        $fiftyPercent = $paymentData['total_charge'] * 50 / 100;
        $paymentData['twenty_five_percent'] = round($twentyFivePercent);
        $paymentData['fifty_percent'] = round($fiftyPercent);
        $paymentData['user_id'] = $user_id;
        //Debug::dump($paymentData);exit;

        $request = $this->getRequest();
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            if ($post['booking_amt_percentage'] == '25') {
                $post['booking_amt_paid'] = round($twentyFivePercent);
                $post['booking_amt_balance'] = $paymentData['total_charge'] - round($twentyFivePercent);
                $post['charge_type'] = 3;
            } else if ($post['booking_amt_percentage'] == '50') {
                $post['booking_amt_paid'] = round($fiftyPercent);
                $post['booking_amt_balance'] = $paymentData['total_charge'] - round($fiftyPercent);
                $post['charge_type'] = 3;
            } else {
                $post['booking_amt_paid'] = $paymentData['total_charge'];
                $post['booking_amt_balance'] = 0;
                $post['charge_type'] = 2;
            }
            //echo $post['wallet_amount'];
            if (!empty($post['wallet_amount'])) {
                //echo "Mohit";
                $walletStatus = 1;
                if ($walletData < $post['booking_amt_paid']) {
                    $walletAmt = 0;
                    $post['booking_amt_paid'] = $post['booking_amt_paid'] - $walletData;
                    $paymentData['wallet_data'] = $walletData;
                    $paymentStatus = 3;
                    $post['charge_type'] = 3;
                } else {
                    $walletAmt = $walletData - $post['booking_amt_paid'];
                    $paymentData['wallet_data'] = 0;
                    $post['charge_type'] = 3;
                    if ($walletAmt < 0) {
                        $paymentStatus = 1;
                    } else {
                        $paymentStatus = 0;
                    }
                }
            } else {
                //echo "Jain";
                $walletStatus = 0;
                $walletAmt = $walletData;
                $paymentData['wallet_data'] = 0;
                 $post['charge_type'] = 1;
                /* if ($walletAmt > $post['booking_amt_paid']) {
                  $paymentStatus = 1;
                  } else {
                  $paymentStatus = 0;
                  } */
                $paymentStatus = 1;
            }
            //echo $paymentStatus;
            //die;
            $paymentData['wallet_updated_amount'] = $walletAmt;
            $paymentData['master_package_mode_id'] = 1;
            //$paymentData['vehicle_type_id'] = $paymentData['vehicle_id'];
            $paymentData['created_date'] = date('Y-m-d H:i:s');
            $paymentData['company_id'] = $this->config()->getConfig()->company->companyId;
            $currencyType = $paymentData['currency_type'];
            $currData = $this->outstationModel->getCurrencyDetails($currencyType);
            $paymentData['currency_code'] = $currData['code'];
            $paymentData['exchange_rate'] = $currData['exchange_rate'];

            //echo $walletAmt.'<br/>';
            //echo $paymentStatus.'<br/>';
            //echo $walletStatus.'<br/>';
            //echo $post['booking_amt_paid'];
            //Debug::dump($post);
            $finalData = [];
            $finalData = array_merge($paymentData, $post);
            //Debug::dump($finalData);
            //exit;
            $this->updateLatLng($finalData);
            $finalBooking = $this->finalBookingSubmission($finalData);
            $lastInsertId = $finalBooking['data']['response']['insertId'];
            $companyInitial = $this->config()->getConfig()->company->companyInitial;
            $finalData['booking_id'] = $lastInsertId;
            //Debug::dump($finalData);
            //exit;

            unset($sessionContainer->vehicleData);
            $sessionContainer->vehicleData = $finalData;

            if (!empty($lastInsertId)) {
                 /* Update booking ref no. generate Now in booking API. - 20-june-2020
                $bookingRefNo = $this->getBookingRefNo($lastInsertId, $companyInitial);
                $updateDataArray['reference_number'] = $bookingRefNo['generated'];
                $updateDataArray['booking_id'] = $lastInsertId;
                $updated = $this->updateBookingNo($updateDataArray); */
                $bookingData = $this->outstationModel->getBookingInfoById($lastInsertId);
                $bookingRefNo = $bookingData[0]['ref'];
                $this->logStackTrackerData($finalData);
                $cityItems = $sessionItems->vehicleItems;
                //echo '<pre>';print_r($cityItems);die();
                //echo '<pre>';print_r(json_encode($finalData));die();
                if($finalData['module_type']== $this->multiCityType){
                $this->insertBookingDetails($lastInsertId, $cityItems);
                }
                //$msg_sku='booking';
                //$this->getSmsTemplate($msg_sku);
                //////////

                $smsparam = [
                    'template_name' => 'booking',
                    'mobile' => $login_mobile,
                    'user_name' => 'User',
                    'booking_ref_no' => $bookingRefNo['generated'],
                    'pickup_time' => $finalData['pickup_date'] . ' ' . $finalData['pickup_time'],
                    'estimated_price' => $finalData['total_charge']
                ];
                //echo '<pre>';print_r($smsparam);//die();
                $this->sendSMS($smsparam);

                $smsparamTraveller = [
                    'template_name' => 'booking',
                    'mobile' => $finalData['mobile'],
                    'user_name' => 'User',
                    'booking_ref_no' => $bookingRefNo['generated'],
                    'pickup_time' => $finalData['pickup_date'] . ' ' . $finalData['pickup_time'],
                    'estimated_price' => $finalData['total_charge']
                ];
                //echo '<pre>';print_r($smsparamTraveller);//die();
                $this->sendSMS($smsparamTraveller);

                $sendMailUser = [
                    'user_name' => $sessionUser->userData['first_name'],
                    //'user_email' => $sessionUser->userData['email'],
                    'user_email' => $login_email,
                    'booking_ref_no' => $bookingRefNo['generated'],
                    'pickup_time' => $finalData['pickup_date'] . ' ' . $finalData['pickup_time'],
                    'estimated_price' => $finalData['total_charge'],
                    'referral_code' => $sessionUser->userData['referral_key'],
                    'template_name' => 'booking',
                    'subject' => 'Booking Message'
                ];
                $this->sendMail($sendMailUser);

                if ($finalData['send_email'] == 1) {
                    $sendMailTraveller = [
                        'user_name' => $finalData['first_name'],
                        'user_email' => $finalData['email'],
                        //'user_email' => 'php@hello42cab.com',
                        'booking_ref_no' => $bookingRefNo['generated'],
                        'pickup_time' => $finalData['pickup_date'] . ' ' . $finalData['pickup_time'],
                        'estimated_price' => $finalData['total_charge'],
                        'referral_code' => $sessionUser->userData['referral_key'],
                        'template_name' => 'booking',
                        'subject' => 'Booking Message'
                    ];
                    $this->sendMail($sendMailTraveller);
                }

                //////////


                $this->checkPayment($walletStatus, $paymentStatus, $finalData, $bookingRefNo, $lastInsertId);
                //$atomPayment = $this->atomPaymentGateway($finalData, $bookingRefNo['generated']);
            }
            //Debug::dump($updated);
            //exit;
        }

        $viewModel = new ViewModel([
            'paymentData' => $paymentData,
            'walletData' => $walletData,
        ]);
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
    public function roundTripAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $userId = $loginData['user_id'];
        $cityData = $this->getRequest()->getQuery()->toArray();
        $form = new RoundTripSearchForm();

        $sessionCityContainer = new Container('vehicleCityData');
        //get request object
        if(!empty($sessionCityContainer->pickup_city)){
            $pickupCity    =   $sessionCityContainer->pickup_city;
            $cityId        =   $sessionCityContainer->city_id;
            $form->get('pickup_city')->setValue($pickupCity);
            $form->get('drop_city1')->setValue($pickupCity);
            $form->get('pickcity_id')->setValue($cityId);
            $boundData = $this->getLatLngData($pickupCity);
            //echo '<pre>';print_r($boundData);die();
            if ($boundData['status'] == 1) {
                $form->get('city_latitude')->setValue($boundData['data']['lat']);
                $form->get('city_longitude')->setValue($boundData['data']['lng']);
                $form->get('city_northeast_latitude')->setValue($boundData['data']['north_east_lat']);
                $form->get('city_northeast_longitude')->setValue($boundData['data']['north_east_lng']);
                $form->get('city_southwest_latitude')->setValue($boundData['data']['south_west_lat']);
                $form->get('city_southwest_longitude')->setValue($boundData['data']['south_west_lng']);
            }
            $sessionVehContainer = new Container('vehicleSearchData');
            $data = $sessionVehContainer->vehicleSearchData;
            if($data!=""){
                $form->setData($data);
            }
        }
        
        if (!empty($cityData)) {
            //$sessionVehContainer = new Container('vehicleSearchData');
            //unset($sessionVehContainer->vehicleSearchData);

            $sessionCityContainer->pickup_city = $cityData['city'];
            $sessionCityContainer->city_id = $cityData['city_id'];
            if(!empty($cityData['drop_city'])){
            $sessionCityContainer->drop_city = $cityData['drop_city'];
            $sessionCityContainer->dropcity_id = $cityData['drop_city_id'];
            }
            $form->get('pickup_city')->setValue($cityData['city']);
            $form->get('pickcity_id')->setValue($cityData['city_id']);
            $form->get('drop_city1')->setValue($cityData['city']);
            $form->get('pickup_date')->setValue(isset($cityData['start_date'])?$cityData['start_date']:'');
            $form->get('pickup_time')->setValue(isset($cityData['start_time'])?$cityData['start_time']:'');
            if(!empty($cityData['drop_city'])){
            $form->get('drop_city')->setValue($cityData['drop_city']);
            $form->get('dropcity_id')->setValue($cityData['drop_city_id']);
            }
            $city_name = $cityData['city'];
            $boundData = $this->getLatLngData($city_name);
            //echo '<pre>';print_r($boundData);die();
            if ($boundData['status'] == 1) {
                $form->get('city_latitude')->setValue($boundData['data']['lat']);
                $form->get('city_longitude')->setValue($boundData['data']['lng']);
                $form->get('city_northeast_latitude')->setValue($boundData['data']['north_east_lat']);
                $form->get('city_northeast_longitude')->setValue($boundData['data']['north_east_lng']);
                $form->get('city_southwest_latitude')->setValue($boundData['data']['south_west_lat']);
                $form->get('city_southwest_longitude')->setValue($boundData['data']['south_west_lng']);
            }

        }

        $sessionVehContainer = new Container('vehicleSearchData');
        $data = $sessionVehContainer->vehicleSearchData;
        //echo '<pre>';print_r($data);die();
        if($data!=""){
        if(isset($data['city_id']) && !empty($data['city_id']))
        {
            $form->get('pickcity_id')->setValue($data['city_id']);
        }
        if(isset($data['pickcity_id']) && !empty($data['pickcity_id']))
        {
            $form->get('pickcity_id')->setValue($data['pickcity_id']);
        }
        if(isset($data['drop_city']) && !empty($data['drop_city']))
        {
            $form->get('pickup_city1')->setValue($data['drop_city']);
        }
        $form->setData($data);
        $form->get('drop_city1')->setValue(isset($data['pickup_city'])?$data['pickup_city']:'');        
        }

        $form->get('module_type')->setValue($this->roundTripType);
        $form->get('master_package_type')->setValue($this->masterPackageType);
        $request = $this->getRequest();
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $form->setData($request->getPost());
            if ($post['flight_mode'] == $this->flightModeOn) {
                $form->getInputFilter()->get('flight_number')->setRequired(true);
                $form->getInputFilter()->get('flight_time')->setRequired(true);
                $form->get('flight_mode_selected')->setValue($this->flightModeOn);
            }

            if ($post['flight_mode'] == $this->flightModeOff) {
                $form->getInputFilter()->get('flight_number')->setRequired(false);
                $form->getInputFilter()->get('flight_time')->setRequired(false);
                $form->get('flight_mode_selected')->setValue($this->flightModeOff);
            }

            if ($form->isValid()) {
                $pickAreaData = $this->fetchGoogleApiData($post['pickup_city']);
                $pickAreaData = json_decode($pickAreaData);


                $dropAreaData = $this->fetchGoogleApiData($post['drop_city']);
                $dropAreaData = json_decode($dropAreaData);

                $pickupAddressData = $this->fetchGoogleApiData($post['pickup_address']);
                $pickupAddressData = Json::decode($pickupAddressData);

                if ($pickAreaData->status == 'OK' && $dropAreaData->status == 'OK' && $pickupAddressData->status == 'OK') {

                    $pickAreaLat = $pickAreaData->results[0]->geometry->location->lat;
                    $pickAreaLng = $pickAreaData->results[0]->geometry->location->lng;

                    $dropAreaLat = $dropAreaData->results[0]->geometry->location->lat;
                    $dropAreaLng = $dropAreaData->results[0]->geometry->location->lng;

                    $dataDistance = $this->fetchGoogleApiDistance($pickAreaLat, $pickAreaLng, $dropAreaLat, $dropAreaLng);
                    $res = json_decode($dataDistance);
                    if ($res->status == 'OK') {
                        $res = $res->routes[0];
                        $distance = round((($res->legs[0]->distance->value) / 1000), 1);
                        $distance = round($distance);
                        $duration = $res->legs[0]->duration->text;
                    }
                    $dropTime = strtotime("+" . $duration, strtotime($post['pickup_date'] . ' ' . $post['pickup_time']));
                    $dropTime = date('Y-m-d H:i:s', $dropTime);

                    $drop = explode(' ', $dropTime);
                    $cityDistance = $this->getCityDistance($post['pickup_city'], $post['drop_city']);
                    if ($cityDistance > $distance) {
                        $distance = $cityDistance;
                    }
                    //$distance=$distance*2;
                    $returnDropTime = strtotime("+" . $duration, strtotime($post['return_date'] . ' ' . $post['return_time']));
                    $returnDropTime = date('Y-m-d H:i:s', $returnDropTime);

                    $return = explode(' ', $returnDropTime);
                    $sessionVehContainer = new Container('vehicleSearchData');
                    unset($sessionVehContainer->vehicleSearchData);
                    $sessionVehContainer->vehicleSearchData = $post;
                    
                    $recentData = [
                        'user_id'=>$userId,
                        'ip'=>$_SERVER['REMOTE_ADDR'],
                        'booking_stage'=>$this->config()->getConfig()->bookingSteps->step1,
                        'booking_data'=>$post
                    ];
                    $this->CommonModel->addRecentViewedItems($recentData);
                    
                    $this->redirect()->toRoute('outstation', [
                        'action' => 'round-trip-vehicle-listing'
                            ], ['query' => [
                            'pickup_city' => $post['pickup_city'],
                            'drop_city' => $post['drop_city'],
                            'pickup_city1' => $post['pickup_city1'],
                            'drop_city1' => $post['drop_city1'],
                            'pickup_date' => $post['pickup_date'],
                            'pickup_time' => $post['pickup_time'],
                            'return_date' => $post['return_date'],
                            'return_time' => $post['return_time'],
                            'number_of_days' => $post['number_of_days'],
                            'flight_mode' => $post['flight_mode'],
                            'flight_number' => $post['flight_number'],
                            'flight_time' => $post['flight_time'],
                            'pickup_address' => $post['pickup_address'],
                            'adults' => $post['adults'],
                            'childs' => $post['childs'],
                            'luggages' => $post['luggages'],
                            'no_of_vehicles' => $post['no_of_vehicles'],
                            'agree_terms' => $post['agree_terms'],
                            'distance' => $distance,
                            'duration' => $duration,
                            'drop_date' => $drop[0],
                            'drop_time' => $drop[1],
                            'return_drop_date' => $return[0],
                            'return_drop_time' => $return[1],
                            'pickcity_id' => $post['pickcity_id'],
                            'dropcity_id' => $post['dropcity_id'],
                            'master_package_type' => $post['master_package_type'],
                            'module_type' => $post['module_type'],
                            'city_latitude' => $post['city_latitude'],
                            'city_longitude' => $post['city_longitude'],
                            'city_northeast_latitude' => $post['city_northeast_latitude'],
                            'city_northeast_longitude' => $post['city_northeast_longitude'],
                            'city_southwest_latitude' => $post['city_southwest_latitude'],
                            'city_southwest_longitude' => $post['city_southwest_longitude'],
                            'nationality' => $post['nationality']
                        ]]
                    );
                } else {
                    if ($pickAreaData->status != 'OK') {
                        $form->get('pickup_city')->setMessages([$this->pickupAreaMsg]);
                    }if ($dropAreaData->status != 'OK') {
                        $form->get('drop_city')->setMessages([$this->dropAreaMsg]);
                    }if ($pickupAddressData->status != 'OK') {
                        $form->get('pickup_address')->setMessages([$this->pickupAddressMsg]);
                    }
                }
            }
        }
        //This is for Tarrif for Outstation Booking
        $vehicleTariff = [
            "0" => [
                "vehicle_type_packages" => [
                    'vehicle_type' => 'Economy',
                    'vehicle_image' => '/images/economycar.png',
                    'package_name' => '4 Hrs - 40 KM',
                    'price' => '800',
                    'extra_km' => '10',
                    'extra_hr' => '100',
                    'package_id' => '1'
                ],
                "packages" => [
                    "0" => [
                        'package_name' => '8 Hrs - 80 KM',
                        'price' => '1500',
                        'extra_km' => '10',
                        'extra_hr' => '100',
                        'package_id' => '2'
                    ],
                    "1" => [
                        'package_name' => '12 Hrs - 120 KM',
                        'price' => '2000',
                        'extra_km' => '10',
                        'extra_hr' => '100',
                        'package_id' => '3'
                    ],
                ],
            ],
            "1" => [
                "vehicle_type_packages" => [
                    'vehicle_type' => 'Sedan',
                    'vehicle_image' => '/images/sedancar.png',
                    'package_name' => '4 Hrs - 40 KM',
                    'price' => '800',
                    'extra_km' => '15',
                    'extra_hr' => '100',
                    'package_id' => '1'
                ],
                "packages" => [
                    "0" => [
                        'package_name' => '8 Hrs - 8 KM',
                        'price' => '1300',
                        'extra_km' => '15',
                        'extra_hr' => '100',
                        'package_id' => '2'
                    ],
                    "1" => [
                        'package_name' => '12 Hrs - 120 KM',
                        'price' => '2400',
                        'extra_km' => '15',
                        'extra_hr' => '100',
                        'package_id' => '3'
                    ],
                ],
            ],
            "2" => [
                "vehicle_type_packages" => [
                    'vehicle_type' => 'Prime',
                    'vehicle_image' => '/images/primecar.png',
                    'package_name' => '4 Hrs - 40 KM',
                    'price' => '1000',
                    'extra_km' => '15',
                    'extra_hr' => '120',
                    'package_id' => '1'
                ],
                "packages" => [
                    "0" => [
                        'package_name' => '8 Hrs - 80 KM',
                        'price' => '1800',
                        'extra_km' => '15',
                        'extra_hr' => '120',
                        'package_id' => '2'
                    ],
                    "1" => [
                        'package_name' => '4 Hrs - 40 KM',
                        'price' => '2600',
                        'extra_km' => '15',
                        'extra_hr' => '120',
                        'package_id' => '3'
                    ],
                ],
            ],
        ];

        $viewModel = new ViewModel([
            'vehicleTariff' => $vehicleTariff,
            'form' => $form,
            'google_map_url' => $this->config()->getConfig()->google_map->url,
            'google_map_key' => $this->config()->getConfig()->google_map->key,
        ]);
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
    public function roundTripVehicleListingAction() {
        $sessionVehContainer = new Container('vehicleSearchData');
        $data = $sessionVehContainer->vehicleSearchData;
        $estimated_time = "";
        $sessionContainer = new Container('roundTrip');
        $data = [];
        $form = new RoundTripSearchForm();
        $guestForm = new GuestForm();
        $data = $this->params()->fromQuery();
        //echo '<pre>';print_r($data);die();
        $sessionContainer->vehicleSearchData = $data;
        //Debug::dump($sessionContainer->vehicleSearchData);
        $form->setData($data);
        $form->get('module_type')->setValue($this->roundTripType);
        $form->get('master_package_type')->setValue($this->masterPackageType);
        if ($data['flight_mode'] == $this->flightModeOn) {
            $form->get('flight_number')->setValue($data['flight_number']);
            $form->get('flight_time')->setValue($data['flight_time']);
            $form->get('flight_mode_selected')->setValue($this->flightModeOn);
        }

        if ($data['flight_mode'] == $this->flightModeOff) {
            $form->get('flight_number')->setValue('');
            $form->get('flight_time')->setValue('');
            $form->get('flight_mode_selected')->setValue($this->flightModeOff);
        }
        $currency_id = 1;
        $data['currency_id']= $currency_id;
        $request = $this->getRequest();
        if ($request->isPost()) {
            $data = "";
            $data = $request->getPost()->toArray();

            $form->setData($request->getPost());
            $currency_id = (isset($data['currency_id']) && $data['currency_id']!='')?$data['currency_id']:1;
            //Debug::dump($data);exit;
            $pickAreaData = $this->fetchGoogleApiData($data['pickup_city']);
            $pickAreaData = json_decode($pickAreaData);
            $pickAreaLat = $pickAreaData->results[0]->geometry->location->lat;
            $pickAreaLng = $pickAreaData->results[0]->geometry->location->lng;

            $dropAreaData = $this->fetchGoogleApiData($data['drop_city']);
            $dropAreaData = json_decode($dropAreaData);
            $dropAreaLat = $dropAreaData->results[0]->geometry->location->lat;
            $dropAreaLng = $dropAreaData->results[0]->geometry->location->lng;

            $dataDistance = $this->fetchGoogleApiDistance($pickAreaLat, $pickAreaLng, $dropAreaLat, $dropAreaLng);
            $res = json_decode($dataDistance);
            if ($res->status == 'OK') {
                $res = $res->routes[0];
                $distance = round((($res->legs[0]->distance->value) / 1000), 1);
                $data['distance'] = round($distance);
                $data['duration'] = $res->legs[0]->duration->text;
                $estimated_time = $res->legs[0]->duration->value;
            }

            $dropTime = strtotime("+" . $data['duration'], strtotime($data['pickup_date'] . ' ' . $data['pickup_time']));
            $data['drop_time'] = date('Y-m-d H:i:s', $dropTime);

            $drop = explode(' ', $data['drop_time']);
            $data['drop_time'] = $drop[1];
            $form->get('drop_date')->setValue($drop[0]);
            $form->get('drop_time')->setValue($drop[1]);

            $returnDropTime = strtotime("+" . $data['duration'], strtotime($data['return_date'] . ' ' . $data['return_time']));
            $data['return_drop_time'] = date('Y-m-d H:i:s', $returnDropTime);

            $cityDistance = $this->getCityDistance($data['pickup_city'], $data['drop_city']);
            if ($cityDistance > $data['distance']) {
                $data['distance'] = $cityDistance;
            }

            //$data['distance']=$data['distance']*2;

            if ($data['flight_mode'] == $this->flightModeOn) {
                $form->getInputFilter()->get('flight_number')->setRequired(true);
                $form->getInputFilter()->get('flight_time')->setRequired(true);
                $form->get('flight_mode_selected')->setValue($this->flightModeOn);
            }

            if ($data['flight_mode'] == $this->flightModeOff) {
                $form->getInputFilter()->get('flight_number')->setRequired(false);
                $form->getInputFilter()->get('flight_time')->setRequired(false);
                $form->get('flight_number')->setValue('');
                $form->get('flight_time')->setValue('');
                $form->get('flight_mode_selected')->setValue($this->flightModeOff);
            }

            if ($form->isValid()) {
                $sessionContainer->vehicleSearchData = $data;
                //Debug::dump($sessionContainer->vehicleSearchData);
                //$data = $request->getPost()->toArray();
                //$form->get('pickup_date')->setValue($data['pickup_date']);
                //$form->get('pickup_time')->setValue($data['pickup_time']);
                $sessionVehContainer = new Container('vehicleSearchData');
                unset($sessionVehContainer->vehicleSearchData);
                $sessionVehContainer->vehicleSearchData = $data;

            }
            /* if ($request->getPost()['form_type'] == "guest_form") {
              $result = [];
              if ($request->isXmlHttpRequest()) {
              $guestForm->setData($request->getPost());
              $postGuest = $request->getPost()->toArray();
              if ($postGuest['gst'] == "1") {
              $guestForm->getInputFilter()->get('gst_registration_number')->setRequired(true);
              $guestForm->getInputFilter()->get('gst_registered_company_name')->setRequired(true);
              }
              if ($guestForm->isValid()) {
              $sessionContainer->vehicleSearchData = $data;
              $sessionContainer->guestFormData = $postGuest;
              $result = array('status' => 'success', 'form_type' => $this->roundTripType);
              $view = new JsonModel($result);
              return $view;
              } else {
              $result = array('status' => 'error', 'msg' => $guestForm->getMessages());
              $view = new JsonModel($result);
              return $view;
              }
              }
              } */
        }

        $sessionVehContainer = new Container('vehicleSearchData');
        unset($sessionVehContainer->vehicleSearchData);
        $sessionVehContainer->vehicleSearchData = $data;

        $searchvehicleResp = $this->fetchFareDetails($data['pickcity_id'], $data['master_package_type'], date('H:i:s', strtotime($data['pickup_time'])), isset($data['distance']) ? $data['distance'] : 0 * 2, isset($data['duration']) ? $data['duration'] : 0, $estimated_time, $data['number_of_days'], $this->roundTripType, $data['adults'], $data['childs'], $data['luggages'],$data['pickup_date'],$currency_id);
        //echo '<pre>';print_r($vehicleList);die();
        //$sessionContainer->vehicleListingData = $vehicleList;
        $vehicleList         =  $searchvehicleResp['response'];
        $leftside_filter_Arr =  $searchvehicleResp['filter_data'];
        $vehicleType = $this->forward()->dispatch(IndexController::class, array('action' => 'getVehicleType'));
        $fuelType = $this->forward()->dispatch(IndexController::class, array('action' => 'getFuelType'));
        $currencyList = $this->forward()->dispatch(IndexController::class, array('action' => 'getCurrencyList'));
        $viewModel = new ViewModel([
            'data' => $data,
            'form' => $form,
            'vehicleList' => $vehicleList,
            'vehicle_type' => $vehicleType,
            'fuel_type' => $fuelType,
            'currency_list' => $currencyList,
            'guestForm' => $guestForm,
            'outstation_type' => 'one-way',
            'google_map_url' => $this->config()->getConfig()->google_map->url,
            'google_map_key' => $this->config()->getConfig()->google_map->key,
            'filter_Arr' => $leftside_filter_Arr
        ]);
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
    public function roundTripFilteredVehicleListingAction() {
        $packageId = '1';
        $vehicleList = [
            "0" => [
                "vehicle_id" => 1,
                "vehicle_type" => "Economy",
                "vehicle_capacity" => 2,
                "vehicle_baggage" => 2,
                "vehicle_ignition_type" => "AC",
                "vehicle_duration" => "4h 5m",
                "approx_distance" => "120",
                "base_fare" => "500",
                "per_km_price" => "10",
                "min_distance" => "5",
                "running_amt" => "550",
                "peak_time_price" => "50",
                "night_charge" => "50",
                "extra_charge" => "50",
                "tax_percentage" => "18",
                "total_price_before_tax" => "1300",
                "tax_price" => "200",
                "total_price" => "1500",
            ],
            "1" => [
                "vehicle_id" => 2,
                "vehicle_type" => "Sedan",
                "vehicle_capacity" => 3,
                "vehicle_baggage" => 4,
                "vehicle_ignition_type" => "AC",
                "vehicle_duration" => "5h 5m",
                "approx_distance" => "150",
                "base_fare" => "700",
                "per_km_price" => "15",
                "min_distance" => "10",
                "running_amt" => "850",
                "peak_time_price" => "50",
                "night_charge" => "50",
                "extra_charge" => "50",
                "tax_percentage" => "18",
                "total_price_before_tax" => "1500",
                "tax_price" => "500",
                "total_price" => "1800",
            ],
            "2" => [
                "vehicle_id" => 3,
                "vehicle_type" => "Prime",
                "vehicle_capacity" => 4,
                "vehicle_baggage" => 5,
                "vehicle_ignition_type" => "NO-AC",
                "vehicle_duration" => "6h 5m",
                "approx_distance" => "180",
                "base_fare" => "800",
                "per_km_price" => "20",
                "min_distance" => "15",
                "running_amt" => "1100",
                "peak_time_price" => "50",
                "night_charge" => "50",
                "extra_charge" => "50",
                "tax_percentage" => "18",
                "total_price_before_tax" => "1700",
                "tax_price" => "800",
                "total_price" => "2000",
            ]
        ];

        $view = new ViewModel([
            'vehicleList' => $vehicleList,
        ]);
        $view->setTerminal(true);
        return $view;
    }

    /**
     *
     * @return ViewModel
     */
    public function roundTripTravellerAction() {
        $sessionUser = new Container('userlogin');
        $userData = $sessionUser->userData;
        $userTypeId = $userData['user_type_id'];
        $userId  = $userData['user_id'];
        
        $sessionContainer = new Container('vehicle');
        $paymentData = $this->getRequest()->getPost();
        $sessionContainer->vehicleData = $paymentData;
        
        $sessionContainer1 = new Container('vehiclePayData');
        $payData = $sessionContainer1->vehiclePaymentData;
        $vehcilePaymentData = $payData[$paymentData['vehicle_id']];        
        
        $currencyType = $paymentData['currency_type'];
        $currData = $this->outstationModel->getCurrencyDetails($currencyType);
        $currIcon = $currData['fa_icon'];
        
        $company_details = $this->outstationModel->getCompanyDetail($userId);
        $company_logo    = (isset($company_details['company_logo']))?$company_details['company_logo']:'';        
        if($company_logo){            
            $companyLogoPath = $this->config()->getConfig()->base_url->b2burl."/" . $userId . "/" . $company_logo;
        }
        
        $holdBookingUser = $this->config()->getConfig()->holdBookingUserAccess;
        $holdBookingUserArr = $holdBookingUser->toArray();
        $userCanHoldBooking =false;
        if (in_array($userTypeId, $holdBookingUserArr)){
            $userCanHoldBooking = true;
        }        
        
        $creditBalance = $this->outstationModel->checkCreditLimit($userId);   // Get User Credit Balance // 
        
        $recentData = [
            'user_id'=>$userData['user_id'],
            'ip'=>$_SERVER['REMOTE_ADDR'],
            'booking_stage'=>$this->config()->getConfig()->bookingSteps->step2,
            'booking_data'=>$paymentData
        ];
        $this->CommonModel->addRecentViewedItems($recentData);
        $form = new TravellerForm();
        $form->get('first_name')->setValue($userData['first_name']);
        $form->get('first_name')->setAttribute('readonly', 'true');
        $form->get('last_name')->setValue($userData['last_name']);
        $form->get('last_name')->setAttribute('readonly', 'true');
        $form->get('mobile')->setValue($userData['mobile']);
        $form->get('mobile')->setAttribute('readonly', 'true');
        $form->get('alt_mobile_number')->setValue($userData['alternate_mobile']);
        $form->get('alt_mobile_number')->setAttribute('readonly', 'true');
        $form->get('email')->setValue($userData['email']);
        $form->get('email')->setAttribute('readonly', 'true');
        $form->get('nationality')->setValue($paymentData['nationality']);
        $form->get('agree_terms')->setValue(1);
        $viewModel = new ViewModel([
            'form' => $form,
            'paymentData' => $paymentData,
            'vehcilePaymentData' => $vehcilePaymentData,
            'currIcon' => $currIcon,
            'captchaKey' => $this->config()->getConfig()->googleCaptcha->siteKey,
            'userCanHoldBooking'=>$userCanHoldBooking,
            'company_logo' =>  (isset($companyLogoPath))?$companyLogoPath:'',
            'creditBalance' =>  $creditBalance
        ]);
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
    public function roundTripTravellerSaveAction() {
        $sessionUser = new Container('userlogin');
        $userData = $sessionUser->userData;
        $userId  = $userData['user_id'];
        $userTypeId = $userData['user_type_id'];
        $recaptcha_error = '';
        if (!empty($userData)) {
            $guest_id = $userData['user_id'];
        } else {
            $guest_id = "";
        }

        $sessionContainer = new Container('vehicle');
        $paymentData = $sessionContainer->vehicleData;
        unset($sessionContainer->booking_id);
        
        $currencyType = $paymentData['currency_type'];
        $currData = $this->outstationModel->getCurrencyDetails($currencyType);
        $currIcon = $currData['fa_icon'];

        $sessionContainer1 = new Container('vehiclePayData');
        $payData = $sessionContainer1->vehiclePaymentData;
        $vehcilePaymentData = $payData[$paymentData['vehicle_id']];
        $vehcilePaymentData = array_filter($vehcilePaymentData);
        //Debug::dump($paymentData); exit;
        //////////// Session Data /////////////////

        /*if ($paymentData['local_pickup'] == 2) {
            $getDate = $this->getDate($paymentData['local_pickup'], $paymentData['pickup_date']);
            $getTime = $this->getTime($paymentData['local_pickup'], $paymentData['pickup_time']);
            $paymentData['pickup_date'] = date("Y-m-d", strtotime($getDate));
            $paymentData['pickup_time'] = $getTime;
        } else if ($paymentData['local_pickup'] == 3) {
            $getTime = $this->getTime($paymentData['local_pickup'], $paymentData['pickup_time']);
            $paymentData['pickup_time'] = $getTime;
        }*/

        $paymentData['pickup_date'] = date("Y-m-d", strtotime($paymentData['pickup_date']));
        $paymentData['pickup_city'] = $paymentData['pickcity_id'];
        $paymentData['drop_city'] = $paymentData['dropcity_id'];

        $pickAreaData = $this->fetchGoogleApiData($paymentData['pickup_address']);

        $pickAreaData = Json::decode($pickAreaData);

        //Debug::dump($pickAreaData); exit;

        $pickAreaLat = isset($pickAreaData->results[0]->geometry->location->lat) ? $pickAreaData->results[0]->geometry->location->lat : '';
        $pickAreaLng = isset($pickAreaData->results[0]->geometry->location->lng) ? $pickAreaData->results[0]->geometry->location->lng : '';
        $pickUpZone = isset($pickAreaData->results[0]->address_components[5]->long_name) ? $pickAreaData->results[0]->address_components[5]->long_name : '';

        $data = $this->getStateCountry($paymentData['pickcity_id']);
        $data1 = $this->getStateCountry($paymentData['dropcity_id']);

        $dropAreaData = $this->fetchGoogleApiData($paymentData['drop_city']);
        $dropAreaData = json_decode($dropAreaData);
        //Debug::dump($dropAreaData); exit;


        $dropAreaLat = isset($dropAreaData->results[0]->geometry->location->lat) ? $dropAreaData->results[0]->geometry->location->lat : '';
        $dropAreaLng = isset($dropAreaData->results[0]->geometry->location->lng) ? $dropAreaData->results[0]->geometry->location->lng : '';
        $dropZone = isset($dropAreaData->results[0]->address_components[5]->long_name) ? $dropAreaData->results[0]->address_components[5]->long_name : '';
        //$dropTime = strtotime("+" . $paymentData['duration'], strtotime($paymentData['pickup_date'] . ' ' . $paymentData['pickup_time']));
        //$dropDate = date('Y-m-d', $dropTime);
        //$dropTime = date('H:i:s', $dropTime);


        $paymentData['pickup_latitude'] = $pickAreaLat;
        $paymentData['pickup_longitude'] = $pickAreaLng;
        $paymentData['pickup_zone'] = $pickUpZone;
        $paymentData['pickup_landmark'] = '';
        $paymentData['pickup_country'] = isset($data['response'][0]['country_id']) ? $data['response'][0]['country_id'] : '';
        $paymentData['pickup_state'] = isset($data['response'][0]['state_id']) ? $data['response'][0]['state_id'] : '';
        $paymentData['drop_date'] = $paymentData['drop_date'];
        $paymentData['drop_time'] = $paymentData['drop_time'];
        $paymentData['drop_country'] = isset($data1['response'][0]['country_id']) ? $data1['response'][0]['country_id'] : '';
        $paymentData['drop_state'] = isset($data1['response'][0]['state_id']) ? $data1['response'][0]['state_id'] : '';
        $paymentData['drop_landmark'] = '';
        $paymentData['drop_latitude'] = $dropAreaLat;
        $paymentData['drop_longitude'] = $dropAreaLng;
        $paymentData['drop_zone'] = $dropZone;
        $paymentData['device_type'] = "Web";
        $paymentData['flight_number'] = '';
        $paymentData['airport'] = '';
        $paymentData['package_id'] = '';
        //exit;

        $paymentData['guest_first_name'] = $paymentData['first_name'];
        $paymentData['guest_last_name'] = $paymentData['last_name'];
        $paymentData['guest_email'] = $paymentData['email'];
        $paymentData['guest_mobile'] = $paymentData['mobile'];
        $paymentData['guest_alt_mobile'] = $paymentData['alt_mobile_no'];
        $paymentData['guest_gender'] = $paymentData['gender'];
        $paymentData = $paymentData->toArray();
        //$paymentData = array_filter($paymentData);
        
        $currencyType = $paymentData['currency_type'];
        $currencyData = $this->outstationModel->getCurrencyDetails($currencyType);
        $company_details = $this->outstationModel->getCompanyDetail($userId);
        $company_logo    = (isset($company_details['company_logo']))?$company_details['company_logo']:'';        
        if($company_logo){            
            $companyLogoPath = $this->config()->getConfig()->base_url->b2burl."/" . $userId . "/" . $company_logo;
        }
        
        $holdBookingUser = $this->config()->getConfig()->holdBookingUserAccess;
        $holdBookingUserArr = $holdBookingUser->toArray();
        $userCanHoldBooking =false;
        if (in_array($userTypeId, $holdBookingUserArr)){
            $userCanHoldBooking = true;
        }
        
        $form = new TravellerForm();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->getPost());
            $post = $request->getPost()->toArray();
            /*if ($post['g-recaptcha-response'] == '') {
                $recaptcha_error = 'Please check the captcha';
            }*/
            $creditBalance = $this->outstationModel->checkCreditLimit($userId);  
            $total_booking_price = $paymentData['total_price'];           
            $balance_error = '';
            if($post['voucher']!='' && ($creditBalance < $total_booking_price)){
                   $balance_error = 'Credit Balance is not available for create voucher'; 
            }
            if ($form->isValid() && $balance_error=='') {
                if ($guest_id == "") {
                    $guestArray['user_type_id'] = 1;
                    $guestArray['first_name'] = $paymentData['guest_first_name'];
                    $guestArray['last_name'] = $paymentData['guest_last_name'];
                    $guestArray['mobile'] = $paymentData['guest_mobile'];
                    $guestArray['email'] = $paymentData['guest_email'];
                    $guestArray['password'] = md5($paymentData['guest_mobile']);
                    $guestArray['gender'] = $paymentData['guest_gender'];
                    $guestArray['user_grade'] = $this->config()->getConfig()->userGrade->defaultGrade;
                    $guestData = $this->getUserId($guestArray);
                    $paymentData['user_id'] =  $guestData['data']['user_id'];
                } else {
                    $paymentData['user_id'] = $guest_id;
                }

                $userArray['user_type_id'] = 2;
                $userArray['company_id'] = $this->config()->getConfig()->company->companyId;
                $userArray['first_name'] = $post['first_name'];
                $userArray['last_name'] = $post['last_name'];
                $userArray['mobile'] = $post['mobile'];
                $userArray['email'] = $post['email'];
                $userArray['password'] = md5($post['mobile']);
                //$userArray['gender'] = $post['gender'];
                $userArray['nationality'] = $this->getCountryId($paymentData['nationality']);
                $userArray['gst_no'] = $post['gst_no'];
                $userArray['alt_mobile_no'] = $post['alt_mobile_number'];
                $userArray['user_grade'] = $this->config()->getConfig()->userGrade->defaultGrade;

                if($post['book_vehicle_user']==1){
                $clientData = $this->getUserId($userArray);
                $paymentData['client_id'] = $clientData['data']['user_id'];
                } else {
                $paymentData['client_id'] = $guest_id;
                }
                $paymentData['vehicle_type_id'] = $vehcilePaymentData['vehicle_type_id'];
                //exit;
                //Debug::dump($paymentData);
                //Debug::dump($post);
                //Debug::dump($vehcilePaymentData);
                //exit;

                $finalData = [];
                $finalData = array_merge($paymentData, $post, $vehcilePaymentData);
                //$finalData = array_merge($paymentData, $post);
                //Debug::dump($finalData); exit;
                unset($sessionContainer->vehicleData);
                $sessionContainer->vehicleData = $finalData;
                
                $recentData = [
                    'user_id'=>$userData['user_id'],
                    'ip'=>$_SERVER['REMOTE_ADDR'],
                    'booking_stage'=>$this->config()->getConfig()->bookingSteps->step3,
                    'booking_data'=>$finalData
                ];
                $this->CommonModel->addRecentViewedItems($recentData);               
                
                if ($guest_id == "") {
                    $this->redirect()->toRoute('outstation', ['action' => 'login']);
                } else {
                     if(isset($post['hold_booking']) && $post['hold_booking']!=''){
                        $this->redirect()->toRoute('outstation', ['action' => 'hold-booking']);
                    }else{
                        $this->redirect()->toRoute('outstation', ['action' => 'checkout']);
                    }
                }
            }
        }

        $viewModel = new ViewModel([
            'form' => $form,
            'paymentData' => $paymentData,
            'currIcon' => $currIcon,
            //'error' => $recaptcha_error,
            'captchaKey' => $this->config()->getConfig()->googleCaptcha->siteKey,
            'balance_error' => $balance_error,            
            'vehcilePaymentData' => $vehcilePaymentData,
            'currencyData' => $currencyData,
            'userCanHoldBooking'=>$userCanHoldBooking,
            'company_logo' =>  (isset($companyLogoPath))?$companyLogoPath:''
        ]);
        $viewModel->setTemplate('outstation/index/round-trip-traveller.phtml');
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
    public function roundTripAddOnAction() {
        $data = [];
        $paymentData = [];
        $sessionContainer = new Container('roundTrip');
        $data = $this->getRequest()->getPost();
        //Debug::dump($data);
        $sessionContainer->vehicle_id = $data['vehicle_id'];
        Debug::dump($sessionContainer->vehicleSearchData);
        Debug::dump($sessionContainer->guestFormData);
        $form = new RoundTripSearchForm();
        $data['pickup_time'] = urldecode($data['pickup_time']);
        $data['return_time'] = urldecode($data['return_time']);
        $data['pickup_address'] = urldecode($data['pickup_address']);
        $form->setData($data);
        $vehicleType = $this->forward()->dispatch(IndexController::class, array('action' => 'getVehicleType'));
        $fuelType = $this->forward()->dispatch(IndexController::class, array('action' => 'getFuelType'));
        $sightseeingList = $this->fetchSightSeeing();

        $viewModel = new ViewModel([
            'form' => $form,
            'data' => $data,
            'vehicle_type' => $vehicleType,
            'fuel_type' => $fuelType,
            'sight_seeing_list' => $sightseeingList,
            'google_map_url' => $this->config()->getConfig()->google_map->url,
            'google_map_key' => $this->config()->getConfig()->google_map->key,
        ]);
        return $viewModel;
    }

    public function roundtripReviewAction() {
        $sessionContainer = new Container('roundTrip');
        echo $sessionContainer->vehicle_id;
        Debug::dump($sessionContainer->vehicleSearchData);
        Debug::dump($sessionContainer->vehicleListingData);
        //Debug::dump($sessionContainer->guestFormData);
        $vehicleList = $sessionContainer->vehicleListingData;
        $request = $this->getRequest();
        if ($request->isPost()) {
            $data = "";
            $paymentData = $request->getPost()->toArray();
            Debug::dump($paymentData);
        }
        $data = array_merge($sessionContainer->vehicleSearchData, $paymentData);
        //$data   =   $sessionContainer->vehicleSearchData;
        Debug::dump($data);
        $form = new RoundTripSearchForm();
        $form->setData($data);
        $viewModel = new ViewModel([
            'form' => $form,
            'data' => $data,
            'vehicleList' => $vehicleList,
            'google_map_url' => $this->config()->getConfig()->google_map->url,
            'google_map_key' => $this->config()->getConfig()->google_map->key,
        ]);
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
    public function guestAction() {
        $guestForm = new GuestForm();
        $viewModel = new ViewModel([
            'guestForm' => $guestForm
        ]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function oneWayGuestAction() {
        $sessionContainer = new Container('oneWay');
        $guestForm = new GuestForm();
        $result = [];
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $guestForm->setData($request->getPost());
            $postGuest = $request->getPost()->toArray();
            if ($postGuest['gst'] == "1") {
                $guestForm->getInputFilter()->get('gst_registration_number')->setRequired(true);
                $guestForm->getInputFilter()->get('gst_registered_company_name')->setRequired(true);
            }
            if ($guestForm->isValid()) {
                $sessionContainer->guestFormData = $postGuest;
                $result = array('status' => 'success', 'form_type' => $this->onWayType);
                $view = new JsonModel($result);
                return $view;
            } else {
                $result = array('status' => 'error', 'msg' => $guestForm->getMessages());
                $view = new JsonModel($result);
                return $view;
            }
        }
    }

    public function roundTripGuestAction() {
        $sessionContainer = new Container('roundTrip');
        $guestForm = new GuestForm();
        $result = [];
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $guestForm->setData($request->getPost());
            $postGuest = $request->getPost()->toArray();
            if ($postGuest['gst'] == "1") {
                $guestForm->getInputFilter()->get('gst_registration_number')->setRequired(true);
                $guestForm->getInputFilter()->get('gst_registered_company_name')->setRequired(true);
            }
            if ($guestForm->isValid()) {
                $sessionContainer->guestFormData = $postGuest;
                $result = array('status' => 'success', 'form_type' => $this->roundTripType);
                $view = new JsonModel($result);
                return $view;
            } else {
                $result = array('status' => 'error', 'msg' => $guestForm->getMessages());
                $view = new JsonModel($result);
                return $view;
            }
        }
    }

    public function multiCityGuestAction() {
        $sessionContainer = new Container('multiCity');
        $guestForm = new GuestForm();
        $result = [];
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $guestForm->setData($request->getPost());
            $postGuest = $request->getPost()->toArray();
            if ($postGuest['gst'] == "1") {
                $guestForm->getInputFilter()->get('gst_registration_number')->setRequired(true);
                $guestForm->getInputFilter()->get('gst_registered_company_name')->setRequired(true);
            }
            if ($guestForm->isValid()) {
                $sessionContainer->guestFormData = $postGuest;
                $result = array('status' => 'success', 'form_type' => $this->multiCityType);
                $view = new JsonModel($result);
                return $view;
            } else {
                $result = array('status' => 'error', 'msg' => $guestForm->getMessages());
                $view = new JsonModel($result);
                return $view;
            }
        }
    }

    /**
     *
     * @return ViewModel
     */
    public function multiCityAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $userId = $loginData['user_id'];
        $form = new MultiCitySearchForm('product-form', null);
        //$form->bind($data);
        $data = '';

        $sessionCityContainer = new Container('vehicleCityData');
        //get request object
        if(!empty($sessionCityContainer->pickup_city)){
            $pickupCity    =   $sessionCityContainer->pickup_city;
            $cityId        =   $sessionCityContainer->city_id;
            $form->get('destination_name')->setValue($pickupCity);
            $form->get('pickcity_id')->setValue($cityId);
            $boundData = $this->getLatLngData($pickupCity);
            //echo '<pre>';print_r($boundData);die();
            if ($boundData['status'] == 1) {
                $form->get('city_latitude')->setValue($boundData['data']['lat']);
                $form->get('city_longitude')->setValue($boundData['data']['lng']);
                $form->get('city_northeast_latitude')->setValue($boundData['data']['north_east_lat']);
                $form->get('city_northeast_longitude')->setValue($boundData['data']['north_east_lng']);
                $form->get('city_southwest_latitude')->setValue($boundData['data']['south_west_lat']);
                $form->get('city_southwest_longitude')->setValue($boundData['data']['south_west_lng']);
            }
            $sessionVehContainer = new Container('vehicleSearchData');
            $data = $sessionVehContainer->vehicleSearchData;
            if($data!=""){
                $form->setData($data);
            }
        }


        $sessionVehContainer = new Container('vehicleSearchData');
        $data = $sessionVehContainer->vehicleSearchData;

        if($data!=""){
            if(isset($data['city_id']) && !empty($data['city_id']))
            {
                $form->get('pickcity_id')->setValue($data['city_id']);
            }
            if(isset($data['pickcity_id']) && !empty($data['pickcity_id']))
            {
                $form->get('pickcity_id')->setValue($data['pickcity_id']);
            }
        $form->setData($data);
        }
        $collection = $form->get('new-product')->get('items')->setCount($this->itemCount);
        $form->get('module_type')->setValue($this->multiCityType);
        $form->get('master_package_type')->setValue($this->masterPackageType);
        // Check if user has submitted the form
        if ($this->getRequest()->isPost()) {

            // Fill in the form with POST data
            $data = $this->params()->fromPost();
            //Debug::dump($data);exit;
            //Debug::dump($data['new-product']['items']);
            //Debug::dump($items);die;
            $form->setData($data);

            if ($data['flight_mode'] == $this->flightModeOn) {
                $form->getInputFilter()->get('flight_number')->setRequired(true);
                $form->getInputFilter()->get('flight_time')->setRequired(true);
                $form->get('flight_mode_selected')->setValue($this->flightModeOn);
            }

            if ($data['flight_mode'] == $this->flightModeOff) {
                $form->getInputFilter()->get('flight_number')->setRequired(false);
                $form->getInputFilter()->get('flight_time')->setRequired(false);
                $form->get('flight_mode_selected')->setValue($this->flightModeOff);
            }

            // Validate form
            if ($form->isValid()) {
                // Get filtered and validated data
                $data = $form->getData();
                //Debug::dump($data['new-product']['items']); //exit;
                $items = $this->getItemsDetails($data['new-product']['items']);
                
                $recentData = [
                        'user_id'=>$userId,
                        'ip'=>$_SERVER['REMOTE_ADDR'],
                        'booking_stage'=>$this->config()->getConfig()->bookingSteps->step1,
                        'booking_data'=>$data
                    ];
                $this->CommonModel->addRecentViewedItems($recentData);
                //Debug::dump($items); exit;
                $this->redirect()->toRoute('outstation', [
                    'action' => 'multi-city-vehicle-listing',
                        ], ['query' => [
                        'items' => $items,
                        'flight_mode' => $data['flight_mode'],
                        'flight_number' => $data['flight_number'],
                        'flight_time' => $data['flight_time'],
                        'pickup_address' => $data['pickup_address'],
                        'adults' => $data['adults'],
                        'childs' => $data['childs'],
                        'luggages' => $data['luggages'],
                        'no_of_vehicles' => $data['no_of_vehicles'],
                        'agree_terms' => $data['agree_terms'],
                        'master_package_type' => $data['master_package_type'],
                        'module_type' => $data['module_type'],
                        'pickcity_id' => $data['pickcity_id'],
                        'city_latitude' => $data['city_latitude'],
                        'city_longitude' => $data['city_longitude'],
                        'city_northeast_latitude' => $data['city_northeast_latitude'],
                        'city_northeast_longitude' => $data['city_northeast_longitude'],
                        'city_southwest_latitude' => $data['city_southwest_latitude'],
                        'city_southwest_longitude' => $data['city_southwest_longitude'],
                        'nationality' => $data['nationality']
                    ]]
                );
            }
        }

        $vehicleTariff = [
            "0" => [
                "vehicle_type_packages" => [
                    'vehicle_type' => 'Economy',
                    'vehicle_image' => '/images/economycar.png',
                    'package_name' => '4 Hrs - 40 KM',
                    'price' => '800',
                    'extra_km' => '10',
                    'extra_hr' => '100',
                    'package_id' => '1'
                ],
                "packages" => [
                    "0" => [
                        'package_name' => '8 Hrs - 80 KM',
                        'price' => '1500',
                        'extra_km' => '10',
                        'extra_hr' => '100',
                        'package_id' => '2'
                    ],
                    "1" => [
                        'package_name' => '12 Hrs - 120 KM',
                        'price' => '2000',
                        'extra_km' => '10',
                        'extra_hr' => '100',
                        'package_id' => '3'
                    ],
                ],
            ],
            "1" => [
                "vehicle_type_packages" => [
                    'vehicle_type' => 'Sedan',
                    'vehicle_image' => '/images/sedancar.png',
                    'package_name' => '4 Hrs - 40 KM',
                    'price' => '800',
                    'extra_km' => '15',
                    'extra_hr' => '100',
                    'package_id' => '1'
                ],
                "packages" => [
                    "0" => [
                        'package_name' => '8 Hrs - 8 KM',
                        'price' => '1300',
                        'extra_km' => '15',
                        'extra_hr' => '100',
                        'package_id' => '2'
                    ],
                    "1" => [
                        'package_name' => '12 Hrs - 120 KM',
                        'price' => '2400',
                        'extra_km' => '15',
                        'extra_hr' => '100',
                        'package_id' => '3'
                    ],
                ],
            ],
            "2" => [
                "vehicle_type_packages" => [
                    'vehicle_type' => 'Prime',
                    'vehicle_image' => '/images/primecar.png',
                    'package_name' => '4 Hrs - 40 KM',
                    'price' => '1000',
                    'extra_km' => '15',
                    'extra_hr' => '120',
                    'package_id' => '1'
                ],
                "packages" => [
                    "0" => [
                        'package_name' => '8 Hrs - 80 KM',
                        'price' => '1800',
                        'extra_km' => '15',
                        'extra_hr' => '120',
                        'package_id' => '2'
                    ],
                    "1" => [
                        'package_name' => '4 Hrs - 40 KM',
                        'price' => '2600',
                        'extra_km' => '15',
                        'extra_hr' => '120',
                        'package_id' => '3'
                    ],
                ],
            ],
        ];

        return new ViewModel(
                [
            'vehicleTariff' => $vehicleTariff,
            'form' => $form,
            'data' => $data,
            'google_map_url' => $this->config()->getConfig()->google_map->url,
            'google_map_key' => $this->config()->getConfig()->google_map->key,
                ]
        );
    }

    /**
     *
     * @return ViewModel
     */
    public function multiCityVehicleListingAction() {
        $estimated_time = "";
        $sessionItems = new Container('multivehicledata');

        $data = [];
        $form = new MultiCitySearchForm('product-form', null);

        $guestForm = new GuestForm();
        $data = $this->params()->fromQuery();        
        $sessionItems->vehicleItems = $data['items'];      
        //$this->insertBookingDetails('2',$data['items']);
        //Debug::dump($data['items']); exit;
        //echo $data['items'][0]['pickcity_id'];
        $val = $this->getTotalDistance($data['items']);
        //$form->bind($data['items']);
        //Debug::dump($val);exit;
        //echo '<pre>';print_r($val);die();
        $data['distance'] = $val['distance'];
        $estimated_time = $val['estimated_time'];
        $total_days = $val['total_days']+ $this->extraDays;
        $collection = $form->get('new-product')->get('items')->setCount(count($data['items']));
        $form->setData($data);
        $form->get('module_type')->setValue($this->multiCityType);
        $form->get('master_package_type')->setValue($this->masterPackageType);
        if ($data['flight_mode'] == $this->flightModeOn) {
            $form->get('flight_number')->setValue($data['flight_number']);
            $form->get('flight_time')->setValue($data['flight_time']);
            $form->get('flight_mode_selected')->setValue($this->flightModeOn);
        }

        if ($data['flight_mode'] == $this->flightModeOff) {
            $form->get('flight_number')->setValue('');
            $form->get('flight_time')->setValue('');
            $form->get('flight_mode_selected')->setValue($this->flightModeOff);
        }
        $currency_id = 1;
        $data['currency_id']= $currency_id;
        $request = $this->getRequest();
        if ($request->isPost()) {
            $data = "";
            $data = $request->getPost()->toArray();
            $currency_id = (isset($data['currency_id']) && $data['currency_id']!='')?$data['currency_id']:1;
            $collection = $form->get('new-product')->get('items')->setCount(count($data['new-product']['items']));
            $data['items'] = $this->getItemsDetails($data['new-product']['items']);
            unset($sessionItems->vehicleItems);
            $sessionItems->vehicleItems = $data['items'];
            $val = $this->getTotalDistance($data['items']);
            $data['distance'] = $val['distance'];
            $estimated_time = $val['estimated_time'];
            $total_days = $val['total_days']+$this->extraDays;
            //Debug::dump($data['items']); //exit;
            $form->setData($request->getPost());
            if ($data['flight_mode'] == $this->flightModeOn) {
                $form->getInputFilter()->get('flight_number')->setRequired(true);
                $form->getInputFilter()->get('flight_time')->setRequired(true);
                $form->get('flight_mode_selected')->setValue($this->flightModeOn);
            }

            if ($data['flight_mode'] == $this->flightModeOff) {
                $form->getInputFilter()->get('flight_number')->setRequired(false);
                $form->getInputFilter()->get('flight_time')->setRequired(false);
                $form->get('flight_number')->setValue('');
                $form->get('flight_time')->setValue('');
                $form->get('flight_mode_selected')->setValue($this->flightModeOff);
            }

            if ($form->isValid()) {

            }

            if ($request->getPost()['form_type'] == "guest_form") {
                $result = [];
                if ($request->isXmlHttpRequest()) {
                    $guestForm->setData($request->getPost());
                    $postGuest = $request->getPost()->toArray();
                    if ($postGuest['gst'] == "1") {
                        $guestForm->getInputFilter()->get('gst_registration_number')->setRequired(true);
                        $guestForm->getInputFilter()->get('gst_registered_company_name')->setRequired(true);
                    }
                    if ($guestForm->isValid()) {
                        $result = array('status' => 'success', 'form_type' => $this->multiCityType);
                        $view = new JsonModel($result);
                        return $view;
                    } else {
                        $result = array('status' => 'error', 'msg' => $guestForm->getMessages());
                        $view = new JsonModel($result);
                        return $view;
                    }
                }
            }
        }

        $sessionVehContainer = new Container('vehicleSearchData');
        unset($sessionVehContainer->vehicleSearchData);
        $sessionVehContainer->vehicleSearchData = $data;

        $searchvehicleResp = $this->fetchFareDetails($data['items'][0]['pickcity_id'], $data['master_package_type'], date('H:i:s', strtotime($data['items'][0]['pickup_time'])), $data['distance'], isset($data['duration']) ? $data['duration'] : 0, $estimated_time, $total_days, $this->multiCityType, $data['adults'], $data['childs'], $data['luggages'],isset($data['pickup_date'])?$data['pickup_date']:'',$currency_id);
        //echo '<pre>';print_r($vehicleList);die();
        $vehicleList         =  $searchvehicleResp['response'];
        $leftside_filter_Arr =  $searchvehicleResp['filter_data'];
        $vehicleType = $this->forward()->dispatch(IndexController::class, array('action' => 'getVehicleType'));
        $fuelType = $this->forward()->dispatch(IndexController::class, array('action' => 'getFuelType'));
        $currencyList = $this->forward()->dispatch(IndexController::class, array('action' => 'getCurrencyList'));
        $viewModel = new ViewModel([
            'data' => $data,
            'form' => $form,
            'vehicleList' => $vehicleList,
            'vehicle_type' => $vehicleType,
            'fuel_type' => $fuelType,
            'currency_list' => $currencyList,
            'guestForm' => $guestForm,
            'outstation_type' => 'one-way',
            'google_map_url' => $this->config()->getConfig()->google_map->url,
            'google_map_key' => $this->config()->getConfig()->google_map->key,
            'filter_Arr' => $leftside_filter_Arr
        ]);
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
    public function multiCityFilteredVehicleListingAction() {
        $packageId = '1';
        $vehicleList = [
            "0" => [
                "vehicle_id" => 1,
                "vehicle_type" => "Economy",
                "vehicle_capacity" => 2,
                "vehicle_baggage" => 2,
                "vehicle_ignition_type" => "AC",
                "vehicle_duration" => "4h 5m",
                "approx_distance" => "120",
                "base_fare" => "500",
                "per_km_price" => "10",
                "min_distance" => "5",
                "running_amt" => "550",
                "peak_time_price" => "50",
                "night_charge" => "50",
                "extra_charge" => "50",
                "tax_percentage" => "18",
                "tax_price" => "200",
                "total_price" => "1500",
            ],
            "1" => [
                "vehicle_id" => 2,
                "vehicle_type" => "Sedan",
                "vehicle_capacity" => 3,
                "vehicle_baggage" => 4,
                "vehicle_ignition_type" => "AC",
                "vehicle_duration" => "5h 5m",
                "approx_distance" => "150",
                "base_fare" => "700",
                "per_km_price" => "15",
                "min_distance" => "10",
                "running_amt" => "850",
                "peak_time_price" => "50",
                "night_charge" => "50",
                "extra_charge" => "50",
                "tax_percentage" => "18",
                "tax_price" => "500",
                "total_price" => "1800",
            ],
            "2" => [
                "vehicle_id" => 3,
                "vehicle_type" => "Prime",
                "vehicle_capacity" => 4,
                "vehicle_baggage" => 5,
                "vehicle_ignition_type" => "NO-AC",
                "vehicle_duration" => "6h 5m",
                "approx_distance" => "180",
                "base_fare" => "800",
                "per_km_price" => "20",
                "min_distance" => "15",
                "running_amt" => "1100",
                "peak_time_price" => "50",
                "night_charge" => "50",
                "extra_charge" => "50",
                "tax_percentage" => "18",
                "tax_price" => "800",
                "total_price" => "2000",
            ]
        ];

        $view = new ViewModel([
            'vehicleList' => $vehicleList,
        ]);
        $view->setTerminal(true);
        return $view;
    }

    /**
     *
     * @return ViewModel
     */
    public function multiCityTravellerAction() {
        $sessionUser = new Container('userlogin');
        $userData = $sessionUser->userData;
        $userTypeId = $userData['user_type_id'];
        $userId  = $userData['user_id'];
        
        $sessionContainer = new Container('vehicle');
        $paymentData = $this->getRequest()->getPost();
        $sessionContainer->vehicleData = $paymentData;
        
        $sessionContainer1 = new Container('vehiclePayData');
        $payData = $sessionContainer1->vehiclePaymentData;
        $vehcilePaymentData = $payData[$paymentData['vehicle_id']];
        
        $currencyType = $paymentData['currency_type'];
        $currData = $this->outstationModel->getCurrencyDetails($currencyType);
        $currIcon = $currData['fa_icon'];
        
        $company_details = $this->outstationModel->getCompanyDetail($userId);
        $company_logo    = (isset($company_details['company_logo']))?$company_details['company_logo']:'';        
        if($company_logo){            
            $companyLogoPath = $this->config()->getConfig()->base_url->b2burl."/" . $userId . "/" . $company_logo;
        }
        
        $holdBookingUser = $this->config()->getConfig()->holdBookingUserAccess;
        $holdBookingUserArr = $holdBookingUser->toArray();
        $userCanHoldBooking =false;
        if (in_array($userTypeId, $holdBookingUserArr)){
            $userCanHoldBooking = true;
        }
        
        $creditBalance = $this->outstationModel->checkCreditLimit($userId);   // Get User Credit Balance //
        
        $recentData = [
            'user_id'=>$userData['user_id'],
            'ip'=>$_SERVER['REMOTE_ADDR'],
            'booking_stage'=>$this->config()->getConfig()->bookingSteps->step2,
            'booking_data'=>$paymentData
        ];
        $this->CommonModel->addRecentViewedItems($recentData);
        
        $form = new TravellerForm();
        $form->get('first_name')->setValue($userData['first_name']);
        $form->get('first_name')->setAttribute('readonly', 'true');
        $form->get('last_name')->setValue($userData['last_name']);
        $form->get('last_name')->setAttribute('readonly', 'true');
        $form->get('mobile')->setValue($userData['mobile']);
        $form->get('mobile')->setAttribute('readonly', 'true');
        $form->get('alt_mobile_number')->setValue($userData['alternate_mobile']);
        $form->get('alt_mobile_number')->setAttribute('readonly', 'true');
        $form->get('email')->setValue($userData['email']);
        $form->get('email')->setAttribute('readonly', 'true');
        $form->get('nationality')->setValue($paymentData['nationality']);
        $form->get('agree_terms')->setValue(1);
        $viewModel = new ViewModel([
            'form' => $form,
            'paymentData' => $paymentData,
            'vehcilePaymentData' => $vehcilePaymentData,
            'currIcon' => $currIcon,
            //'captchaKey' => $this->config()->getConfig()->googleCaptcha->siteKey,
            'userCanHoldBooking'=>$userCanHoldBooking,
            'company_logo' =>  (isset($companyLogoPath))?$companyLogoPath:'',
            'creditBalance' =>  $creditBalance
        ]);
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
    public function multiCityTravellerSaveAction() {
        $sessionUser = new Container('userlogin');
        $userData = $sessionUser->userData;
        $userId  = $userData['user_id'];
        $userTypeId = $userData['user_type_id'];
        $recaptcha_error = '';
        if (!empty($userData)) {
            $guest_id = $userData['user_id'];
        } else {
            $guest_id = "";
        }

        $sessionContainer = new Container('vehicle');
        $paymentData = $sessionContainer->vehicleData;
        unset($sessionContainer->booking_id);
        
        $currencyType = $paymentData['currency_type'];
        $currData = $this->outstationModel->getCurrencyDetails($currencyType);
        $currIcon = $currData['fa_icon'];
        $sessionContainer1 = new Container('vehiclePayData');
        $payData = $sessionContainer1->vehiclePaymentData;
        $vehcilePaymentData = $payData[$paymentData['vehicle_id']];
        $vehcilePaymentData = array_filter($vehcilePaymentData);
        //Debug::dump($vehcilePaymentData); exit;
        //////////// Session Data /////////////////

        /*if ($paymentData['local_pickup'] == 2) {
            $getDate = $this->getDate($paymentData['local_pickup'], $paymentData['pickup_date']);
            $getTime = $this->getTime($paymentData['local_pickup'], $paymentData['pickup_time']);
            $paymentData['pickup_date'] = date("Y-m-d", strtotime($getDate));
            $paymentData['pickup_time'] = $getTime;
        } else if ($paymentData['local_pickup'] == 3) {
            $getTime = $this->getTime($paymentData['local_pickup'], $paymentData['pickup_time']);
            $paymentData['pickup_time'] = $getTime;
        }*/

        $paymentData['pickup_date'] = date("Y-m-d", strtotime($paymentData['new-product']['items'][0]['pickup_date']));
        $paymentData['pickup_time'] = $paymentData['new-product']['items'][0]['pickup_time'];
        $pickAreaData = $this->fetchGoogleApiData($paymentData['pickup_address']);
        $pickAreaData = Json::decode($pickAreaData);

        //Debug::dump($paymentData); exit;

        $pickAreaLat = $pickAreaData->results[0]->geometry->location->lat;
        $pickAreaLng = $pickAreaData->results[0]->geometry->location->lng;
        $pickUpZone = isset($pickAreaData->results[0]->address_components[5]->long_name) ? $pickAreaData->results[0]->address_components[5]->long_name : '';

        $data = $this->getStateCountry($paymentData['pickcity_id']);
        $data1 = $this->getStateCountry($paymentData['dropcity_id']);
        $pickup_country_id = '';
        $drop_country_id = '';
        $pickup_state_id = '';
        $drop_state_id = '';
        if (!empty($data)) {
            $pickup_country_id = isset($data['response'][0]['country_id']) ? $data['response'][0]['country_id'] : '';
            $pickup_state_id = isset($data['response'][0]['state_id']) ? $data['response'][0]['state_id'] : '';
        }
        if (!empty($data1)) {
            $drop_country_id = isset($data1['response'][0]['country_id']) ? $data1['response'][0]['country_id'] : '';
            $drop_state_id = isset($data1['response'][0]['state_id']) ? $data1['response'][0]['state_id'] : '';
        }

        if (isset($paymentData['drop_city'])) {
            $dropAreaData = $this->fetchGoogleApiData($paymentData['drop_city']);
            $dropAreaData = json_decode($dropAreaData);
            //Debug::dump($dropAreaData); exit;


            $dropAreaLat = $dropAreaData->results[0]->geometry->location->lat;
            $dropAreaLng = $dropAreaData->results[0]->geometry->location->lng;
            $dropZone = $dropAreaData->results[0]->address_components[5]->long_name;
            $dropTime = strtotime("+" . $paymentData['duration'], strtotime($paymentData['pickup_date'] . ' ' . $paymentData['pickup_time']));
            $dropDate = date('Y-m-d', $dropTime);
            $dropTime = date('H:i:s', $dropTime);
        }

        $paymentData['pickup_latitude'] = $pickAreaLat;
        $paymentData['pickup_longitude'] = $pickAreaLng;
        $paymentData['pickup_zone'] = $pickUpZone;
        $paymentData['pickup_landmark'] = '';
        $paymentData['pickup_country'] = $pickup_country_id;
        $paymentData['pickup_state'] = $pickup_state_id;
        $paymentData['pickup_city'] = $paymentData['pickcity_id'];
        $paymentData['drop_date'] = isset($dropDate) ? $dropDate : '';
        $paymentData['drop_time'] = isset($dropTime) ? $dropTime : '';
        $paymentData['drop_country'] = $drop_country_id;
        $paymentData['drop_state'] = $drop_state_id;
        $paymentData['drop_city'] = $paymentData['dropcity_id'];
        $paymentData['drop_landmark'] = '';
        $paymentData['drop_latitude'] = isset($dropAreaLat) ? $dropAreaLat : '';
        $paymentData['drop_longitude'] = isset($dropAreaLng) ? $dropAreaLng : '';
        $paymentData['drop_zone'] = isset($dropZone) ? $dropZone : '';
        $paymentData['device_type'] = "Web";
        $paymentData['flight_number'] = '';
        $paymentData['airport'] = '';
        $paymentData['package_id'] = '';

        //exit;

        $paymentData['guest_first_name'] = $paymentData['first_name'];
        $paymentData['guest_last_name'] = $paymentData['last_name'];
        $paymentData['guest_email'] = $paymentData['email'];
        $paymentData['guest_mobile'] = $paymentData['mobile'];
        $paymentData['guest_alt_mobile'] = $paymentData['alt_mobile_no'];
        $paymentData['guest_gender'] = $paymentData['gender'];
        $paymentData = $paymentData->toArray();
        //$paymentData = array_filter($paymentData);
        //echo '<pre>';print_r($paymentData);die();

        $currencyType = $paymentData['currency_type'];
        $currencyData = $this->outstationModel->getCurrencyDetails($currencyType);
        $company_details = $this->outstationModel->getCompanyDetail($userId);
        $company_logo    = (isset($company_details['company_logo']))?$company_details['company_logo']:'';        
        if($company_logo){            
            $companyLogoPath = $this->config()->getConfig()->base_url->b2burl."/" . $userId . "/" . $company_logo;
        }
        
        $holdBookingUser = $this->config()->getConfig()->holdBookingUserAccess;
        $holdBookingUserArr = $holdBookingUser->toArray();
        $userCanHoldBooking =false;
        if (in_array($userTypeId, $holdBookingUserArr)){
            $userCanHoldBooking = true;
        }
        
        $form = new TravellerForm();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->getPost());
            $post = $request->getPost()->toArray();
            
            $creditBalance = $this->outstationModel->checkCreditLimit($userId);  
            $total_booking_price = $paymentData['total_price'];           
            $balance_error = '';
            if($post['voucher']!='' && ($creditBalance < $total_booking_price)){
                   $balance_error = 'Credit Balance is not available for create voucher'; 
            }
            
            /*if ($post['g-recaptcha-response'] == '') {
                $recaptcha_error = 'Please check the captcha';
            }*/
            if ($form->isValid() && $balance_error=='') {

                if ($guest_id == "") {
                    $guestArray['user_type_id'] = 1;
                    $guestArray['first_name'] = $paymentData['guest_first_name'];
                    $guestArray['last_name'] = $paymentData['guest_last_name'];
                    $guestArray['mobile'] = $paymentData['guest_mobile'];
                    $guestArray['email'] = $paymentData['guest_email'];
                    $guestArray['password'] = md5($paymentData['guest_mobile']);
                    $guestArray['gender'] = $paymentData['guest_gender'];
                    $guestArray['user_grade'] = $this->config()->getConfig()->userGrade->defaultGrade;
                    $guestData = $this->getUserId($guestArray);
                    $paymentData['user_id'] =  $guestData['data']['user_id'];
                } else {
                    $paymentData['user_id'] = $guest_id;
                }

                $userArray['user_type_id'] = 2;
                $userArray['company_id'] = $this->config()->getConfig()->company->companyId;
                $userArray['first_name'] = $post['first_name'];
                $userArray['last_name'] = $post['last_name'];
                $userArray['mobile'] = $post['mobile'];
                $userArray['email'] = $post['email'];
                $userArray['password'] = md5($post['mobile']);
                //$userArray['gender'] = $post['gender'];
                $userArray['nationality'] = $this->getCountryId($paymentData['nationality']);
                $userArray['gst_no'] = $post['gst_no'];
                $userArray['alt_mobile_no'] = $post['alt_mobile_number'];
                $userArray['user_grade'] = $this->config()->getConfig()->userGrade->defaultGrade;
                if($post['book_vehicle_user']==1){
                $clientData = $this->getUserId($userArray);
                $paymentData['client_id'] = $clientData['data']['user_id'];
                } else {
                $paymentData['client_id'] = $guest_id;
                }
                $paymentData['vehicle_type_id'] = $vehcilePaymentData['vehicle_type_id'];
                //exit;
                //Debug::dump($paymentData);
                //Debug::dump($post);
                //Debug::dump($vehcilePaymentData);
                //exit;

                $finalData = [];
                $finalData = array_merge($paymentData, $post, $vehcilePaymentData);
                //$finalData = array_merge($paymentData, $post);
                //Debug::dump($finalData); exit;
                unset($sessionContainer->vehicleData);
                $sessionContainer->vehicleData = $finalData;
                
                $recentData = [
                    'user_id'=>$userData['user_id'],
                    'ip'=>$_SERVER['REMOTE_ADDR'],
                    'booking_stage'=>$this->config()->getConfig()->bookingSteps->step3,
                    'booking_data'=>$finalData
                ];
                $this->CommonModel->addRecentViewedItems($recentData);
        
                if ($guest_id == "") {
                    $this->redirect()->toRoute('outstation', ['action' => 'login']);
                } else {
                    if(isset($post['hold_booking']) && $post['hold_booking']!=''){
                        $this->redirect()->toRoute('outstation', ['action' => 'hold-booking']);
                    }else{
                        $this->redirect()->toRoute('outstation', ['action' => 'checkout']);
                    }
                }
            }
        }

        $viewModel = new ViewModel([
            'form' => $form,
            'paymentData' => $paymentData,
            'currIcon' => $currIcon,
            'error' => $recaptcha_error,
            'captchaKey' => $this->config()->getConfig()->googleCaptcha->siteKey,
            'balance_error' => $balance_error,            
            'vehcilePaymentData' => $vehcilePaymentData,
            'currencyData' => $currencyData,
            'userCanHoldBooking'=>$userCanHoldBooking,
            'company_logo' =>  (isset($companyLogoPath))?$companyLogoPath:''
        ]);
        $viewModel->setTemplate('outstation/index/multi-city-traveller.phtml');
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
    public function multiCityAddOnAction() {
        $data = [];
        $form = new MultiCitySearchForm('product-form', null);
        $viewModel = new ViewModel([
            'form' => $form
        ]);
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
    public function multiCityAddMoreAction() {
        $form = new MultiCitySearchForm();
        $viewModel = new ViewModel([
            'form' => $form
        ]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
    public function applyCouponAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $couponCode = trim($postData['coupon_code']);
        $totalPrice = $postData['total_price'];
        $masterPackageId = $postData['master_package_id'];
        $companyId = $this->config()->getConfig()->company->companyId;

        $url = $this->apiUrl() . "/coupon-list/couponValidate?companyId=" . $companyId . "&couponcode=" . rawurlencode($couponCode) . "&masterPackageId=" . $masterPackageId;
        $resp = $this->get($url);
        $couponData = Json::decode($resp->getBody(), true);
        if ($couponData['validateCoupon']['status']=="success") {
            $coupon =   $couponData['validateCoupon']['data'];
            $status = true;
            $msg = "Coupon Code is Valid";
            $coupon_id = $coupon['id'];
            $coupon_discount_type = $coupon['discount_type'];
            $coupon_discount_value = $coupon['discount_amount'];
            if ($coupon['discount_type'] == 'Rs') {
                $couponDiscount = $coupon['discount_amount'];
                $totalPrice = $totalPrice - $couponDiscount;
            } else {
                $couponDiscount = $totalPrice * $coupon['discount_amount'] / 100;
                $totalPrice = $totalPrice - $couponDiscount;
            }
        } else {
            $status = false;
            $msg = "Coupon code is In-Valid";
            $couponDiscount = 0;
            $totalPrice = $totalPrice;
            $coupon_id = "";
            $coupon_discount_type = "";
            $coupon_discount_value = "";
        }
        $data = [
            'status' => $status,
            "msg" => $msg,
            "total_price" => $totalPrice,
            "coupon_discount" => $couponDiscount,
            "coupon_id" => $coupon_id,
            "coupon_discount_type" => $coupon_discount_type,
            "coupon_discount_value" => $coupon_discount_value
        ];
        $view = new JsonModel($data);
        return $view;
    }
    /**
     *
     * @return ViewModel
     */
    public function fareRulesAction() {
        $sessionContainer = new Container('vehiclePayData');
        $payData = $sessionContainer->vehiclePaymentData;
        $sessionVehContainer = new Container('vehicleSearchData');
        $searchData = $sessionVehContainer->vehicleSearchData;
        $data = [];
        $val = $this->params()->fromQuery();
        $data = $payData[$val['id']];
        $viewModel = new ViewModel([
            'data' => $data,
            'searchData' => $searchData
        ]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
    public function baggageAction() {
        $data = $this->params()->fromQuery('data');
        $viewModel = new ViewModel([
            'data' => $data
        ]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
    public function seatingCapacityAction() {
        $data = $this->params()->fromQuery('data');
        $viewModel = new ViewModel([
            'data' => $data
        ]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
    public function amenitiesAction() {
        $sessionContainer = new Container('vehiclePayData');
        $payData = $sessionContainer->vehiclePaymentData;
        $data = [];
        $val = $this->params()->fromQuery();
        $data = $payData[$val['id']];
        $viewModel = new ViewModel([
            'data' => $data
        ]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
    public function featureAction() {
        $sessionContainer = new Container('vehiclePayData');
        $payData = $sessionContainer->vehiclePaymentData;
        
        $sessionVehContainer = new Container('vehicleSearchData');
        $searchData = $sessionVehContainer->vehicleSearchData;
        
        $data = [];
        $val = $this->params()->fromQuery();
        $data = $payData[$val['id']];
        if ($val['type'] == "fare-rules") {
            $heading = "Fare Rules";
            $data = $data['fare_rule'];
        } elseif ($val['type'] == "baggage") {
            $heading = "Baggage";
            $data = $data['baggage'];
        } elseif ($val['type'] == "seating-capacity") {
            $heading = "Seating Capacity";
            $data = $data['seating_capacity'];
        } elseif ($val['type'] == "amenities") {
            $heading = "Amenities";
            $data = $data['amenities'];
        }elseif ($val['type'] == "meeting-point") {
            $heading = "Meeting Point";
            $data = $searchData['pickup_address'];
        }
        $viewModel = new ViewModel(['data' => $data, 'heading' => $heading]);
        $viewModel->setTemplate('local-hire/index/feature.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */

     public function paymentAction() {
        $sessionContainer = new Container('vehiclePayData');
        $payData = $sessionContainer->vehiclePaymentData;
        //Debug::dump($payData); //exit;
        $data = [];
        $postData = $this->getRequest()->getPost();
        $vehicleId = $postData['vehicle_id'];
        $currencyType = $postData['currency_type'];
        $currData = $this->outstationModel->getCurrencyDetails($currencyType);
        $exchange_rate = $currData['exchange_rate'];
        //echo $currencyType; die;
        $data = $payData[$vehicleId];
        //Debug::dump($data); exit;
        $data['base_fare']= round(($data['base_fare']*$exchange_rate),2);
        $data['per_km_price']= round(($data['per_km_price']*$exchange_rate),2);
        $data['running_amt']= round(($data['running_amt']*$exchange_rate),2);
        $data['peak_time_price']= round(($data['peak_time_price']*$exchange_rate),2);
        $data['night_charge']= round(($data['night_charge']*$exchange_rate),2);
        $data['extra_charge']= round(($data['extra_charge']*$exchange_rate),2);
        //$data['price_before_tax']= round(($data['price_before_tax']*$exchange_rate),2);
        $data['tax_price']= round(($data['tax_price']*$exchange_rate),2);
        $data['markup_price']= round(($data['markup_price']*$exchange_rate),2);
        $data['total_price']= round(($data['total_price']*$exchange_rate),2);
        $view = new JsonModel($data);
        return $view;
    }

    /**
     *
     * @return ViewModel
     */
    public function addOnServicesAction() {

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

    /**
     *
     * @return ViewModel
     */
    public function travellerAction() {

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

    /**
     *
     * @return ViewModel
     */
    public function reviewAction() {

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

    public function multiCityCarListingAction() {

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

    public function roundTripCarListingAction() {

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

    public function multiCityPaymentRightAction() {

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

    public function oneWayPaymentRightAction() {

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

    public function roundTripPaymentRightAction() {

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

    /**
     *
     * @return ViewModel
     */
    public function getDate($localPickup, $pickupDate) {
        if ($localPickup == $this->pickupNow) {
            $pickupDate = date("d-m-Y");
        } else {
            $pickupDate = date("d-m-Y", strtotime($pickupDate));
        }
        return $pickupDate;
    }

    /**
     *
     * @return ViewModel
     */
    public function getTime($localPickup, $pickupTime) {
        if ($localPickup == $this->pickupNow) {
            $pickupTime = date("H:i:s", strtotime("+30 minutes"));
        } else {
            $pickupTime = date("H:i:s", strtotime($pickupTime));
        }
        return $pickupTime;
    }

    public function getVehicleTypeAction() {
        $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 getFuelTypeAction() {
        $fuelTypeJsonDataArray = [];
        $url = $this->apiUrl() . "/fuel-type";
        $resp = $this->get($url);
        $fuelTypeJsonData = Json::decode($resp->getBody(), true);
        if ($fuelTypeJsonData['status'] == "success") {
            foreach ($fuelTypeJsonData['data'] as $res) {
                $fuelTypeJsonDataArray[$res['id']] = $res['fuel_type'];
            }
        }
        return $fuelTypeJsonDataArray;
    }

    public function getCurrencyListAction() {
        $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;
    }

    /**
     *
     * @return City Json
     */
    public function getToCityListAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $term = $postData['term'];
        //$val = '{"where":{"and": [{"city_id": "'.$city.'"},{"area": {"like": "' . $term . '%"}}]},"limit":10}';
        $val = '{"where": {"name": {"like": "' . $term . '%"}},"limit":10}';
        $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[] = ["label" => $value['name'], "city_id" => $value['id']];
            }
        } else {
            $data[] = ["label" => 'Not Exist'];
        }
        $view = new JsonModel($data);
        return $view;
    }

    public function getCityListAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $term = $postData['term'];
        $url = $this->apiUrl() . "/city/packageCity?city_name=" . $term;
        $resp = $this->get($url);
        $cityJsonData = Json::decode($resp->getBody(), true);
        if (!empty($cityJsonData['response'])) {
            foreach ($cityJsonData['response'] as $value) {
                $data[] = [
                    "label" => $value['city_name'],
                    "city_id" => $value['city_id'],
                    "latitude" => $value['latitude'],
                    "longitude" => $value['longitude'],
                    "north_east_latitude" => $value['north_east_latitude'],
                    "north_east_longitude" => $value['north_east_longitude'],
                    "south_west_latitude" => $value['south_west_latitude'],
                    "south_west_longitude" => $value['south_west_longitude']
                ];
            }
        } else {
            $data[] = ["label" => 'Not Exist'];
        }
        $view = new JsonModel($data);
        return $view;
    }

    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;
    }

    public function fetchGoogleApiDistance($origin_lat, $origin_lng, $destiny_lat, $destiny_lng) {
        $url = $this->config()->getConfig()->google_map->distUrl . "?origin=" . $origin_lat . ',' . $origin_lng . "&destination=" . $destiny_lat . ',' . $destiny_lng . "&key=" . $this->config()->getConfig()->google_map->key;
        $curl_handle = curl_init();
        curl_setopt($curl_handle, CURLOPT_URL, $url);
        curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 50);
        curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 199130000);
        $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;
    }

    public function getItemsDetails($items) {
        //echo '<pre>';print_r($items);die();
        $data = [];
        $estimated_time = 0;
        $i = 0;
        foreach ($items as $item) {
            $pickcity_id = $this->getCityId($item['pickup_city']);
            $dropcity_id = $this->getCityId($item['drop_city']);
            
            $pickupCitydata= $this->getStateCountry($pickcity_id);
            $dropCitydata = $this->getStateCountry($dropcity_id);
            
            $pickAreaData = $this->fetchGoogleApiData($item['pickup_city'].'-'.$pickupCitydata['response'][0]['counrty_name']);
            $pickAreaData = json_decode($pickAreaData);
            $pickAreaLat = $pickAreaData->results[0]->geometry->location->lat;
            $pickAreaLng = $pickAreaData->results[0]->geometry->location->lng;

            $dropAreaData = $this->fetchGoogleApiData($item['drop_city'].'-'.$dropCitydata['response'][0]['counrty_name']);
            $dropAreaData = json_decode($dropAreaData);
            $dropAreaLat = $dropAreaData->results[0]->geometry->location->lat;
            $dropAreaLng = $dropAreaData->results[0]->geometry->location->lng;

            $dataDistance = $this->fetchGoogleApiDistance($pickAreaLat, $pickAreaLng, $dropAreaLat, $dropAreaLng);
            $res = json_decode($dataDistance);
            //echo '<pre>';print_r($res);//die();
            if ($res->status == 'OK') {
                $res = $res->routes[0];
                $distance = round((($res->legs[0]->distance->value) / 1000), 1);
                $distance = round($distance);
                $duration = $res->legs[0]->duration->text;
                $estimated_time = $res->legs[0]->duration->value;
            }

            $dropTime = strtotime("+" . $duration, strtotime($item['pickup_date'] . ' ' . $item['pickup_time']));
            $dropTime = date('Y-m-d H:i:s', $dropTime);
            $drop = explode(' ', $dropTime);

            $cityDistance = $this->getCityDistance($item['pickup_city'], $item['drop_city']);
            if ($cityDistance > $distance) {
                $distance = $cityDistance;
            }

            

            $data[$i]['pickup_city'] = $item['pickup_city'];
            $data[$i]['drop_city'] = $item['drop_city'];
            $data[$i]['pickup_date'] = date('Y-m-d', strtotime($item['pickup_date']));
            $data[$i]['pickup_time'] = $item['pickup_time'];
            $data[$i]['days'] = $item['days'];
            $data[$i]['distance'] = $distance;
            $data[$i]['duration'] = $duration;
            $data[$i]['drop_date'] = $drop[0];
            $data[$i]['drop_time'] = $drop[1];
            $data[$i]['estimated_time'] = $estimated_time;
            $data[$i]['pickcity_id'] = $pickcity_id;
            $data[$i]['dropcity_id'] = $dropcity_id;
            $i++;
        }
        //die;
        return $data;
    }

    public function fetchSightSeeing() {

        $sightseeingList = [
            "0" => [
                "sight_details" => [
                    'city' => 'Delhi',
                    'date' => '12/10/2017',
                    'day' => 1
                ],
                "sight_seeings" => [
                    "0" => [
                        "sight_id" => 1,
                        "sight_name" => "Qutub Minar",
                        "sight_price" => 500,
                        "sight_image" => "/images/tajmahal.jpg"
                    ],
                    "1" => [
                        "sight_id" => 2,
                        "sight_name" => "Red Fort",
                        "sight_price" => 400,
                        "sight_image" => "/images/tajmahal.jpg"
                    ],
                    "2" => [
                        "sight_id" => 3,
                        "sight_name" => "Lotus Temple",
                        "sight_price" => 300,
                        "sight_image" => "/images/tajmahal.jpg"
                    ],
                    "3" => [
                        "sight_id" => 4,
                        "sight_name" => "Esckon Temple",
                        "sight_price" => 200,
                        "sight_image" => "/images/tajmahal.jpg"
                    ],
                    "4" => [
                        "sight_id" => 5,
                        "sight_name" => "Raj Ghat",
                        "sight_price" => 100,
                        "sight_image" => "/images/tajmahal.jpg"
                    ]
                ],
            ],
            "1" => [
                "sight_details" => [
                    'city' => 'Agra',
                    'date' => '13/10/2017',
                    'day' => 2
                ],
                "sight_seeings" => [
                    "0" => [
                        "sight_id" => 1,
                        "sight_name" => "Taj Mahal",
                        "sight_price" => 500,
                        "sight_image" => "/images/tajmahal.jpg"
                    ],
                    "1" => [
                        "sight_id" => 2,
                        "sight_name" => "Agra Fort",
                        "sight_price" => 400,
                        "sight_image" => "/images/tajmahal.jpg"
                    ],
                    "2" => [
                        "sight_id" => 3,
                        "sight_name" => "Chini Ka Rauza",
                        "sight_price" => 300,
                        "sight_image" => "/images/tajmahal.jpg"
                    ],
                    "3" => [
                        "sight_id" => 4,
                        "sight_name" => "Kanch Mahal",
                        "sight_price" => 200,
                        "sight_image" => "/images/tajmahal.jpg"
                    ],
                    "4" => [
                        "sight_id" => 5,
                        "sight_name" => "Great Idgah",
                        "sight_price" => 100,
                        "sight_image" => "/images/tajmahal.jpg"
                    ]
                ],
            ]
        ];

        return $sightseeingList;
    }

    /**
     *
     * @return Country
     */
    public function getStateCountry($city_id) {
        $data = [];
        if ($city_id) {
            $url = $this->apiUrl() . "/city/stateCountry?city_id=" . $city_id;
            $resp = $this->get($url);
            $data = Json::decode($resp->getBody(), true);
        }
        return $data;
    }

    public function getUserId($data) {
        $url = $this->apiUrl() . "/user/userRegistration";
        $resp = $this->post($url, $data);
        if ($resp->isSuccess()) {
            $respdata = Json::decode($resp->getBody(), true);
            $user_id = $respdata['responsedata']['data'];
            $response = ["status" => true, "message" => "Insert Successfully", "data" =>$user_id];
        } else {
            $response = ["status" => false, "message" => "Something Went Wrong", "data" => ""];
        }
        return $response;
    }

    public function userLogin($data) {
        $url = $this->apiUrl() . "/user/login";
        $resp = $this->post($url, $data);
        $response = Json::decode($resp->getBody(), true);
        $responseStatus = $response['responsedata']['status'];
        if ($responseStatus == true) {
            $val = ["status" => true, "data" => Json::decode($resp->getBody(), true)];
        } else {
            $val = ["status" => false, "data" => Json::decode($resp->getBody(), true)];
        }
        return $val;
        //Debug::dump($response);
        //exit;
    }

    public function getWalletAmt($user_id) {
        $url = $this->apiUrl() . "/user/walletamount?user_id=" . $user_id;
        $resp = $this->get($url);
        $response = Json::decode($resp->getBody(), true);
        $walletAmt = $response['responsedata']['data']['wallet_amount'];
        if ($walletAmt != "") {
            $data = $response['responsedata']['data']['wallet_amount'];
        } else {
            $data = 0;
        }
        return $data;
    }

    public function getWalletAmtUpdate($data) {
        $url = $this->apiUrl() . "/user/updateWalletAmount";
        $resp = $this->put($url, $data);
        $response = Json::decode($resp->getBody(), true);
        //Debug::dump($response);
        //exit;
        return $response;
    }

    public function userTransactionUpdate($data) {
        $url = $this->apiUrl() . "/payment/userTransaction";
        $resp = $this->post($url, $data);
        $response = Json::decode($resp->getBody(), true);
        //Debug::dump($response);
        //exit;
        return $response;
    }
    
    public function addUserTransaction($data) {
        $url = $this->apiUrl() . "/payment/adduserTransaction";
        $resp = $this->post($url, $data);
        $response = Json::decode($resp->getBody(), true);       
        return $response;
    }

    public function getBookingTransNo($val, $initial) {
        $dateYear = date('y');
        $dateMonth = date('m');
        $trans_no = $initial . '' . $dateYear . '' . $dateMonth . '' . $val;
        return $trans_no;
    }

    public function finalBookingSubmission($data) {
        $url = $this->apiUrl() . "/Booking/finalbooking";
        $resp = $this->post($url, $data);
        if ($resp->isSuccess()) {
            $response = ["status" => true, "message" => "Booking Insert Successfully", "data" => Json::decode($resp->getBody(), true)];
        } else {
            $response = ["status" => false, "message" => "Something Went Wrong", "data" => ""];
        }
        return $response;
    }

    public function getBookingRefNo($val, $initial) {
        //5380;HC
        //// Code for year Starts Here ///
        $dateYear = date('y');
        $dateYear = 64 + $dateYear;
        $dateYear = chr($dateYear);
        //// Code for year Ends Here ///
        //// Code for Month Starts Here ////////
        $dateMonth = date('m');
        $dateMonth = 64 + $dateMonth;
        $dateMonth = chr($dateMonth);
        //// Code for Month Ends Here///////

        $final1 = str_pad($val, 4, 0, STR_PAD_LEFT);
        $datam1 = array();
        if ($val >= 10000) {
            $divide = floor($val / 10000);
            $next = $val - ($divide * 10000);
            $aa = 64 + $divide;
            $neww = chr($aa);
            $final = str_pad($next, 4, 0, STR_PAD_LEFT);
            $id = $initial . '' . $dateYear . '' . $dateMonth . '' . $neww . '' . $final;
            $generated = $id;
        } else {
            $id = $initial . '' . $dateYear . '' . $dateMonth . '' . $final1;
            $generated = $id;
        }
        $datam1['generated'] = $generated;
        return $datam1;
    }

    public function updateBookingNo($data) {
        $url = $this->apiUrl() . "/booking/updateBookingNo";
        $resp = $this->put($url, $data);
        if ($resp->isSuccess()) {
            $response = ["status" => true, "message" => "Updated Successfully", "data" => Json::decode($resp->getBody(), true)];
        } else {
            $response = ["status" => false, "message" => "Something Went Wrong", "data" => ""];
        }
        return $response;
    }

    public function logStackTrackerData($bookingData) {
        $dataLogs = [];
        $dataStack = [];
        $dataTracker = [];

        $dataLogs['bookingid'] = $bookingData['booking_id'];
        $dataLogs['status'] = 1;
        $dataLogs['message'] = 'Requesting car';
        $dataLogs['time'] = date('Y-m-d H:i:s');

        $urlDataLogs = $this->apiUrl() . "/booking-logs";
        $this->post($urlDataLogs, $dataLogs);

        $dataStack['booking_id'] = $bookingData['booking_id'];
        $dataStack['latitude'] = $bookingData['pickup_latitude'];
        $dataStack['longitude'] = $bookingData['pickup_longitude'];
        $dataStack['status'] = '';
        $dataStack['last_try'] = date('Y-m-d H:i:s');

        $urlDataStack = $this->apiUrl() . "/booking-stack";
        $this->post($urlDataStack, $dataStack);

        $dataTracker['BookingID'] = $bookingData['booking_id'];
        $dataTracker['Latitutude'] = $bookingData['pickup_latitude'];
        $dataTracker['Logitude'] = $bookingData['pickup_longitude'];
        $dataTracker['Date_Time'] = date('Y-m-d H:i:s');
        $dataTracker['CabStatus'] = 1;

        $urlDataTracker = $this->apiUrl() . "/booking-tracker";
        $resp = $this->post($urlDataTracker, $dataTracker);
        $response = Json::decode($resp->getBody(), true);
    }

    public function checkPayment($walletStatus, $paymentStatus, $paymentData, $bookingRefNo, $bookingId) {
        //Debug::dump($paymentData);
        //echo $paymentStatus;
        //echo $bookingRefNo;
        //exit;
        if ($paymentStatus == 1) {
            //echo "Go on Payment Gateway";
            $atomPayment = $this->atomPaymentGateway($paymentData, $bookingRefNo, $walletStatus);
        } else {
            //echo "No Payment Gateway";
            if ($walletStatus == 1) {
                $data['user_id'] = $paymentData['user_id'];
                $data['wallet_amount'] = $paymentData['wallet_updated_amount'];
                $resp = $this->getWalletAmtUpdate($data);
                //print_r($resp);
                if ($resp['response']['changedRows'] == 1) {
                    $data['user_id'] = $paymentData['user_id'];
                    $data['booking_id'] = $bookingId;
                    $data['booking_transaction_no'] = $this->getBookingTransNo($bookingId, $this->config()->getConfig()->company->companyInitial);
                    $data['amount'] = $paymentData['booking_amt_paid'];
                    $data['current_balance'] = $paymentData['wallet_updated_amount'];
                    $data['payment_type_id'] = 3;
                    $data['payment_status'] = 1;
                    $data['created_date'] = date('Y-m-d');
                    $data['created_by'] = $paymentData['user_id'];
                    $this->userTransactionUpdate($data);
                }
            }
            $this->redirect()->toRoute('outstation', ['action' => 'success', 'param' => $bookingRefNo]);
        }
        //exit;
    }

    public function atomPaymentGateway($paymentData, $bookingRefNo, $walletStatus) {
        $data = [];
        //echo $walletStatus;
        //Debug::dump($paymentData);
        //exit;
        $url = $this->apiUrl() . "/payment/Atom";
        $data['login'] = $this->config()->getConfig()->atom_payment->login;
        $data['pass'] = $this->config()->getConfig()->atom_payment->pass;
        $data['ttype'] = $this->config()->getConfig()->atom_payment->ttype;
        $data['prodid'] = $this->config()->getConfig()->atom_payment->prodid;
        $data['amt'] = $paymentData['booking_amt_paid'];
        //$data['txncur'] = $this->config()->getConfig()->atom_payment->txncur;
        $data['txncur'] = $paymentData['currency_code'];
        $data['txnamt'] = $paymentData['booking_amt_paid'];
        $data['clientcode'] = $paymentData['client_id'];
        $data['transid'] = $bookingRefNo;
        $data['datepick'] = date('d/m/Y');
        $data['custacc'] = $this->config()->getConfig()->atom_payment->custacc;
        $data['udf1'] = $paymentData['first_name'];
        $data['udf2'] = $paymentData['email'];
        $data['udf3'] = $paymentData['mobile'];
        $data['udf4'] = 'karol bagh';
        $data['ru'] = $this->config()->getConfig()->base_url->url . "outstation/payment-response/" . $walletStatus;
        //Debug::dump(json_encode($data));
        $resp = $this->post($url, $data);
        $response = Json::decode($resp->getBody(), true);
        //Debug::dump($response);
        //exit;
        if ($response['response']['status'] == true) {
            $this->redirect()->toUrl($response['response']['url']);
        }
    }

    public function paymentResponseAction() {
        $sessionContainer = new Container('vehicle');
        $paymentData = $sessionContainer->vehicleData;
        $postData = $this->getRequest()->getPost()->toArray();
        $walletStatus = $this->params()->fromRoute('param');
        $url = $this->apiUrl() . "/payment/Atomresponse";
        $resp = $this->post($url, $postData);
        $response = Json::decode($resp->getBody(), true);
        //Debug::dump($response);
        //exit;
        $response['response']['data']['date'] = date('Y-m-d H:i:s', strtotime($response['response']['data']['date']));
        $url1 = $this->apiUrl() . "/payment/Transactionresp";
        $resp1 = $this->post($url1, $response['response']['data']);
        $response1 = Json::decode($resp1->getBody(), true);
        //Debug::dump($response1);
        //exit;
        if ($walletStatus == 1) {
            $data['user_id'] = $paymentData['user_id'];
            $data['wallet_amount'] = $paymentData['wallet_updated_amount'];
            $resp = $this->getWalletAmtUpdate($data);
        }
        if ($paymentData['wallet_data'] != 0) {
            $data['user_id'] = $paymentData['user_id'];
            $data['booking_id'] = $paymentData['booking_id'];
            $data['booking_transaction_no'] = $this->getBookingTransNo($paymentData['booking_id'], $this->config()->getConfig()->company->companyInitial);
            $data['amount'] = $paymentData['wallet_data'];
            $data['current_balance'] = $paymentData['wallet_updated_amount'];
            $data['payment_type_id'] = 4;
            $data['payment_status'] = 1;
            $data['created_date'] = date('Y-m-d');
            $data['created_by'] = $paymentData['user_id'];
            $this->userTransactionUpdate($data);
        }

        $data['user_id'] = $paymentData['user_id'];
        $data['booking_id'] = $paymentData['booking_id'];
        $data['booking_transaction_no'] = $this->getBookingTransNo($paymentData['booking_id'], $this->config()->getConfig()->company->companyInitial);
        $data['amount'] = $paymentData['booking_amt_paid'];
        $data['current_balance'] = $paymentData['wallet_updated_amount'];
        $data['payment_response_id'] = $response1['responsedata']['data']['insertId'];
        $data['payment_type_id'] = 5;
        $data['payment_status'] = 1;
        $data['action_type'] = 'Credit';
        $data['created_date'] = date('Y-m-d');
        $data['created_by'] = $paymentData['user_id'];
        $this->userTransactionUpdate($data);
        
        $data['user_id'] = $paymentData['user_id'];
        $data['booking_id'] = $paymentData['booking_id'];
        $data['booking_transaction_no'] = $this->getBookingTransNo($paymentData['booking_id'], $this->config()->getConfig()->company->companyInitial);
        $data['amount'] = $paymentData['booking_amt_paid'];
        $data['payment_response_id'] = $response1['responsedata']['data']['insertId'];
        $data['payment_type_id'] = 5;
        $data['payment_status'] = 1;
        $data['action_type'] = 'Debit';
        $data['created_date'] = date('Y-m-d');
        $data['created_by'] = $paymentData['user_id'];
        $this->addUserTransaction($data);

        if ($response['response']['data']['f_code'] == 'Ok') {
            $this->redirect()->toRoute('outstation', ['action' => 'success', 'param' => $response['response']['data']['mer_txn']]);
        } else {
            $this->redirect()->toRoute('outstation', ['action' => 'fail', 'param' => $response['response']['data']['mer_txn']]);
        }
        //return $response;
        //exit;
    }

    public function successAction() {
        $bookingRef = $this->params()->fromRoute('param');
        $invoicePath  = $this->config()->getConfig()->base_url->invoiceurl.date('Y')."/".date('m')."/".$bookingRef.".pdf";
        $viewModel = new ViewModel(['bookingRef' => $bookingRef,'invoicePath'=>$invoicePath]);
        return $viewModel;
    }

    public function failAction() {
        $bookingRef = $this->params()->fromRoute('param');
        $viewModel = new ViewModel(['bookingRef' => $bookingRef]);
        return $viewModel;
    }

    public function fetchFareDetails($city_id, $master_package_type, $pickupTime, $distance, $duration, $estimated_time, $total_days, $module_type, $adults, $childs, $luggages,$pickup_date,$currency_id) {
        $sessionUserContainer = new Container('userlogin');
        $userData = $sessionUserContainer->userData;
        //echo '<pre>';print_r($userData);die();
        $sessionContainer = new Container('vehiclePayData');
        $sessionCurrContainer = new Container('vehicleCurrencyData');
        $response = [];
        $data = [
            'city_id' => $city_id,
            'master_package_id' => $master_package_type,
            'pickup_time' => $pickupTime,
            'distance' => $distance,
            'duration' => $duration,
            'estimated_time' => $estimated_time,
            'total_days' => $total_days,
            'module_type' => $module_type,
            'company_id' => $this->config()->getConfig()->company->companyId,
            'user_id'=>$userData['user_id'],
            'company_gstno'=>$userData['companysetup_gst_no'],
            'user_gstno'=>$userData['user_gst_no'],
            'seating_capacity' => $adults+$childs,
            'luggage' => $luggages,
            'pickup_date'=> date("Y-m-d", strtotime($pickup_date)),
            'currency_id'=>$currency_id,
            'master_booking_type_id' => $this->config()->getConfig()->masterBookTypeId[1],
        ];

        $url = $this->apiUrl() . "/local_hire/faredetails";
        $resp = $this->post($url, $data);
        $packageFareData = Json::decode($resp->getBody(), true);
        //echo '<pre>';print_r($packageFareData);die();
        if (!empty($packageFareData)) {
            if ($packageFareData['responsedata']['status'] == "success") {
                $response = $packageFareData['responsedata']['data'];
                $filter_data = $packageFareData['responsedata']['filter_data'];
                $sessionCurrContainer->vehicleCurrencyData = $response;
                //echo '<pre>';print_r($a);die();
                foreach($response as $v){
                $response1 = $v;
                foreach ($response1 as $val) {
                    $res[$val['base_vehicle_id']] = $val;
                }
                }
                //echo '<pre>';print_r($res);die();
                unset($sessionContainer->vehiclePaymentData);
                $sessionContainer->vehiclePaymentData = $res;
            }
        }
        //echo '<pre>';print_r($response);die();
        //return $response;
        return ['response'=>$response,'filter_data'=>$filter_data];
    }

    public function fetchFareDetails1($city_id, $master_package_type, $pickupTime, $distance, $duration, $estimated_time, $total_days, $module_type) {
        $sessionUserContainer = new Container('userlogin');
        $userData = $sessionUserContainer->userData;
        //echo '<pre>';print_r($userData);die();
        $sessionContainer = new Container('vehiclePayData');
        $response = [];
        $data = [
            'city_id' => $city_id,
            'master_package_id' => $master_package_type,
            'pickup_time' => $pickupTime,
            'distance' => $distance,
            'duration' => $duration,
            'estimated_time' => $estimated_time,
            'total_days' => $total_days,
            'module_type' => $module_type,
            'company_id' => $this->config()->getConfig()->company->companyId,
            'user_id'=>$userData['user_id']
        ];
        $url = $this->apiUrl() . "/local_hire/faredetails";
        $resp = $this->post($url, $data);
        $packageFareData = Json::decode($resp->getBody(), true);
        if (!empty($packageFareData)) {
            if ($packageFareData['responsedata']['status'] == "success") {
                $response = $packageFareData['responsedata']['data'];
                foreach ($response as $val) {
                    $res[$val['base_vehicle_id']] = $val;
                }
                unset($sessionContainer->vehiclePaymentData);
                $sessionContainer->vehiclePaymentData = $res;
            }
        }
        return $response;
    }

    /**
     *
     * @return Fare Details
     */
    public function fetchFareDetailsOld($city_id, $master_package_type, $pickupTime, $distance, $duration, $estimated_time, $total_days, $module_type) {
        $sessionUserContainer = new Container('userlogin');
        $userData = $sessionUserContainer->userData;
        $sessionContainer = new Container('vehiclePayData');
        $response = [];
        if ($module_type == $this->roundTripType || $module_type == $this->multiCityType) {
            //$url = $this->apiUrl() . "/outstation/packageFareDetail?city_id=" . $city_id . "&package_id=" . $master_package_type ."&module_type=".$module_type;
            $url = $this->apiUrl() . "/outstation/packageFareDetail?city_id=" . $city_id . "&package_id=" . $master_package_type;
        } else {
            $url = $this->apiUrl() . "/outstation/packageFareDetail?city_id=" . $city_id . "&package_id=" . $master_package_type;
        }
        $resp = $this->get($url);
        $packageFareData = Json::decode($resp->getBody(), true);


        $gradeArray = [
            'searchCity' => $city_id,
            'userCity' => $userData['city_id'],
            'userTypeId' => $userData['user_type_id'],
            'userGender' => $userData['gender'],
        ];

        $grade = $this->outstationModel->getMarkupGrade($gradeArray);
        $markupData = $this->outstationModel->getCompanyMarkup($this->config()->getConfig()->company->companyId, $city_id, $master_package_type, $grade);

        /* $markup_data = $this->apiUrl() . "/markup/getCompanyMarkup?company_id=".$this->config()->getConfig()->company->companyId."&city_id=" . $city_id ."&master_package_id=" . $master_package_type;
          $markupValue = $this->get($markup_data);
          $markupData = Json::decode($markupValue->getBody(), true);
          if($markupData['responsedata']['status']=="success"){
          $markupData =   $markupData['responsedata']['data'][0];
          }else{
          $markupData=[];
          } */
        //Debug::dump($markupData);
        //exit;



        $min_pkg_km = '';
        $min_pkg_hrs = '';
        $peak_fare = 0;
        $night_charges = 0;
        $extra_charges = 0;
        $status = 1;
        $ignore_hrs = 0;
        $ignore_km = 0;
        $minimumCharge = 0;
        $estimated_time = $this->convertTime($estimated_time);

        if (!empty($packageFareData['packageFareDetail'])) {
            foreach ($packageFareData['packageFareDetail'] as $value) {

                $val = $this->fetchCalculationType($master_package_type, $value['master_package_mode_id'], $value['base_vehicle_id'], $minimumCharge, $ignore_hrs, $ignore_km, $status, $distance, $duration, $total_days, $markupData);
                //print_r($data);
                //$datam = $val;
//        if ($totalbill > $val['totalbill']) {
//            $datam['total_price'] = $totalbill;
//        } else {
//            $datam['total_price'] = $val['totalbill'];
//        }

                if ($val['min_pkg_km'] != "") {
                    $min_pkg_km = $val['min_pkg_km'];
                } else {
                    $min_pkg_km = $min_pkg_km;
                }

                if ($val['min_pkg_hrs'] != "") {
                    $min_pkg_hrs = $val['min_pkg_hrs'];
                } else {
                    $min_pkg_hrs = $min_pkg_hrs;
                }


                /* Peak Time Charge Calculation Starts Here */
                $peaks = $this->outstationModel->getFareData($value['base_vehicle_id'], $this->peakTimeCharge);
                //echo '<pre>';print_r($peaks);//die();
                if (!empty($peaks)) {
                    $peakValueArr = [];
                    $peak_fare = 0;
                    foreach ($peaks as $key => $peak) {
                        $peakValueArr[$key]['start_time'] = $peak['start_time'];
                        $peakValueArr[$key]['end_time'] = $peak['end_time'];
                        $peakValueArr[$key]['peaktime_type'] = $peak['peaktime_type'];
                        $peakValueArr[$key]['peaktime_value'] = $peak['peaktime_value'];
                        $peak_fare += $this->calculateCharges($pickupTime, $peak['start_time'], $peak['end_time'], $peak['peaktime_type'], $peak['peaktime_value'], $val['totalbill']);
                    }
                } else {
                    $peak_fare = 0;
                    $peakValueArr = [];
                }

                /* Peak Time Charge Calculation Ends Here */
                /* Peak Time Charge Calculation Ends Here */

                /* Night Charge Calculation Starts Here */
                $night_charges = $this->calculateCharges($pickupTime, $value['night_rate_begins'], $value['night_rate_ends'], $value['night_rate_type'], $value['night_rate_value'], $val['totalbill']);

                /* Night Charge Calculation Ends Here */

                /* Extra Charge Calculation Starts Here */

                $extras = $this->outstationModel->getFareData($value['base_vehicle_id'], $this->extras);
                if (!empty($extras)) {
                    $extraValueArr = [];
                    $extra_charges = 0;
                    foreach ($extras as $key => $extra) {
                        $extraValueArr[$key]['extras_name'] = $extra['extras_master_id'];
                        $extraValueArr[$key]['extra_value_type'] = $extra['extra_value_type'];
                        $extraValueArr[$key]['extra_value'] = $extra['extra_value'];
                        $extra_charges += $this->calculateExtraCharges($val['totalbill'], $extra['extra_value_type'], $extra['extra_value']);
                    }
                } else {
                    $extra_charges = 0;
                    $extraValueArr = [];
                }
                /* Extra Charge Calculation Ends Here */

                $totalbill = $peak_fare + $night_charges + $extra_charges + $val['totalbill'];

                /* Tax Calculation Starts Here */
                $total_tax = $value['sgst'] + $value['cgst'] + $value['igst'];
                $taxPrice = round((($totalbill) * $total_tax) / 100);
                $totalbill = $totalbill + $taxPrice;
                /* Tax Calculation Ends Here */

                $estimated_price_before_markup = $totalbill;

                if (!empty($markupData)) {
                    if ($markupData['markup_amt_base'] == 1) {
                        if ($markupData['mark_amt_type'] == 'Rs') {
                            $markupAmt = $markupData['basic_amt'];
                        } else {
                            $markupAmt = round(($totalbill * $markupData['basic_amt']) / 100);
                        }
                        $totalbill = $markupAmt + $totalbill;
                    } else {
                        $markupAmt = $val['markup_price'];
                    }
                } else {
                    $markupAmt = 0;
                }

                $totalbill = round($totalbill);
//                $total_bill_show= $totalbill;
//
//                if($module_type== $this->roundTripType){
//                $totalbill= $totalbill*2;
//                }

                $response[] = [
                    "min_pkg_km" => $min_pkg_km,
                    "min_pkg_hrs" => $min_pkg_hrs,
                    "vehicle_type_id" => $value['master_vehicle_type_id'],
                    "base_vehicle_id" => $value['base_vehicle_id'],
                    "vehicle_image" => $value['vehicle_image'],
                    "vehicle_type" => $value['vehicle_type'],
                    "base_fare" => $val['minimum_charge'],
                    "per_km_price" => $val['per_km_charge'],
                    "min_distance" => $val['min_distance'],
                    "running_amt" => $val['totalbill'],
                    "peak_time_price" => $peak_fare,
                    "night_charge" => $night_charges,
                    "extra_charge" => $extra_charges,
                    "tax_percentage" => $total_tax,
                    "tax_price" => $taxPrice,
                    "estimated_price_before_markup" => $estimated_price_before_markup,
                    "markup_base" => isset($markupData['markup_amt_base']) ? $markupData['markup_amt_base'] : '',
                    "markup_type" => isset($markupData['mark_amt_type']) ? $markupData['mark_amt_type'] : '',
                    "markup_value" => isset($markupData['basic_amt']) ? $markupData['basic_amt'] : 0,
                    "markup_price" => $markupAmt,
                    "total_price" => $totalbill,
                    "total_show_price" => $totalbill,
                    "vehicle_baggage" => $value['luggage'],
                    "vehicle_capacity" => $value['person_capacity'],
                    "vehicle_ignition_type" => 'AC',
                    "fare_rule" => $value['fare_rule'],
                    "baggage" => $value['baggage'],
                    "seating_capacity" => $value['seating_capacity'],
                    "amenities" => $value['amenities'],
                    "night_rate_type" => $value['night_rate_type'],
                    "night_rate_value" => $value['night_rate_value'],
                    "night_rate_begins" => $value['night_rate_begins'],
                    "night_rate_ends" => $value['night_rate_ends'],
                    "peakFare" => $peakValueArr,
                    "cgst_tax" => $value['cgst'],
                    "igst_tax" => $value['igst'],
                    "sgst_tax" => $value['sgst'],
                    "extras" => $extraValueArr,
                    "master_package_mode_id" => $value['master_package_mode_id'],
                    "estimated_time" => $estimated_time,
                    "duration" => $duration,
                    "estimated_distance" => $distance,
                    "approx_waiting_charge" => '',
                    "approx_waiting_minute" => '',
                    "created_date" => date('Y-m-d H:i:s'),
                ];

                $res[$value['base_vehicle_id']] = [
                    "min_pkg_km" => $min_pkg_km,
                    "min_pkg_hrs" => $min_pkg_hrs,
                    "vehicle_type_id" => $value['master_vehicle_type_id'],
                    "base_vehicle_id" => $value['base_vehicle_id'],
                    "vehicle_image" => $value['vehicle_image'],
                    "vehicle_type" => $value['vehicle_type'],
                    "base_fare" => $val['minimum_charge'],
                    "per_km_price" => $val['per_km_charge'],
                    "min_distance" => $val['min_distance'],
                    "running_amt" => $val['totalbill'],
                    "peak_time_price" => $peak_fare,
                    "night_charge" => $night_charges,
                    "extra_charge" => $extra_charges,
                    "tax_percentage" => $total_tax,
                    "tax_price" => $taxPrice,
                    "estimated_price_before_markup" => $estimated_price_before_markup,
                    "markup_base" => isset($markupData['markup_amt_base']) ? $markupData['markup_amt_base'] : '',
                    "markup_type" => isset($markupData['mark_amt_type']) ? $markupData['mark_amt_type'] : '',
                    "markup_value" => isset($markupData['basic_amt']) ? $markupData['basic_amt'] : 0,
                    "markup_price" => $markupAmt,
                    "total_price" => $totalbill,
                    "total_show_price" => $totalbill,
                    "vehicle_baggage" => $value['luggage'],
                    "vehicle_capacity" => $value['person_capacity'],
                    "vehicle_ignition_type" => 'AC',
                    "fare_rule" => $value['fare_rule'],
                    "baggage" => $value['baggage'],
                    "seating_capacity" => $value['seating_capacity'],
                    "amenities" => $value['amenities'],
                    "night_rate_type" => $value['night_rate_type'],
                    "night_rate_value" => $value['night_rate_value'],
                    "night_rate_begins" => $value['night_rate_begins'],
                    "night_rate_ends" => $value['night_rate_ends'],
                    "peakFare" => $peakValueArr,
                    "cgst_tax" => $value['cgst'],
                    "igst_tax" => $value['igst'],
                    "sgst_tax" => $value['sgst'],
                    "extras" => $extraValueArr,
                    "master_package_mode_id" => $value['master_package_mode_id'],
                    "estimated_time" => $estimated_time,
                    "duration" => $duration,
                    "estimated_distance" => $distance,
                    "approx_waiting_charge" => '',
                    "approx_waiting_minute" => '',
                    "created_date" => date('Y-m-d H:i:s'),
                ];
            }
            //$response = ["status" => true, "data" => $data];
            unset($sessionContainer->vehiclePaymentData);
            $sessionContainer->vehiclePaymentData = $res;
        }
        return $response;
        //return $data;
        //exit;
    }

    /**
     *
     * @return Calculation Type
     */
    public function fetchCalculationType($package_id, $calculationType, $baseVehicleId, $minimumCharge, $ignore_hrs, $ignore_km, $status, $distance, $duration, $total_days) {
        $totalmint = 0;
        $datam1 = [];
        $duration = 2;
        $permntavr = 40 / 60;
        if ($calculationType == '1') {
            $tableData = "distance_fares";
        } else if ($calculationType == '2') {
            $tableData = "hourly-fare";
        } else if ($calculationType == '3') {
            $tableData = "distance-hour-fare";
        } else if ($calculationType == '4') {
            $tableData = "distance-waiting-fare";
        }

        $val = '{"where": {"base_vehicle_id": "' . $baseVehicleId . '"}}';
        $val = rawurlencode($val);
        $urlFare = $this->apiUrl() . "/" . $tableData . "?&filter=" . $val;
        $respFare = $this->get($urlFare);
        $fareData = Json::decode($respFare->getBody(), true);
        //Debug::dump($fareData);
        //echo $status;
        if ($status == 1) {
            if ($calculationType == 1) {
                $ignore_hrs = 0;
                $ignore_km = isset($fareData[0]['minimum_distance']) ? $fareData[0]['minimum_distance'] : 0 * $total_days;
                $minimumCharge = isset($fareData[0]["minimum_charge"]) ? $fareData[0]["minimum_charge"] : 0 * $total_days;
            } elseif ($calculationType == 2) {
                $ignore_hrs = isset($fareData[0]['minimum_hrs']) ? $fareData[0]['minimum_hrs'] : 0;
                $ignore_km = 0;
                $minimumCharge = isset($fareData[0]["minimum_charge"]) ? $fareData[0]["minimum_charge"] * $total_days : 0 * $total_days;
            } elseif ($calculationType == 3) {
                $ignore_hrs = $fareData[0]['minimum_hrs'];
                $ignore_km = $fareData[0]['minimum_distance'] * $total_days;
                $minimumCharge = $fareData[0]["minimum_charge"] * $total_days;
            } elseif ($calculationType == 4) {
                $ignore_hrs = 0;
                $ignore_km = $fareData[0]['minimum_distance'] * $total_days;
                $minimumCharge = $fareData[0]["minimum_charge"] * $total_days;
            }
        }

        if ($package_id == "1") {
            if ($ignore_km == 0) {
                $distance = $ignore_hrs . ' hrs';
            } else {
                $distance = $ignore_km;
            }
            $travel_dis = $ignore_km;
            $travel_hrs = $ignore_hrs;
            if (strpos($distance, 'hrs') !== false) {
                $distance = explode(" ", $distance);
                $totalmint = $distance[0] * 60;
            } else {
                $totalmint = round($distance / $permntavr);
            }
        } elseif ($package_id == "2") {
            if ($distance == 0) {
                $distance = $ignore_km;
            } else {
                $distance = $distance;
            }
        }


        //echo '<pre>';print_r($markupData);die();
        if (!empty($markupData)) {
            if ($markupData['markup_amt_base'] == 2) {
                if ($markupData['mark_amt_type'] == '%') {
                    $markupPrice = round((($minimumCharge * $markupData['basic_amt']) / 100));
                    $minimumCharge = $minimumCharge + $markupPrice;
                    //$fareData[0]["per_km_charge"] = $fareData[0]["per_km_charge"] + round((($data["Per_Km_Charge"] * $markupData['extra_km_markup']) / 100));
                    //$fareData[0]["per_hr_charge"] = $fareData[0]["per_hr_charge"] + round((($fareData[0]["per_hr_charge"] * $markupData['extra_hr_markup']) / 100));
                } elseif ($markupData['mark_amt_type'] == 'Rs') {
                    $markupPrice = $markupData['basic_amt'];
                    $minimumCharge = $minimumCharge + $markupData['basic_amt'];
                    //$fareData[0]["per_km_charge"] = $fareData[0]["per_km_charge"] + $markupData['extra_km_markup'];
                    //$fareData[0]["per_hr_charge"] = $fareData[0]["per_hr_charge"] + $markupData['extra_hr_markup'];
                }
            } else {
                $markupPrice = 0;
            }
        } else {
            $markupPrice = 0;
        }

        if (empty($fareData[0]["per_km_charge"])) {
            $fareData[0]["per_km_charge"] = 0;
        }
        if ($calculationType == 1) {
            if ($distance > $ignore_km) {
                $ExtraKM = $distance - $ignore_km;
                $ExtraFare = $ExtraKM * $fareData[0]["per_km_charge"];
                $EstimatedPrice = $ExtraFare + $minimumCharge;
            } else {
                $EstimatedPrice = $minimumCharge;
            }

            $datam1['per_km_charge'] = isset($fareData[0]["per_km_charge"]) ? $fareData[0]["per_km_charge"] : 0;
            $datam1['min_distance'] = $ignore_km;
            $datam1['minimum_charge'] = $minimumCharge;
        } elseif ($calculationType == 2) {
            $ignore_first_hours = $ignore_hrs * 60; //die;
            if ($totalmint > $ignore_first_hours) {
                $rest_min = $totalmint - $ignore_first_hours;
                $ExtraFare = ($rest_min / 60) * $fareData[0]["per_hr_charge"];
                $EstimatedPrice = $ExtraFare + $minimumCharge;
            } else {
                $EstimatedPrice = $minimumCharge;
            }
            //// In Case per Hourly Charge 120 Rs and If car is running 40 Km Per hrs then per km charge is 120/40 is 3 Rs per Km Charge
            $datam1['per_km_charge'] = isset($fareData[0]["per_hr_charge"]) ? $fareData[0]["per_hr_charge"] : 0;
            $datam1['min_distance'] = $ignore_hrs * 40;
            $datam1['minimum_charge'] = $minimumCharge;
        } elseif ($calculationType == 3) {
            $totalmint = $travel_hrs;
            if ($distance < $ignore_km) {
                $distanceRate = 0;
            } else {
                $distanceRate = ($distance - $ignore_km) * $fareData[0]["per_km_charge"];
            }
            if ($travel_hrs > $ignore_hrs) {
                $hourlyRate = 0;
            } else {
                $hourlyRate = $travel_hrs - $ignore_hrs;
                $rate_per_min = $fareData[0]["per_hr_charge"] / 60;
                $hourlyRate = $hourlyRate * $rate_per_min;
            }
            $EstimatedPrice = $distanceRate + $hourlyRate + $minimumCharge;
            $datam1['min_distance'] = $ignore_km;
            $datam1['minimum_charge'] = $minimumCharge;
            $datam1['per_km_charge'] = $fareData[0]["per_km_charge"];
            $datam1['per_hr_charge'] = $fareData[0]["per_hr_charge"];
        } elseif ($calculationType == 4) {
            if ($distance > $ignore_km) {
                $ExtraKM = $distance - $ignore_km;
                $ExtraFare = $ExtraKM * $fareData[0]["per_km_charge"];
                $EstimatedPrice = $ExtraFare + $minimumCharge;
            } else {
                $EstimatedPrice = $minimumCharge;
            }
            $datam1['per_km_charge'] = $fareData[0]["per_km_charge"];
            $datam1['min_distance'] = $ignore_km;
            $datam1['minimum_charge'] = $minimumCharge;
        }

        $datam1['totalbill'] = $EstimatedPrice;
        $datam1['min_pkg_hrs'] = $ignore_hrs;
        $datam1['min_pkg_km'] = $ignore_km;
        $datam1['markup_price'] = $markupPrice;
        return $datam1;
    }

    public function calculateCharges($pickupTime, $rateBegins, $rateEnds, $chargeUnit, $charges, $totalbill) {
        $val = $this->isBetween($rateBegins, $rateEnds, $pickupTime) ? 'TRUE' : 'FALSE';
        if ($val == "FALSE") {
            $total_charges = 0;
        } else {
            if ($chargeUnit == 'Rs') {
                $total_charges = $charges;
            } else {
                $total_charges = ($totalbill * $charges) / 100;
            }
        }
        return $total_charges;
    }

    public function isBetween($from, $till, $input) {
        $f = \DateTime::createFromFormat('!H:i:s', $from);
        $t = \DateTime::createFromFormat('!H:i:s', $till);
        $i = \DateTime::createFromFormat('!H:i:s', $input);
        if ($f > $t)
            $t->modify('+1 day');
        return ($f <= $i && $i <= $t) || ($f <= $i->modify('+1 day') && $i <= $t);
    }

    public function calculateExtraCharges($totalbill, $extras_type, $extras_value) {
        $extra_charges = 0;
        if ($extras_type == "Rs") {
            $extra_charges = $extras_value;
        } elseif ($extras_type == "%") {
            $extra_charges = ($totalbill * $extras_value) / 100;
        }
        return $extra_charges;
    }

    /**
     *
     * @return Time
     */
    function convertTime($seconds) {
        if ($seconds != "") {
            $h = floor($seconds / 3600);
            $m = floor(($seconds % 3600) / 60);
            $s = $seconds - ($h * 3600) - ($m * 60);
            return sprintf('%02d:%02d:%02d', $h, $m, $s);
        }
    }

    /**
     *
     * @return City Distance
     */
    public function getCityDistance($from_city, $to_city) {
        $data = 0;
        $val = '{"where":{"and": [{"source_city": "' . $from_city . '"},{"destination_city": "' . $to_city . '"}]},"limit":1}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/city-distance-list?&filter=" . $val;
        $resp = $this->get($url);
        $cityJsonData = Json::decode($resp->getBody(), true);
        if (!empty($cityJsonData)) {
            $data = $cityJsonData[0]['distance_km'];
        }
        return $data;
    }

    /**
     *
     * @return Total Distance
     */
    public function getTotalDistance($data) {
        //echo '<pre>';print_r($data);die();
        $distance = 0;
        $estimated_time = 0;
        $days = 0;
        if (count($data) > 0) {
            foreach ($data as $val) {
                $distance += isset($val['distance']) ? $val['distance'] : $distance;
                $estimated_time += isset($val['estimated_time']) ? $val['estimated_time'] : $estimated_time;
                $days += (int) $val['days'];
            }
        }
        $val = ['distance' => $distance, 'estimated_time' => $estimated_time, 'total_days' => $days];
        return $val;
    }

    /**
     *
     * @return City Id
     */
    public function getCityId($city_name) {
        $val = '{"where": {"name": "' . $city_name . '"}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/city?&filter=" . $val;
        $resp = $this->get($url);
        $data = Json::decode($resp->getBody(), true);
        return $data[0]['id'];
    }

    /**
     *
     * @return Calculate No of Days
     */
    public function calculateDays($from_date, $to_date) {
        $date1 = date_create($from_date);
        $date2 = date_create($to_date);
        $diff = date_diff($date1, $date2);
        //$diff->format("%R%a days");
        $days = $diff->format("%a");
        return $days;
    }

    public function calculateDates($fromdate, $todate) {

        $datediff = strtotime($todate) - strtotime($fromdate);
        $datediff = floor($datediff / (60 * 60 * 24));
        for ($i = 0; $i < $datediff + 1; $i++) {
            $dateArr[$i] = date("Y-m-d", strtotime($fromdate . ' + ' . $i . 'day'));
        }
        return $dateArr;
    }

    /**
     *
     * @return Insert Booking Details
     */
    public function insertBookingDetails($booking_id, $posted_bookingdata) {
        $finalArr = [];
        $pickdroparr = array_column($posted_bookingdata, 'pickup_date', 'drop_date');
        $posted_bookingdata = array_combine($pickdroparr, $posted_bookingdata);
        $fromDate = current($pickdroparr);
        $endDate = end($pickdroparr);
        $trip_date_range = $this->calculateDates($fromDate, $endDate);
        $finalDaysTrip = array();
        $day = 1;
        foreach ($trip_date_range as $days) {
            $keyexist = array_search($days, $pickdroparr);
            $finalDaysTrip[$days]['booking_id'] = $booking_id;
            $finalDaysTrip[$days]['pickup_date'] = date('Y-m-d',strtotime($posted_bookingdata[$days]['pickup_date']));
            $finalDaysTrip[$days]['pickup_time'] = $posted_bookingdata[$days]['pickup_time'];
            $finalDaysTrip[$days]['days'] = $day;
            $finalDaysTrip[$days]['created_date'] = date("Y-m-d H:i:s");
            $finalDaysTrip[$days]['ip'] = $_SERVER['REMOTE_ADDR'];
            $finalDaysTrip[$days]['distance'] = $posted_bookingdata[$days]['distance'];
            if (($keyexist) != '') {
                $finalDaysTrip[$days]['pickcity_id'] = $posted_bookingdata[$days]['pickcity_id'];
                $finalDaysTrip[$days]['dropcity_id'] = $posted_bookingdata[$days]['dropcity_id'];
            } elseif (($keyexist) == '') {
                if (count($finalDaysTrip) > 0) {
                    $arrcount = count($finalDaysTrip);
                    $prevoius_date = date('Y-m-d', strtotime('-1 day', strtotime($days)));
                    $samedaytrip = $finalDaysTrip[$prevoius_date];
                    $to_city_id = $samedaytrip['dropcity_id'];
                    $finalDaysTrip[$days]['distance'] = 0;
                    $finalDaysTrip[$days]['pickcity_id'] = $to_city_id;
                    $finalDaysTrip[$days]['dropcity_id'] = $to_city_id;
                }
            }
            $day++;
            $data = $this->outstationModel->addMultiCityData($finalDaysTrip[$days]);
        }
        return $data;
    }

    /**
     *
     * @return ViewModel
     */
    public function countryListAction() {

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

        //$val = '{"where":{"and": [{"city_id": "'.$city.'"},{"area": {"like": "' . $term . '%"}}]},"limit":10}';
        $val = '{"where": {"nationality": {"like": "' . $term . '%"}},"limit":10}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/country?&filter=" . $val;
        $resp = $this->get($url);

        //echo $resp->isSuccess();exit;
        $cityJsonData = Json::decode($resp->getBody(), true);
        if (!empty($cityJsonData)) {
            foreach ($cityJsonData as $value) {
                $data[] = ["label" => $value['nationality'], "value" => $value['id']];
            }
        } else {
            $data[] = ["label" => 'No Record Found'];
        }

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

    /**
     *
     * @return ViewModel
     */
    public function getLatLngAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $term = $postData['term'];
        $googleData = $this->fetchGoogleApiData($term);
        $googleAddressData = Json::decode($googleData);
        if ($googleAddressData->status == 'OK') {
            if (array_key_exists("bounds",$googleAddressData)){
            $north_east_lat = $googleAddressData->results[0]->geometry->bounds->northeast->lat;
            $north_east_lng = $googleAddressData->results[0]->geometry->bounds->northeast->lng;
            $south_west_lat = $googleAddressData->results[0]->geometry->bounds->southwest->lat;
            $south_west_lng = $googleAddressData->results[0]->geometry->bounds->southwest->lng;
            }else{
            $north_east_lat = $googleAddressData->results[0]->geometry->viewport->northeast->lat;
            $north_east_lng = $googleAddressData->results[0]->geometry->viewport->northeast->lng;
            $south_west_lat = $googleAddressData->results[0]->geometry->viewport->southwest->lat;
            $south_west_lng = $googleAddressData->results[0]->geometry->viewport->southwest->lng; 
            }
            $lat = $googleAddressData->results[0]->geometry->location->lat;
            $lng = $googleAddressData->results[0]->geometry->location->lng;
            $data = [
                'north_east_lat' => $north_east_lat,
                'north_east_lng' => $north_east_lng,
                'south_west_lat' => $south_west_lat,
                'south_west_lng' => $south_west_lng,
                'lat' => $lat,
                'lng' => $lng
            ];
            $response = ["status" => true, "data" => $data];
        } else {
            $response = ["status" => false, "data" => ''];
        }
        $view = new JsonModel($response);
        return $view;
    }

    public function getCountryId($country_name) {
        $val = '{"where": {"nationality": "' . $country_name . '"}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/country?filter=" . $val;
        $resp = $this->get($url);
        $countryId = Json::decode($resp->getBody(), true);
        $countryIdData = $countryId[0]['id'];
        return $countryIdData;
    }

    public function getLatLngData($term) {
        $data = [];
        $city = rawurlencode($term);
        $url = $this->apiUrl() . "/city/packageCity?city=" . $city;
        $resp = $this->get($url);
        $cityJsonData = Json::decode($resp->getBody(), true);
        if (isset($cityJsonData['response'][0]['latitude']) && $cityJsonData['response'][0]['latitude'] != "") {
            $cityData = $cityJsonData['response'][0];
            $data = [
                'north_east_lat' => $cityData['north_east_latitude'],
                'north_east_lng' => $cityData['north_east_longitude'],
                'south_west_lat' => $cityData['south_west_latitude'],
                'south_west_lng' => $cityData['south_west_longitude'],
                'lat' => $cityData['latitude'],
                'lng' => $cityData['longitude']
            ];
            $response = ["status" => true, "data" => $data];
        } else {
            $googleData = $this->fetchGoogleApiData($term);
            $googleAddressData = Json::decode($googleData);
            if ($googleAddressData->status == 'OK') {
                if (array_key_exists("bounds",$googleAddressData)){
                $north_east_lat = $googleAddressData->results[0]->geometry->bounds->northeast->lat;
                $north_east_lng = $googleAddressData->results[0]->geometry->bounds->northeast->lng;
                $south_west_lat = $googleAddressData->results[0]->geometry->bounds->southwest->lat;
                $south_west_lng = $googleAddressData->results[0]->geometry->bounds->southwest->lng;
                }else{
                $north_east_lat = $googleAddressData->results[0]->geometry->viewport->northeast->lat;
                $north_east_lng = $googleAddressData->results[0]->geometry->viewport->northeast->lng;
                $south_west_lat = $googleAddressData->results[0]->geometry->viewport->southwest->lat;
                $south_west_lng = $googleAddressData->results[0]->geometry->viewport->southwest->lng; 
                }
                $lat = $googleAddressData->results[0]->geometry->location->lat;
                $lng = $googleAddressData->results[0]->geometry->location->lng;
                $data = [
                    'north_east_lat' => $north_east_lat,
                    'north_east_lng' => $north_east_lng,
                    'south_west_lat' => $south_west_lat,
                    'south_west_lng' => $south_west_lng,
                    'lat' => $lat,
                    'lng' => $lng
                ];
                $response = ["status" => true, "data" => $data];
            } else {
                $response = ["status" => false, "data" => ''];
            }
        }
        return $response;
    }

    public function updateLatLng($data) {
        $data=[
            'city_id'=>$data['pickcity_id'],
            'latitude'=>$data['city_latitude'],
            'longitude'=>$data['city_longitude'],
            'north_east_latitude'=>$data['city_northeast_latitude'],
            'north_east_longitude'=>$data['city_northeast_longitude'],
            'south_west_latitude'=>$data['city_southwest_latitude'],
            'south_west_longitude'=>$data['city_southwest_longitude'],
        ];
        $url = $this->apiUrl() . "/city/updateLatLng";
        $resp = $this->post($url, $data);
        $response = Json::decode($resp->getBody(), true);
        return $response;
    }

    public function currencyConversionAction() {
        $sessionCurrContainer = new Container('vehicleCurrencyData');
        $vehicleList = $sessionCurrContainer->vehicleCurrencyData;
        $sessionVehContainer = new Container('vehicleSearchData');
        $data = $sessionVehContainer->vehicleSearchData;
        //echo '<pre>';print_r($data);die();
        $postData = $this->getRequest()->getPost();
        //echo '<pre>';print_r($postData);die();
        $filter_id = $postData['filter_id'];
        $currData = $this->outstationModel->getCurrencyDetails($filter_id);
        $viewModel = new ViewModel([
                'vehicleList' => $vehicleList,
                'data' => $data,
                'currData' => $currData,
        ]);
        if($data['master_package_type']==4 && $data['module_type']==1){
        $viewModel->setTemplate('outstation/index/round-trip-currency-filtered-vehicle-listing.phtml');
        }else if($data['master_package_type']==4 && $data['module_type']==2){
        $viewModel->setTemplate('outstation/index/multi-city-currency-filtered-vehicle-listing.phtml');
        }else{
        $viewModel->setTemplate('outstation/index/one-way-currency-filtered-vehicle-listing.phtml');
        }
        $viewModel->setTerminal(true);
        return $viewModel;
    }
    
     
     /** @Created_date: 27-AUG-2020
     *  @Created_by : Mohit verma
     *  @Description : Hold booking limited time of period
     *  @return :
     */
    function holdBookingAction(){
        $sessionContainer = new Container('vehicle');
        $paymentData     = $sessionContainer->vehicleData;

        if(isset($sessionContainer->booking_id)){
           $lastInsertId =  $sessionContainer->booking_id;
        }else{
            $sessionUser = new Container('userlogin');
            $user_id = $sessionUser->userData['user_id'];
            $paymentData['user_id'] = $user_id;
            $paymentData['company_id'] = $this->config()->getConfig()->company->companyId;
            $paymentData['booking_status'] = 22;
            $finalData = [];
            $finalData = $paymentData;
        }



         if(!empty($finalData)){
         $finalBooking = $this->finalBookingSubmission($finalData);        
            $lastInsertId = $finalBooking['data']['response']['insertId'];
            $finalData['booking_id'] = $lastInsertId;
            //unset($sessionContainer->vehicleData);
            $sessionContainer->booking_id = $lastInsertId;
            //$this->logStackTrackerData($finalData);
             //$this->redirect()->toRoute('local-hire', ['action' => 'hold-booking']);

           }

            if ($lastInsertId) {
               $bookingparam = ['id'=>$lastInsertId];
               $booking_info = $this->bookingModel->getRecentBookings($bookingparam); 
             
            }


        $viewModel = new ViewModel([
            'booking_info' => $booking_info,
            'paymentData' => $paymentData,
        ]);
        return $viewModel;
    }

}
