<?php

namespace LocalHire\Controller;

use Application\Controller\RestAPIClientController;
use LocalHire\Model\Local;
use Application\Model\CommonModel;
use Dashboard\Model\Booking;
use LocalHire\Form\{
    VehicleSearchForm,
    GuestForm,
    TravellerForm,
    LoginForm
};
use Zend\View\Model\{
    ViewModel,
    JsonModel
};
use Zend\Debug\Debug;
use Zend\Session\Container;
use Zend\Json\Json;

class IndexController extends RestAPIClientController {

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

    private $pickupNow = 2;
    private $pickupLater = 3;
    private $masterPackageType = 1;
    private $pickupAreaMsg = "Please enter valid Pickup Area";
    private $pickupAddressMsg = "Please enter valid Pickup Address";
    private $extras = 'extras';
    private $peakTimeCharge = 'peak_time_charges';

    //private $moduleType  = 1;
    /**
     *
     * @return ViewModel
     */
    public function indexAction() {
        
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $userId = $loginData['user_id'];
        $city_name = '';
        $vehicleTarrifData = '';
        $cityData = $this->getRequest()->getQuery()->toArray();
        $form = new VehicleSearchForm();
        $sessionCityContainer = new Container('vehicleCityData');

        if (!empty($sessionCityContainer->pickup_city)) {
            $pickupCity = $sessionCityContainer->pickup_city;
            $cityId = $sessionCityContainer->city_id;
            $form->get('pickup_city')->setValue($pickupCity);
            $form->get('city_id')->setValue($cityId);
            //$city_name = $cityData['city'];
            $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']);
            }
            $packageList = $this->getPackageListAction($cityId, $this->masterPackageType);
            if (!empty($packageList['data'])) {
                foreach ($packageList['data'] as $val) {
                    $list[$val['local_package_id']] = $val['package_name'];
                }
                $form->get('package_id')->setValueOptions($list);
            }
            $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'];

            $form->get('pickup_city')->setValue($cityData['city']);
            $form->get('city_id')->setValue($cityData['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']);
            }
            $packageList = $this->getPackageListAction($cityData['city_id'], $this->masterPackageType);
            if (!empty($packageList['data'])) {
                foreach ($packageList['data'] as $val) {
                    $list[$val['local_package_id']] = $val['package_name'];
                }
                $form->get('package_id')->setValueOptions($list);
            }
        } else {
            $sessionVehContainer = new Container('vehicleSearchData');
            $data = $sessionVehContainer->vehicleSearchData;
            if ($data != "") {
                if (isset($data['pickcity_id']) && !empty($data['pickcity_id'])) {
                    $form->get('city_id')->setValue($data['pickcity_id']);
                    $city = $data['pickcity_id'];
                } else {
                    $city = $data['city_id'];
                }
                $packageList = $this->getPackageListAction($city, $this->masterPackageType);
                if (!empty($packageList['data'])) {
                    foreach ($packageList['data'] as $val) {
                        $list[$val['local_package_id']] = $val['package_name'];
                    }
                    $form->get('package_id')->setValueOptions($list);
                }
                $form->setData($data);
            }
        }
        
        $form->get('master_package_type')->setValue($this->masterPackageType);
        $request = $this->getRequest();
        if ($request->isPost()) {

            $post = $request->getPost()->toArray();
            $form->setData($request->getPost());
            //pickup-later value=3
            if ($post['local_pickup'] == $this->pickupLater) {
                $form->getInputFilter()->get('pickup_date')->setRequired(true);
                $form->getInputFilter()->get('pickup_time')->setRequired(true);
                $form->get('pickup_later_selected')->setValue(1);
            }
            //pickup-now value=2
            if ($post['local_pickup'] == $this->pickupNow) {
                $form->get('pickup_now_selected')->setValue(0);
            }


            if ($post['city_id'] != "") {
                $packageList = $this->getPackageListAction($post['city_id'], $this->masterPackageType);
                if (!empty($packageList['data'])) {
                    foreach ($packageList['data'] as $val) {
                        $list[$val['local_package_id']] = $val['package_name'];
                    }
                    $form->get('package_id')->setValueOptions($list);
                }
            }

            $city_name = $post['pickup_city'];

            if ($form->isValid()) {

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

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

                //exit;
                if ($pickAreaData->status == 'OK' && $pickupAddressData->status == 'OK') {
                    $getDate = $this->getDate($post['local_pickup'], $post['pickup_date']);
                    $getTime = $this->getTime($post['local_pickup'], $post['pickup_time']);
                    $post['pickup_date'] = $getDate;
                    $post['pickup_time'] = $getTime;
                    $sessionVehContainer = new Container('vehicleSearchData');
                    unset($sessionVehContainer->vehicleSearchData);
                    $sessionVehContainer->vehicleSearchData = $post;

                    //$sessionCityContainer = new Container('vehicleCityData');
                    //unset($sessionCityContainer->pickup_city);
                    //unset($sessionCityContainer->city_id);
                    $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('local-hire', [
                        'action' => 'vehicle-listing'
                            ], ['query' => [
                            'pickup_city' => $post['pickup_city'],
                            'package_id' => $post['package_id'],
                            'pickup_area' => $post['pickup_area'],
                            'pickup_area_value' => $post['pickup_area_value'],
                            'pickup_address' => $post['pickup_address'],
                            'local_pickup' => $post['local_pickup'],
                            'pickup_date' => $post['pickup_date'],
                            'pickup_time' => $post['pickup_time'],
                            'adults' => $post['adults'],
                            'childs' => $post['childs'],
                            'luggages' => $post['luggages'],
                            'no_of_vehicles' => $post['no_of_vehicles'],
                            'agree_terms' => $post['agree_terms'],
                            'city_id' => $post['city_id'],
                            'master_package_type' => $post['master_package_type'],
                            'vehicle_type_id' => $post['vehicle_type_id'],
                            '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 ($pickupAddressData->status != 'OK') {
                        $form->get('pickup_address')->setMessages([$this->pickupAddressMsg]);
                    }
                }
            }
        }

        //This is for Terrif for local Booking
        $bookingTypeId = '';
        if (!empty($cityData)) {
            $vehicleTarrifData = $this->getLocalHireFaresList($cityData['city_id'], $this->masterPackageType);
        }

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

    /**
     *
     * @return ViewModel
     */
    public function vehicleListingAction() {
        $session = new \Zend\Session\Container('userlogin');
        $user_id = isset($session->userData['user_id'])?$session->userData['user_id']:'';
        $sessionVehContainer = new Container('vehicleSearchData');
        $searchCitydata = $sessionVehContainer->vehicleSearchData;
        //echo '<pre>';print_r($data);die();
        $data = [];
        $city_id = "";
        $form = new VehicleSearchForm();
        $guestForm = new GuestForm();
        $data = $this->params()->fromQuery();
        if(empty($data)){        
            $data = $searchCitydata;
        }
        
        $form->setData($data);

        if (isset($data['city_id']) != '') {
            $city_id = $data['city_id'];
        } else {
            $city_id = "";
        }

        if (isset($data['local_pickup']) && $data['local_pickup'] == $this->pickupLater) {
            $form->get('pickup_date')->setValue(date("d-m-Y", strtotime($data['pickup_date'])));
            $form->get('pickup_time')->setValue($data['pickup_time']);
            $form->get('pickup_later_selected')->setValue(1);
        }
        if (isset($data['local_pickup']) && $data['local_pickup'] == $this->pickupNow) {
            $form->get('pickup_now_selected')->setValue(0);
            $form->get('pickup_time')->setValue('');
        }
        $form->get('master_package_type')->setValue($this->masterPackageType);

        $currency_id = 1;
        $data['currency_id']= $currency_id;
        $request = $this->getRequest();
        if ($request->isPost()) {
            //$data = "";
            $data = $request->getPost()->toArray();            
            $form = new VehicleSearchForm();
            $currency_id = (isset($data['currency_id']) && $data['currency_id']!='')?$data['currency_id']:1;
            
            $form->setData($request->getPost());
            //echo '<pre>';print_r($data);die();

            if ($data['local_pickup'] == $this->pickupLater) {
                //$form->get('pickup_date')->setValue($data['pickup_date']);
                //$form->get('pickup_time')->setValue($data['pickup_time']);
                $form->getInputFilter()->get('pickup_date')->setRequired(true);
                $form->getInputFilter()->get('pickup_time')->setRequired(true);
                $form->get('pickup_later_selected')->setValue(1);
            }
            if ($data['local_pickup'] == $this->pickupNow) {
                $form->get('pickup_now_selected')->setValue(0);
            }


            /* if ($data['city_id']!="") {
              echo 'Mohit'.$data['city_id']; //die;
              $packageList = $this->getPackageListAction($data['city_id'], $this->masterPackageType);
              if (!empty($packageList['data'])) {
              foreach ($packageList['data'] as $val) {
              $list[$val['local_package_id']] = $val['package_name'];
              }
              $form->get('package_id')->setValueOptions($list);
              }
              } */

            $getDate = $this->getDate($data['local_pickup'], $data['pickup_date']);
            $getTime = $this->getTime($data['local_pickup'], $data['pickup_time']);
            $data['pickup_date'] = $getDate;
            $data['pickup_time'] = $getTime;
            if ($data['local_pickup'] == $this->pickupLater) {
                $form->get('pickup_date')->setValue(date("d-m-Y", strtotime($data['pickup_date'])));
                $form->get('pickup_time')->setValue($data['pickup_time']);
            }

            if ($form->isValid()) {
                $pickAreaData = $this->fetchGoogleApiData($data['pickup_area']);
                $pickAreaData = Json::decode($pickAreaData);
                $pickupAddressData = $this->fetchGoogleApiData($data['pickup_address']);
                $pickupAddressData = Json::decode($pickupAddressData);
                if ($pickAreaData->status != 'OK') {
                    $form->get('pickup_area')->setMessages([$this->pickupAreaMsg]);
                }if ($pickupAddressData->status != 'OK') {
                    $form->get('pickup_address')->setMessages([$this->pickupAddressMsg]);
                }
                $sessionVehContainer = new Container('vehicleSearchData');
                unset($sessionVehContainer->vehicleSearchData);
                $sessionVehContainer->vehicleSearchData = $data;
            } else {

            }

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

        if ($data['city_id'] != "") {
            $packageList = $this->getPackageListAction($data['city_id'], $this->masterPackageType);
            if (!empty($packageList['data'])) {
                foreach ($packageList['data'] as $val) {
                    $list[$val['local_package_id']] = $val['package_name'];
                }
                $form->get('package_id')->setValueOptions($list);
            }
        }
        $searchvehicleResp = $this->fetchFareDetails($data['city_id'], $data['master_package_type'], $data['pickup_time'], $data['package_id'], $data['adults'], $data['childs'], $data['luggages'],$data['pickup_date'],$currency_id);        
        $vehicleList         =  $searchvehicleResp['response'];
        $leftside_filter_Arr =  $searchvehicleResp['filter_data'];
        //echo '<pre>';print_r($vehicleList);//die();
        //echo '<pre>';print_r($leftside_filter_Arr);die();
        $data['package_name'] = $this->getPackageName($data['package_id']);
        $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,
            '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 fareRulesAction() {
        $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 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
     */

    /**
     *
     * @return ViewModel
     */
    public function filteredVehicleListingAction() {
        $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 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->localModel->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 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 locationAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $term = $postData['term'];
        $city = $postData['city'];
        if ($city != "") {
            $val = '{"where":{"and": [{"city_id": "' . $city . '"},{"area": {"like": "' . $term . '%"}}]},"limit":10}';
        } else {
            $val = '{"where": {"area": {"like": "' . $term . '%"}},"limit":10}';
        }
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/location?&filter=" . $val;
        $resp = $this->get($url);

        $locationJsonData = Json::decode($resp->getBody(), true);
        if (!empty($locationJsonData)) {
            foreach ($locationJsonData as $value) {
                $data[] = [
                    'id' => $value['id'],
                    "label" => $value['area'],
                    "lat" => $value['latitude'],
                    "lng" => $value['longitude'],
                    "value" => $value['latitude'] . ',' . $value['longitude'],
                    'Country' => $value['country_id'],
                    'State' => $value['state_id'],
                    'City' => $value['city_id'],
                    'Zone' => $value['zone']
                ];
            }
        } else {
            $data[] = ["label" => 'Not Exist'];
        }
        $view = new JsonModel($data);
        return $view;
    }

    /**
     *
     * @return ViewModel
     */
    public function locationAddressAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $term = $postData['term'];
        $val = '{"where": {"address": {"like": "' . $term . '%"}},"limit":10}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/address?&filter=" . $val;
        $resp = $this->get($url);

        $locationJsonData = Json::decode($resp->getBody(), true);
        if (!empty($locationJsonData)) {
            foreach ($locationJsonData as $value) {
                $data[] = [
                    "label" => $value['address'],
                ];
            }
        } else {
            $data[] = ["label" => 'Check Google'];
        }
        $view = new JsonModel($data);
        return $view;
    }

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

    /**
     *
     * @return ViewModel
     */
    public function menuAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $city = $postData['city'];
        if ($city == "Noida") {
            $data = ['Local Hire', 'Point To Point'];
        }

        $viewModel = new ViewModel([
            'data' => $data
        ]);

        $viewModel->setTerminal(true);
        return $viewModel;
    }

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

    /**
     *
     * @return ViewModel
     */
    public function travellerAction() {
        $sessionUser = new Container('userlogin');
        $userData = $sessionUser->userData;
        //echo '<pre>';print_r($userData);die();
        $userTypeId = $userData['user_type_id'];
        $userId  = $userData['user_id'];
        
        $sessionContainer = new Container('vehicle');
        $paymentData          = $this->getRequest()->getPost();
      /* 
        $filter_vehicle        = [];
        $filter_vehicle_color = $paymentData['filter_vehicle_color'];       
        $filter_vehicle_model = $paymentData['filter_vehicle_model'];       
        $filter_vehicle_type  = $paymentData['filter_vehicle_type'];   
        $filter_vehicle_name  = $paymentData['filter_vehicle_name'];   
        $filter_fuel_type     = $paymentData['filter_fuel_type'];   
        $filter_amenities     = $paymentData['filter_amenities'];   
        $filter_supplier_name = $paymentData['filter_supplier_name'];   
        
        $filter_vehicle['filter_vehicle_color'] = array_filter(explode(',',$filter_vehicle_color));
        $filter_vehicle['filter_vehicle_model'] = array_filter(explode(',',$filter_vehicle_model));
        $filter_vehicle['filter_vehicle_type']  = array_filter(explode(',',$filter_vehicle_type));
        $filter_vehicle['filter_vehicle_name']  = array_filter(explode(',',$filter_vehicle_name));
        $filter_vehicle['filter_fuel_type']     = array_filter(explode(',',$filter_fuel_type));
        $filter_vehicle['filter_amenities']     = array_filter(explode(',',$filter_amenities));
        $filter_vehicle['filter_supplier_name'] = array_filter(explode(',',$filter_supplier_name));*/
        
//        unset($paymentData['filter_vehicle_color']);       
//        unset($paymentData['filter_vehicle_model']);       
//        unset($paymentData['filter_vehicle_type']);   
//        unset($paymentData['filter_vehicle_name']);   
//        unset($paymentData['filter_fuel_type']);  
//        unset($paymentData['filter_amenities']);
//        unset($paymentData['filter_supplier_name']);
        
        //$paymentData['filter_data'] = json_encode($filter_vehicle,JSON_FORCE_OBJECT);
        $sessionContainer->vehicleData = $paymentData;

        $sessionContainer1 = new Container('vehiclePayData');
        $payData = $sessionContainer1->vehiclePaymentData;
        $vehcilePaymentData = $payData[$paymentData['vehicle_id']];


        $currencyType = $paymentData['currency_type'];
        $currencyData = $this->localModel->getCurrencyDetails($currencyType);        
        
        
        $company_details = $this->localModel->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->localModel->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,
            'currencyData' => $currencyData,
            'captchaKey' => $this->config()->getConfig()->googleCaptcha->siteKey,
            'userCanHoldBooking'=>$userCanHoldBooking,
            'company_logo'  =>  (isset($companyLogoPath))?$companyLogoPath:'',
            'creditBalance' =>  $creditBalance
            
        ]);
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
    public function travellerSaveAction() {
        $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->localModel->getCurrencyDetails($currencyType);
        $currIcon = $currData['fa_icon'];

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

        if ($paymentData['local_pickup'] == 2) {  // Pick up Now Status //
            $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) {  // Pick up Later Status //
            $getDate = $this->getDate($paymentData['local_pickup'], $paymentData['pickup_date']);
            $paymentData['pickup_date'] = date("Y-m-d", strtotime($getDate));
            $getTime = $this->getTime($paymentData['local_pickup'], $paymentData['pickup_time']);
            $paymentData['pickup_time'] = $getTime;
        }

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

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

        $data = $this->getStateCountry($paymentData['city_id']);


        $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['pickup_city'] = $paymentData['city_id'];
        $paymentData['drop_date'] = date("Y-m-d", strtotime($getDate));
        $paymentData['drop_time'] = $getTime;
        $paymentData['drop_area'] = '';
        $paymentData['drop_address'] = '';
        $paymentData['drop_country'] = '';
        $paymentData['drop_state'] = '';
        $paymentData['drop_city'] = '';
        $paymentData['drop_landmark'] = '';
        $paymentData['drop_latitude'] = '';
        $paymentData['drop_longitude'] = '';
        $paymentData['drop_zone'] = '';
        $paymentData['device_type'] = "Web";
        $paymentData['flight_number'] = '';
        $paymentData['airport'] = '';


        $sessionContainer1 = new Container('vehiclePayData');
        $payData = $sessionContainer1->vehiclePaymentData;
        $vehcilePaymentData = $payData[$paymentData['vehicle_id']];
        //echo '<pre>';print_r($vehcilePaymentData);//die();
        //$vehcilePaymentData = array_filter($vehcilePaymentData);

        //////////// Session Data /////////////////

        $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->localModel->getCurrencyDetails($currencyType);
        $company_details = $this->localModel->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->localModel->checkCreditLimit($userId);            
            //echo '<pre>';print_r($post);die();
            $total_booking_price = $paymentData['total_price'];
            /*if ($post['g-recaptcha-response'] == '') {
                $recaptcha_error = 'Please check the captcha';
            }*/
            $balance_error = '';
            if($post['voucher']!='' && ($creditBalance < $total_booking_price)){
                   $balance_error = 'Credit Balance is not available for create voucher'; 
            }
            
            if ($form->isValid() && $balance_error=='') {
                //echo '<pre>';print_r($post);die();
                
                
                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;
                //echo '<pre>';print_r($userArray);die();
                if ($post['book_vehicle_user'] == 1) {
                    $clientData = $this->getUserId($userArray);
                    $paymentData['client_id'] = $clientData['data']['user_id'];
                } else {
                    $paymentData['client_id'] = $guest_id;
                }
                //die;
                $paymentData['vehicle_type_id'] = $vehcilePaymentData['vehicle_type_id'];
                //echo $paymentData['client_id'];
                //exit;
                //echo "Mohit";
                //Debug::dump($paymentData); //exit;
                //echo "Jain";
                $finalData = [];
                //$finalData = array_merge($paymentData, $post, $vehcilePaymentData);
                $finalData = array_merge($vehcilePaymentData, $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('local-hire', ['action' => 'login']);
                } else {
                     if($post['hold_booking']!=''){                         
                        $this->redirect()->toRoute('local-hire', ['action' => 'hold-booking']);
                    }else if($post['voucher']!=''){
                        $this->redirect()->toRoute('local-hire', ['action' => 'voucher']);
                    }
                    else{
                        $this->redirect()->toRoute('local-hire', ['action' => 'checkout']);
                    }
                }
            }
        }
        $viewModel = new ViewModel([
            'form' => $form,
            'paymentData' => $paymentData,
            //'error' => $recaptcha_error,
            'balance_error' => $balance_error,
            'currIcon' => $currIcon,
            //'captchaKey' => $this->config()->getConfig()->googleCaptcha->siteKey,            
            'vehcilePaymentData' => $vehcilePaymentData,
            'currencyData' => $currencyData,
            'userCanHoldBooking'=>$userCanHoldBooking,
            'company_logo' =>  (isset($companyLogoPath))?$companyLogoPath:''
        ]);
        $viewModel->setTemplate('local-hire/index/traveller.phtml');
        return $viewModel;
    }

    public function loginAction() {
        $sessionContainer = new Container('vehicle');
        $paymentData = $sessionContainer->vehicleData;

        $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('local-hire', ['action' => 'checkout']);
                } else {
                    $errorMsg = $data['data']['responsedata']['error'];
                }
                //Debug::dump($data);
                //exit;
            }
        }
        $viewModel = new ViewModel([
            'form' => $form,
            'paymentData' => $paymentData,
            'errorMsg' => $errorMsg
        ]);
        $viewModel->setTemplate('local-hire/index/book-now.phtml');
        return $viewModel;
    }

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

        $currencyType = $paymentData['currency_type'];
        $currData = $this->localModel->getCurrencyDetails($currencyType);
        $currIcon = $currData['fa_icon'];

        $request = $this->getRequest();
        if ($request->isPost()) {
           //  $hold_booking_id   = isset($sessionContainer->booking_id)?$sessionContainer->booking_id:'';
           //  $lastInsertId      = isset($sessionContainer->booking_id)?$sessionContainer->booking_id:'';
            $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';
            }

            if (!empty($post['wallet_amount'])) {

                $walletStatus = 1;
                if ($walletData < $post['booking_amt_paid']) {
                    $walletAmt = 0;
                    $post['booking_amt_paid'] = $post['booking_amt_paid'] - $walletData;
                    $paymentData['wallet_data'] = $walletData;
                    $paymentStatus = 1;
                    $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 {

                $walletStatus = 0;
                $walletAmt = $walletData;
                $paymentData['wallet_data'] = 0;
                $paymentStatus = 1;
                $post['charge_type'] = 1;
            }

            $paymentData['wallet_updated_amount'] = $walletAmt;
            $paymentData['company_id'] = $this->config()->getConfig()->company->companyId;
            $currencyType = $paymentData['currency_type'];
            $currData = $this->localModel->getCurrencyDetails($currencyType);
            $paymentData['currency_code'] = $currData['code'];
            $paymentData['exchange_rate'] = $currData['exchange_rate'];

            $finalData = [];
            $finalData = array_merge($paymentData, $post);

            //echo '<pre>';print_r($finalData);die();
            /* if($hold_booking_id==''){ */
            $this->updateLatLng($finalData);
            $finalBooking = $this->finalBookingSubmission($finalData);
            $lastInsertId = $finalBooking['data']['response']['insertId'];
            //$companyInitial = $this->config()->getConfig()->company->companyInitial;
            $finalData['booking_id'] = $lastInsertId;
            /*}else{
                 $finalData['booking_id'] = $lastInsertId;
            } */

            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->localModel->getBookingInfoById($lastInsertId);
                $bookingRefNo = $bookingData[0]['ref'];
                $this->logStackTrackerData($finalData);

                $smsparam = [
                    'template_name' => 'booking',
                    'mobile' => $login_mobile,
                    'user_name' => 'User',
                    'booking_ref_no' => $bookingRefNo,
                    'pickup_time' => $finalData['pickup_date'] . ' ' . $finalData['pickup_time'],
                    'estimated_price' => $finalData['total_charge']
                ];

                $this->sendSMS($smsparam);

                $smsparamTraveller = [
                    'template_name' => 'booking',
                    'mobile' => $finalData['mobile'],
                    'user_name' => 'User',
                    'booking_ref_no' => $bookingRefNo,
                    'pickup_time' => $finalData['pickup_date'] . ' ' . $finalData['pickup_time'],
                    'estimated_price' => $finalData['total_charge']
                ];

                $this->sendSMS($smsparamTraveller);

                $sendMailUser = [
                    'user_name' => $sessionUser->userData['first_name'],
                    'user_email' => $login_email,
                    'booking_ref_no' => $bookingRefNo,
                    '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,
                        '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,
            'currIcon' => $currIcon
        ]);
        return $viewModel;
    }

    /*
      public function travellerSaveOldAction() {
      $guest_id = "";
      $sessionContainer = new Container('vehicle');
      $paymentData = $sessionContainer->vehicleData;
      //print_r($paymentData);
      //////////// 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;
      }

      $twentyFivePercent = ($paymentData['total_charge'] * 25 / 100);
      $fiftyPercent = ($paymentData['total_charge'] * 50 / 100);
      $paymentData['twenty_five_percent'] = $twentyFivePercent;
      $paymentData['fifty_percent'] = $fiftyPercent;


      $pickAreaData = $this->fetchGoogleApiData($paymentData['pickup_area']);
      $pickAreaData = Json::decode($pickAreaData);


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

      $data = $this->getStateCountry($paymentData['city_id']);

      //echo $paymentData['pickup_address']= $paymentData['pickup_address']; die;
      $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_time'] = '';
      $paymentData['drop_area'] = '';
      $paymentData['drop_address'] = '';
      $paymentData['drop_country'] = '';
      $paymentData['drop_state'] = '';
      $paymentData['drop_city'] = '';
      $paymentData['drop_landmark'] = '';
      $paymentData['drop_latitude'] = '';
      $paymentData['drop_longitude'] = '';
      $paymentData['drop_zone'] = '';
      $paymentData['device_type'] = "Web";
      $paymentData['flight_number'] = '';
      $paymentData['airport'] = '';


      $sessionContainer1 = new Container('vehiclePayData');
      $payData = $sessionContainer1->vehiclePaymentData;
      $vehcilePaymentData = $payData[$paymentData['vehicle_id']];
      $vehcilePaymentData = array_filter($vehcilePaymentData);

      //////////// Session Data /////////////////

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


      $form = new TravellerForm();
      $request = $this->getRequest();
      if ($request->isPost()) {
      $form->setData($request->getPost());
      if ($form->isValid()) {
      $post = $request->getPost()->toArray();
      //print_r($post);
      if ($post['booking_amt_percentage'] == '25') {
      $post['booking_amt_paid'] = $twentyFivePercent;
      $post['booking_amt_balance'] = $paymentData['total_charge'] - $twentyFivePercent;
      } else if ($post['booking_amt_percentage'] == '50') {
      $post['booking_amt_paid'] = $fiftyPercent;
      $post['booking_amt_balance'] = $paymentData['total_charge'] - $fiftyPercent;
      } else {
      $post['booking_amt_paid'] = $paymentData['total_charge'];
      $post['booking_amt_balance'] = 0;
      }

      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'];
      $guestData = $this->getUserId($guestArray);
      $paymentData['user_id'] = $guestData['data']['responsedata'][0]['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['created_date'] = date('Y-m-d h:i:s');

      $clientData = $this->getUserId($userArray);
      $paymentData['client_id'] = $clientData['data']['responsedata'][0]['user_id'];

      //exit;
      $finalData = [];
      $finalData = array_merge($paymentData, $post, $vehcilePaymentData);
      //$data = json_encode($finalData);
      $finalBooking = $this->finalBookingSubmission($finalData);
      $lastInsertId = $finalBooking['data']['response']['insertId'];
      $companyInitial = $this->config()->getConfig()->company->companyInitial;
      if (!empty($lastInsertId)) {
      $bookingRefNo = $this->getBookingRefNo($lastInsertId, $companyInitial);
      $updateDataArray['reference_number'] = $bookingRefNo['generated'];
      $updateDataArray['booking_id'] = $lastInsertId;
      $updated = $this->updateBookingNo($updateDataArray);
      //$msg_sku='booking';
      //$this->getSmsTemplate($msg_sku);
      $atomPayment = $this->atomPaymentGateway($finalData, $bookingRefNo['generated']);
      }
      //Debug::dump($updated);
      exit;
      }
      }

      $viewModel = new ViewModel([
      'form' => $form,
      'paymentData' => $paymentData
      ]);
      $viewModel->setTemplate('local-hire/index/traveller.phtml');
      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) {
            $date = date("Y-m-d H:i:s");
            $pickupTime = date("H:i:s", strtotime($date."+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 ViewModel
     */
    public function getCityListOldAction() {
        $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;
    }

    /**
     *
     * @return ViewModel
     */
    public function getCityListAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $term = $postData['term'];
        $url = $this->apiUrl() . "/city/packageCity?city_name=" . $term . '&master_package_id=' . $this->masterPackageType;
        $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 getAjaxPackageListAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $city_id = $postData['city_id'];
        $package_id = $postData['master_package_type'];
        $url = $this->apiUrl() . "/local_hire/package?city_id=" . $city_id . "&package_id=" . $package_id;
        $resp = $this->get($url);
        $packageJsonData = Json::decode($resp->getBody(), true);
        if (!empty($packageJsonData['package'])) {
            foreach ($packageJsonData['package'] as $value) {
                if ($value['name'] != null) {
                    $data[] = ["local_package_id" => $value['local_pkg_id'], "package_name" => $value['name']];
                }
            }
            $response = ["status" => true, "data" => $data];
        } else {
            $response = ["status" => false];
        }
        $view = new JsonModel($response);
        return $view;
    }

    public function getPackageListAction($city_id, $package_id) {
        $data = [];
        $url = $this->apiUrl() . "/local_hire/package?city_id=" . $city_id . "&package_id=" . $package_id;
        $resp = $this->get($url);
        $packageJsonData = Json::decode($resp->getBody(), true);
        if (!empty($packageJsonData['package'])) {
            foreach ($packageJsonData['package'] as $value) {
                $data[] = ["local_package_id" => $value['local_pkg_id'], "package_name" => $value['name']];
            }
            $response = ["status" => true, "data" => $data];
        } else {
            $response = ["status" => false];
        }
        return $response;
    }

    public function getLocalFareListAction() {
        $vehiclePackages = [];
        $vehicleTariff = [];
        $postData = $this->getRequest()->getPost();
        $city_id = $postData['city_id'];
        $package_id = $postData['master_package_type'];
        $city_name = $postData['city_name'];
        $url = $this->apiUrl() . "/local_hire/package?city_id=" . $city_id . "&package_id=" . $package_id;
        $resp = $this->get($url);
        $packageJsonData = Json::decode($resp->getBody(), true);
        if (!empty($packageJsonData['package'])) {
            foreach ($packageJsonData['package'] as $value) {
                $vehiclePackages[] = ["local_package_id" => $value['local_package_id'], "package_name" => $value['name'], "extra_hr" => $value['hrs'], "extra_km" => $value['km'], "price" => $value['price']];
            }
        }

        $url1 = $this->apiUrl() . "/local_hire/packageFareDetail?city_id=" . $city_id . "&package_id=" . $package_id;
        $resp1 = $this->get($url1);
        $packageJsonData1 = Json::decode($resp1->getBody(), true);
        if (!empty($packageJsonData1['packageFareDetail'])) {
            foreach ($packageJsonData1['packageFareDetail'] as $value1) {
                $vehicleTariff[] = ["vehicle_type" => $value1['vehicle_type'], "vehicle_image" => $value1['vehicle_image'], "vehicle_type_id" => $value1['master_vehicle_type_id']];
            }
        }
        //Debug::dump($vehiclePackages);
        //Debug::dump($vehicleTariff); exit;
        $viewModel = new ViewModel([
            'vehiclePackages' => $vehiclePackages,
            'vehicleTariff' => $vehicleTariff,
            'city_name' => $city_name
        ]);
        $viewModel->setTemplate('local-hire/index/local-hire-tariff.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function getLocalHireFaresList($city_id, $package_id) {
        $vehiclePackages = [];
        $vehicleTariff = [];
        $url = $this->apiUrl() . "/local_hire/package?city_id=" . $city_id . "&package_id=" . $package_id;
        $resp = $this->get($url);
        $packageJsonData = Json::decode($resp->getBody(), true);
        if (!empty($packageJsonData['package'])) {
            foreach ($packageJsonData['package'] as $value) {
                $vehiclePackages[] = ["local_package_id" => $value['local_package_id'], "package_name" => $value['name'], "extra_hr" => $value['hrs'], "extra_km" => $value['km'], "price" => $value['price']];
            }
        }

        $url1 = $this->apiUrl() . "/local_hire/packageFareDetail?city_id=" . $city_id . "&package_id=" . $package_id;
        $resp1 = $this->get($url1);
        $packageJsonData1 = Json::decode($resp1->getBody(), true);
        if (!empty($packageJsonData1['packageFareDetail'])) {
            foreach ($packageJsonData1['packageFareDetail'] as $value1) {
                $vehicleTariff[] = ["vehicle_type" => $value1['vehicle_type'], "vehicle_image" => $value1['vehicle_image'], "vehicle_type_id" => $value1['master_vehicle_type_id']];
            }
        }
        $data = [
            'vehiclePackages' => $vehiclePackages,
            'vehicleTariff' => $vehicleTariff
        ];
        return $data;
    }

    public function fetchFareDetails($city_id, $master_package_type, $pickupTime, $package_id, $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');
        
        $stateCountry = $this->getStateCountry($city_id);
        if(!empty($stateCountry)){
            $state_id = $stateCountry['response'][0]['state_id'];
            $country_id = $stateCountry['response'][0]['country_id'];
        }else{
            $state_id = "";
            $country_id = "";
        }

        $response = [];
        $data = [
            'city_id' => $city_id,
            'state_id' => $state_id,
            'country_id' => $country_id,
            'master_package_id' => $master_package_type,
            'local_package_id' => $package_id,
            'pickup_time' => $pickupTime,
            '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],
        ];
        //echo '<pre>';print_r($data);die();
        $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'=>$response,'filter_data'=>$filter_data];
    }

    public function fetchFareDetails1($city_id, $master_package_type, $pickupTime, $package_id) {
        $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,
            'local_package_id' => $package_id,
            'pickup_time' => $pickupTime,
            '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);
        //echo '<pre>';print_r($packageFareData);die();
        if (!empty($packageFareData)) {
            if ($packageFareData['responsedata']['status'] == "success") {
                $response = $packageFareData['responsedata']['data'];
                foreach ($response 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;
    }

    public function fetchFareDetailsOld($city_id, $master_package_type, $pickupTime, $package_id) {
        $sessionUserContainer = new Container('userlogin');
        $userData = $sessionUserContainer->userData;
        //echo '<pre>';print_r($userData);die();
        $sessionContainer = new Container('vehiclePayData');
        $response = [];
        $url = $this->apiUrl() . "/local_hire/packageFareDetail?city_id=" . $city_id . "&package_id=" . $master_package_type;
        $resp = $this->get($url);
        $packageFareData = Json::decode($resp->getBody(), true);
        //Debug::dump($packageFareData); exit;
        //$url_package = $this->apiUrl() . "/local-package/" . $package_id;
        $url_package = $this->apiUrl() . "/local_hire/package?city_id=" . $city_id . "&package_id=" . $master_package_type . "&local_package_id=" . $package_id;
        $resp_package = $this->get($url_package);
        $packageData = Json::decode($resp_package->getBody(), true);
        $packageData = $packageData['package'][0];
        //Debug::dump($packageData); exit;

        $gradeArray = [
            'searchCity' => $city_id,
            'userCity' => $userData['city_id'],
            'userTypeId' => $userData['user_type_id'],
            'userGender' => $userData['gender'],
        ];
        $grade = $this->localModel->getMarkupGrade($gradeArray);
        $markupData = $this->localModel->getCompanyMarkup($this->config()->getConfig()->company->companyId, $city_id, $master_package_type, $grade);
        //$userMarkupData = $this->localModel->getUserMarkup($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=[];
//        }



        $status = 0;
        $min_pkg_km = '';
        $min_pkg_hrs = '';
        $peak_fare = 0;
        $night_charges = 0;
        $extra_charges = 0;

        if (!empty($packageData)) {
            $min_pkg_km = $packageData['km'];
            $min_pkg_hrs = $packageData['hrs'];
            $totalbill = $packageData['price'];
            $ignore_hrs = $packageData['hrs'];
            $ignore_km = $packageData['km'];
            $minimumCharge = $totalbill;
            $distance = $packageData['km'];
        } else {
            $status = 1;
            $ignore_hrs = 0;
            $ignore_km = 0;
            $minimumCharge = 0;
            $distance = 0;
        }
        $estimated_time = $this->convertTime($ignore_hrs);
        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, $markupData);

                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->localModel->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 */

                /* 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->localModel->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);
                //echo $totalbill;

                $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,
                    "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,
                    "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,
                    "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,
                    "estimated_distance" => $distance,
                    "approx_waiting_charge" => '',
                    "appox_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;
    }

    public function fetchCalculationType($package_id, $calculationType, $baseVehicleId, $minimumCharge, $ignore_hrs, $ignore_km, $status, $distance, $markupData) {
        $datam1 = [];
        $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);

        if ($status == 1) {
            if ($calculationType == 1) {
                $ignore_hrs = 0;
                $ignore_km = isset($fareData[0]['minimum_distance']) ? $fareData[0]['minimum_distance'] : 0;
                $minimumCharge = isset($fareData[0]['minimum_charge']) ? $fareData[0]['minimum_charge'] : 0;
            } 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'] : 0;
            } elseif ($calculationType == 3) {
                $ignore_hrs = isset($fareData[0]['minimum_hrs']) ? $fareData[0]['minimum_hrs'] : 0;
                $ignore_km = isset($fareData[0]['minimum_distance']) ? $fareData[0]['minimum_distance'] : 0;
                $minimumCharge = isset($fareData[0]['minimum_charge']) ? $fareData[0]['minimum_charge'] : 0;
            } elseif ($calculationType == 4) {
                $ignore_hrs = 0;
                $ignore_km = isset($fareData[0]['minimum_distance']) ? $fareData[0]['minimum_distance'] : 0;
                $minimumCharge = isset($fareData[0]['minimum_charge']) ? $fareData[0]['minimum_charge'] : 0;
            }
        }

        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 ($calculationType == 1) {
            if ($distance > $ignore_km) {
                $ExtraKM = $distance - $ignore_km;
                $ExtraFare = $ExtraKM * (isset($fareData[0]["per_km_charge"]) ? $fareData[0]["per_km_charge"] : 0);
                $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) * (isset($fareData[0]["per_hr_charge"]) ? $fareData[0]["per_hr_charge"] : 0);
                $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) * (isset($fareData[0]["per_km_charge"]) ? $fareData[0]["per_km_charge"] : 0);
            }
            if ($travel_hrs > $ignore_hrs) {
                $hourlyRate = 0;
            } else {
                $hourlyRate = $travel_hrs - $ignore_hrs;
                $rate_per_min = (isset($fareData[0]["per_hr_charge"]) ? $fareData[0]["per_hr_charge"] : 0) / 60;
                $hourlyRate = $hourlyRate * $rate_per_min;
            }
            $EstimatedPrice = $distanceRate + $hourlyRate + $minimumCharge;
            $datam1['min_distance'] = $ignore_km;
            $datam1['minimum_charge'] = $minimumCharge;
            $datam1['per_km_charge'] = isset($fareData[0]["per_km_charge"]) ? $fareData[0]["per_km_charge"] : 0;
            $datam1['per_hr_charge'] = isset($fareData[0]["per_hr_charge"]) ? $fareData[0]["per_hr_charge"] : 0;
        } elseif ($calculationType == 4) {
            if ($distance > $ignore_km) {
                $ExtraKM = $distance - $ignore_km;
                $ExtraFare = $ExtraKM * (isset($fareData[0]["per_km_charge"]) ? $fareData[0]["per_km_charge"] : 0);
                $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;
        }

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

    public function getPackageName($package_id) {
        $data = '';
        $url = $this->apiUrl() . "/local_hire/getlocalpackage?local_package_id=" . $package_id;
        $resp = $this->get($url);
        $data = Json::decode($resp->getBody(), true);
        if (!empty($data['package'])) {
            return $data['package'][0]['name'];
        } else {
            return $data;
        }
    }

    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 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 convertTime($time) {
        $seconds = $time * 3600;
        $h = floor($seconds / 3600);
        $m = floor(($seconds % 3600) / 60);
        $s = $seconds - ($h * 3600) - ($m * 60);
        return sprintf('%02d:%02d:%02d', $h, $m, $s);
    }

    public function getStateCountry($city_id) {
        $data = [];
        $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 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 checkPayment($walletStatus, $paymentStatus, $paymentData, $bookingRefNo, $bookingId) {
        if ($paymentStatus == 1) {
            $atomPayment = $this->atomPaymentGateway($paymentData, $bookingRefNo, $walletStatus);
        } else {
            if ($walletStatus == 1) {
                $data['user_id'] = $paymentData['user_id'];
                $data['wallet_amount'] = $paymentData['wallet_updated_amount'];
                $resp = $this->getWalletAmtUpdate($data);

                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('local-hire', ['action' => 'success', 'param' => $bookingRefNo]);
        }
    }

    public function atomPaymentGateway($paymentData, $bookingRefNo, $walletStatus) {
        $data = []; 
        $sessionContainer = new Container('vehicle');
        $paymentData = $sessionContainer->vehicleData;
        
        $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['paymentData'] = $paymentData;

        $data['ru'] = $this->config()->getConfig()->base_url->url . "local-hire/payment-response/" . $walletStatus;
        //Debug::dump(json_encode($data));
        $resp = $this->post($url, $data);
        $response = Json::decode($resp->getBody(), true);


        if ($response['response']['status'] == true) {
            $this->redirect()->toUrl($response['response']['url']);
        }
    }

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

        $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);
       
        $sessionContainer = new Container('vehicle');
        $paymentData = $sessionContainer->vehicleData;

        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('local-hire', ['action' => 'success', 'param' => $response['response']['data']['mer_txn']]);
        } else {
            $this->redirect()->toRoute('local-hire', ['action' => 'fail', 'param' => $response['response']['data']['mer_txn']]);
        }
    }

    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 userLogin($data) {
        $url = $this->apiUrl() . "/user/login";
        $resp = $this->post($url, $data);
        $response = Json::decode($resp->getBody(), true);
        //Debug::dump($response);
        //exit;
        $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 getSmsTemplate($msg_sku) {
      $val = '{"where": {"msg_sku": "' . $msg_sku . '"}}';
      $val = rawurlencode($val);
      $smsTemplate = $this->apiUrl() . "/sms_template?&filter=" . $val;
      $respSmsTemplate = $this->get($smsTemplate);
      if ($respSmsTemplate->isSuccess()) {
      $response = ["status" => true, "data" => Json::decode($respSmsTemplate->getBody(), true)];
      } else {
      $response = ["status" => false, "data" => ""];
      }
      return $response;
      } */

    public function getSmsApi($data) {
        $mobileNumber = $data['mobile_no'];
        $message = $data['message'];
        //$val1=$this->checkSms();

        $val = '{"where": {"active": "1"}}';
        $val = rawurlencode($val);
        $smsTemplate = $this->apiUrl() . "/sms_apis?&filter=" . $val;
        $respSmsTemplate = $this->get($smsTemplate);
        $smsData = Json::decode($respSmsTemplate->getBody(), true);
        //Debug::dump($smsData); die;
        foreach ($smsData as $key => $sms_api) {
            if ($sms_api['api_title'] == "ValueFirst") {
                $api_base_uri = $sms_api['api_base_uri'];
                $api_username = $sms_api['api_username'];
                $api_password = $sms_api['api_password'];
                $api_sender_id = $sms_api['api_sender_id'];
                $url = "$api_base_uri?username=$api_username&password=$api_password&to=91$mobileNumber&from=$api_sender_id&udh=&text=$message&dlr-mask=19&dlr-url";
                $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);
                if ($result === FALSE) {
                    die('Curl failed: ' . curl_error($curl_handle));
                }
                curl_close($curl_handle);
                // echo $result;
            } elseif ($result != 'Sent.' && $sms_api['api_title'] == "ACLMobile") {

                $api_base_uri = $sms_api['api_base_uri'];
                $api_username = $sms_api['api_username'];
                $api_password = $sms_api['api_password'];
                $api_sender_id = $sms_api['api_sender_id'];
                $url = "$api_base_uri?userId=$api_username&pass=$api_password&appid=$api_username&subappid=$api_username&msgtype=1&contenttype=1&selfid=true&to=91$mobileNumber&from=$api_sender_id&dlrreq=true&text=$message&alert=1";
                $curl_handle = curl_init();
                curl_setopt($curl_handle, CURLOPT_URL, $url);
                curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
                curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
                $result = curl_exec($curl_handle);
                if ($result === FALSE) {
                    die('Curl failed: ' . curl_error($curl_handle));
                }
                curl_close($curl_handle);
            }
        }
    }

    public function checkSms() {
        $url = "https://push3.maccesssmspush.com/servlet/com.aclwireless.pushconnectivity.listeners.ConfigurationListener?action=prepaid&userid=helloalt&pass=helloalt&appid=helloalt&subappid=helloalt";
        $curl_handle = curl_init();
        curl_setopt($curl_handle, CURLOPT_URL, $url);
        curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 2);
        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);
        //$aa= json_encode($buffer);
        $result = explode('#', $result);
        $val = $result[0];
        return $val;
    }

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

    /**
     *
     * @return ViewModel
     */
    public function countryListAction() {
        $request = $this->getRequest();
        $postdata = $request->getPost();
        $term = $postdata['term'];
        $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') {
          $lat = $googleAddressData->results[0]->geometry->location->lat;
          $lng = $googleAddressData->results[0]->geometry->location->lng;
          $response = ["status" => true, "lat" => $lat, "lng" =>$lng];
          }else{
          $response = ["status" => false, "lat" => '', "lng" =>''];
          }
          $view = new JsonModel($response);
          return $view; */
        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 fetchCurrencyConversion() {
        $url = "https://api.exchangeratesapi.io/latest?base=INR";
        $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 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);
            //echo '<pre>';print_r($googleAddressData);die();
            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['city_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 filterDataAction() {
        $sessionContainer = new Container('vehiclePayData');
        $payData = $sessionContainer->vehiclePaymentData;
        //Debug::dump($payData); exit;
        $data = [];
        $postData = $this->getRequest()->getPost();
        //echo $postData['filter_id']; die;
        $filter_id = $postData['filter_id'];
        $filter_id = '1,2';
        //$val    =   array_search($postData['filter_id'], array_column($payData, 'vehicle_type_id'));
        $new = array_filter($payData, function ($var) use ($filter_id) {
            return ($var['vehicle_type_id'] == $filter_id);
        });
        echo '<pre>';
        print_r($new);
        die();

        $vehicleId = $postData['vehicle_id'];
        $data = $payData[$vehicleId];
        //Debug::dump($data); exit;
        $view = new JsonModel($data);
        return $view;
    }

    /* Created Date 11-11-2019 */

    public function currencyConversionAction() {
        $sessionCurrContainer = new Container('vehicleCurrencyData');
        $vehicleList = $sessionCurrContainer->vehicleCurrencyData;
        $sessionVehContainer = new Container('vehicleSearchData');
        $data = $sessionVehContainer->vehicleSearchData;
        $postData = $this->getRequest()->getPost();
        //echo '<pre>';print_r($postData);die();
        $filter_id = $postData['filter_id'];
        $currData = $this->localModel->getCurrencyDetails($filter_id);
        $viewModel = new ViewModel([
            'vehicleList' => $vehicleList,
            'data' => $data,
            'currData' => $currData,
        ]);
        $viewModel->setTemplate('local-hire/index/currency-filtered-vehicle-listing.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

     /** @Created_date: 4-July-2020
     * @description : Get fare cancellation rule policy
     * @return
     */
    public function cancellationRulesAction() {
        $sessionContainer = new Container('vehiclePayData');
        $payData = $sessionContainer->vehiclePaymentData;
        $data = [];
        $val = $this->params()->fromQuery();
        $data = $payData[$val['id']];
        $viewModel = new ViewModel([
            'cancellation_rule' => $data['cancellation_fare_rule']
        ]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /** @Created_date: 6-July-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;
    }
    
    
    public function voucherAction(){
        $sessionContainer = new Container('vehicle');
        $paymentData     = $sessionContainer->vehicleData;
        
        $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'] = 1;
        $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);
           $bookingparam = ['id'=>$lastInsertId];
           $booking_info = $this->bookingModel->getRecentBookings($bookingparam);
           $booking_info_detail = $booking_info[0];
           $booking_ref_no = $booking_info_detail['ref'];
           
            $data['user_id'] = $paymentData['user_id'];
            $data['booking_id'] = $lastInsertId;
            $data['booking_transaction_no'] =$booking_ref_no;
            $data['amount'] = $paymentData['total_price'];
            $data['payment_response_id'] = $lastInsertId;
            $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);
           
           
           $this->redirect()->toRoute('local-hire', ['action' => 'success', 'param' => $booking_ref_no]);
           }


   
    }

    /* Get auto expiry date from travel date
    function getAutoExpiryDate($pickup_date){
        $current_date = date('Y-m-d');
        $pickup_date = $pickup_date;

    }*/

}
