<?php

namespace PointToPoint\Controller;

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

class IndexController extends RestAPIClientController {

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

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

    /**
     *
     * @return ViewModel
     */
    public function indexAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $userId = $loginData['user_id'];
        $city_name = '';
        $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);
            $boundData = $this->getLatLngData($pickupCity);
            //echo '<pre>';print_r($boundData);die();
            if ($boundData['status'] == 1) {
                $form->get('city_latitude')->setValue($boundData['data']['lat']);
                $form->get('city_longitude')->setValue($boundData['data']['lng']);
                $form->get('city_northeast_latitude')->setValue($boundData['data']['north_east_lat']);
                $form->get('city_northeast_longitude')->setValue($boundData['data']['north_east_lng']);
                $form->get('city_southwest_latitude')->setValue($boundData['data']['south_west_lat']);
                $form->get('city_southwest_longitude')->setValue($boundData['data']['south_west_lng']);
            }
            $sessionVehContainer = new Container('vehicleSearchData');
            $data = $sessionVehContainer->vehicleSearchData;
            if($data!=""){
                $form->setData($data);
            }
        }

        if (!empty($cityData)) {
            //$sessionVehContainer = new Container('vehicleSearchData');
            //unset($sessionVehContainer->vehicleSearchData);
            $sessionCityContainer->pickup_city = $cityData['city'];
            $sessionCityContainer->city_id = $cityData['city_id'];

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

        }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']);
            }
            $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 ($form->isValid()) {

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

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

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

                if ($pickAreaData->status == 'OK' && $dropAreaData->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;

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

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

                    $dropTime = strtotime("+" . $duration, strtotime($post['pickup_date'] . ' ' . $post['pickup_time']));
                    $dropTime = date('d-m-Y H:i:s', $dropTime);
                    $sessionVehContainer = new Container('vehicleSearchData');
                    unset($sessionVehContainer->vehicleSearchData);
                    $sessionVehContainer->vehicleSearchData = $post;
                    
                    $recentData = [
                        'user_id'=>$userId,
                        'ip'=>$_SERVER['REMOTE_ADDR'],
                        'booking_stage'=>$this->config()->getConfig()->bookingSteps->step1,
                        'booking_data'=>$post
                    ];
                    $this->CommonModel->addRecentViewedItems($recentData);
                    
                    $this->redirect()->toRoute('point-to-point', [
                        'action' => 'vehicle-listing'
                            ], ['query' => [
                            'pickup_city' => $post['pickup_city'],
                            'pickup_area' => $post['pickup_area'],
                            'pickup_area_value' => $post['pickup_area_value'],
                            'drop_area' => $post['drop_area'],
                            'drop_area_value' => $post['drop_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'],
                            'distance' => $distance,
                            'duration' => $duration,
                            'drop_time' => $dropTime,
                            'city_id' => $post['city_id'],
                            'master_package_type' => $post['master_package_type'],
                            'city_latitude' => $post['city_latitude'],
                            'city_longitude' => $post['city_longitude'],
                            'city_northeast_latitude' => $post['city_northeast_latitude'],
                            'city_northeast_longitude' => $post['city_northeast_longitude'],
                            'city_southwest_latitude' => $post['city_southwest_latitude'],
                            'city_southwest_longitude' => $post['city_southwest_longitude'],
                            'nationality' => $post['nationality']
                        ]]
                    );
                } else {
                    if ($pickAreaData->status != 'OK') {
                        $form->get('pickup_area')->setMessages([$this->pickupAreaMsg]);
                    }if ($dropAreaData->status != 'OK') {
                        $form->get('drop_area')->setMessages([$this->dropAreaMsg]);
                    }if ($pickupAddressData->status != 'OK') {
                        $form->get('pickup_address')->setMessages([$this->pickupAddressMsg]);
                    }
                }
            }
        }

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


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

    /**
     *
     * @return ViewModel
     */
    public function vehicleSearchAction() {
        $form = new VehicleSearchForm();
        $cityId = '1';
        $packageId = '2';
        $form->get('pickup_city')->setValue($cityId);
        $form->get('package_id')->setValue($packageId);
        $view = new ViewModel(['form' => $form]);
        $view->setTerminal(true);
        return $view;
    }

    /**
     *
     * @return ViewModel
     */
    public function vehicleListingAction() {
        $sessionVehContainer = new Container('vehicleSearchData');
        $data = $sessionVehContainer->vehicleSearchData;
        $data = [];
        $estimated_time = 0;
        $form = new VehicleSearchForm();
        $guestForm = new GuestForm();
        $data = $this->params()->fromQuery();
        $form->setData($data);

        if (isset($data['local_pickup']) && $data['local_pickup'] == $this->pickupLater) {
            //$form->get('pickup_date')->setValue(date("Y-m-d", strtotime($data['pickup_date'])));
            $form->get('pickup_date')->setValue($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);
        $request = $this->getRequest();
        if ($request->isPost()) {
            $data = "";
            $data = $request->getPost()->toArray();
            //print_r($data);
            $form = new VehicleSearchForm();
            $form->setData($request->getPost());


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

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

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

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

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

                    $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("Y-m-d", strtotime($data['pickup_date'])));
                        $form->get('pickup_date')->setValue($data['pickup_date']);
                        $form->get('pickup_time')->setValue($data['pickup_time']);
                    }



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

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

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

                    $dropTime = strtotime("+" . $data['duration'], strtotime($data['pickup_date'] . ' ' . $data['pickup_time']));
                    $data['drop_time'] = date('d-m-Y H:i:s', $dropTime);
                } else {
                    if ($pickAreaData->status != 'OK') {
                        $form->get('pickup_area')->setMessages([$this->pickupAreaMsg]);
                    }if ($dropAreaData->status != 'OK') {
                        $form->get('drop_area')->setMessages([$this->dropAreaMsg]);
                    }if ($pickupAddressData->status != 'OK') {
                        $form->get('pickup_address')->setMessages([$this->pickupAddressMsg]);
                    }
                }
                $sessionVehContainer = new Container('vehicleSearchData');
                unset($sessionVehContainer->vehicleSearchData);
                $sessionVehContainer->vehicleSearchData = $data;
            }
            if ($request->getPost()['form_type'] == "guest_form") {
                $result = [];
                if ($request->isXmlHttpRequest()) {
                    $guestForm->setData($request->getPost());
                    $postGuest = $request->getPost()->toArray();
                    if ($postGuest['gst']) {
                        $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 (empty($data['distance'])) {
            $data['distance'] = '';
        }
        if (empty($data['duration'])) {
            $data['duration'] = '';
        }
        $vehicleList = $this->fetchFareDetails($data['city_id'], $data['master_package_type'], $data['pickup_time'], $data['distance'], $data['duration'], $estimated_time, $data['adults'], $data['childs'], $data['luggages']);
        //echo '<pre>';print_r($vehicleList);die();
        //Debug::dump($vehicleList);
        //exit;
        $vehicleType = $this->forward()->dispatch(IndexController::class, array('action' => 'getVehicleType'));
        $fuelType = $this->forward()->dispatch(IndexController::class, array('action' => 'getFuelType'));

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


        $viewModel = new ViewModel([
            'data' => $data,
            'form' => $form,
            'vehicleList' => $vehicleList,
            'vehicle_type' => $vehicleType,
            'fuel_type' => $fuelType,
            'guestForm' => $guestForm,
            'google_map_url' => $this->config()->getConfig()->google_map->url,
            'google_map_key' => $this->config()->getConfig()->google_map->key,
        ]);
        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;
        $sessionContainer = new Container('vehicle');
        $paymentData = $this->getRequest()->getPost();


        $sessionContainer->vehicleData = $paymentData;
        
        $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,
            'captchaKey' => $this->config()->getConfig()->googleCaptcha->siteKey
        ]);
        return $viewModel;
    }

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

        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'] = $getDate;
            $paymentData['pickup_time'] = $getTime;
        }
        //Debug::dump($paymentData);//exit;
        $sessionContainer1 = new Container('vehiclePayData');
        $payData = $sessionContainer1->vehiclePaymentData;
        $vehcilePaymentData = $payData[$paymentData['vehicle_id']];
        //exit;

        $paymentData['guest_first_name'] = $paymentData['first_name'];
        $paymentData['guest_last_name'] = $paymentData['last_name'];
        $paymentData['guest_email'] = $paymentData['email'];
        $paymentData['guest_mobile'] = $paymentData['mobile'];
        $paymentData['guest_alt_mobile'] = $paymentData['alt_mobile_no'];
        $paymentData['guest_gender'] = $paymentData['gender'];
        $paymentData = $paymentData->toArray();

        $form = new TravellerForm();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $form->setData($request->getPost());
            if ($form->isValid()) {
                $post = $request->getPost()->toArray();
                $finalData = [];
                $finalData = array_merge($paymentData, $post, $vehcilePaymentData);
                $aa = json_encode($finalData);
                print_r($aa);
                exit;
            }
        }

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

    /**
     *
     * @return ViewModel
     */
    public function travellerSaveAction() {
        $sessionUser = new Container('userlogin');
        $userData = $sessionUser->userData;
        $recaptcha_error = '';
        if (!empty($userData)) {
            $guest_id = $userData['user_id'];
        } else {
            $guest_id = "";
        }
        $sessionContainer = new Container('vehicle');
        $paymentData = $sessionContainer->vehicleData;

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

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

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

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


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

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

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


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

        //exit;

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

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

            if ($post['g-recaptcha-response'] == '') {
                $recaptcha_error = 'Please check the captcha';
            }
            if ($form->isValid() && $recaptcha_error == '') {

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

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

                //exit;
                //Debug::dump($paymentData); exit;
                $finalData = [];
                $finalData = array_merge($paymentData, $post, $vehcilePaymentData);
                //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('point-to-point', ['action' => 'login']);
                } else {
                    $this->redirect()->toRoute('point-to-point', ['action' => 'checkout']);
                }
            }
        }

        $viewModel = new ViewModel([
            'form' => $form,
            'paymentData' => $paymentData,
            'error' => $recaptcha_error,
            'captchaKey' => $this->config()->getConfig()->googleCaptcha->siteKey
        ]);
        $viewModel->setTemplate('point-to-point/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('point-to-point', ['action' => 'checkout']);
                } else {
                    $errorMsg = $data['data']['responsedata']['error'];
                }
                //Debug::dump($data);
                //exit;
            }
        }
        $viewModel = new ViewModel([
            'form' => $form,
            'paymentData' => $paymentData,
            'errorMsg' => $errorMsg
        ]);
        $viewModel->setTemplate('point-to-point/index/book-now.phtml');
        return $viewModel;
    }

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

        $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;
        //echo '<pre>';print_r($paymentData);die();

        $request = $this->getRequest();
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            //echo '<pre>';print_r($post);//die();
            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'])) {

                if(!empty($post['cash_payment']))
                {
                  //echo "Mohit"; die;
                  $walletStatus = 0;
                  $paymentStatus = 0;
                  $walletAmt = $walletData;
                  $paymentData['wallet_data'] = 0;
                  $post['charge_type'] = 1;
                }else{

                //echo "Jain"; die;
                $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;
                } else {
                    $walletAmt = $walletData - $post['booking_amt_paid'];
                    $paymentData['wallet_data'] = 0;
                    if ($walletAmt < 0) {
                        $paymentStatus = 1;
                    } else {
                        $paymentStatus = 0;
                        $post['charge_type'] = 1;
                    }
                }

                }
            } else {
                if(!empty($post['cash_payment'])){
                  //echo "Mohittt"; //die;

                  $paymentStatus = 0;
                  $post['charge_type'] = 1;
                }else{
                //echo "Jainaa"; //die;
                $paymentStatus = 1;
                }

                $walletStatus = 0;
                $walletAmt = $walletData;
                $paymentData['wallet_data'] = 0;
                //die;
            }

            $paymentData['wallet_updated_amount'] = $walletAmt;
            $paymentData['company_id'] = $this->config()->getConfig()->company->companyId;
            $finalData = [];
            $finalData = array_merge($paymentData, $post);
            //Debug::dump($finalData);
            //exit;
            $this->updateLatLng($finalData);
            $finalBooking = $this->finalBookingSubmission($finalData);
            $lastInsertId = $finalBooking['data']['response']['insertId'];
            $companyInitial = $this->config()->getConfig()->company->companyInitial;
            $finalData['booking_id'] = $lastInsertId;
            //Debug::dump($finalData);
            //exit;

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

            if (!empty($lastInsertId)) {
                 /* Update booking ref no. generate Now in booking API. - 20-june-2020
                $bookingRefNo = $this->getBookingRefNo($lastInsertId, $companyInitial);
                $updateDataArray['reference_number'] = $bookingRefNo['generated'];
                $updateDataArray['booking_id'] = $lastInsertId;
                $updated = $this->updateBookingNo($updateDataArray); */
                $this->logStackTrackerData($finalData);
                //$msg_sku='booking';
                //$this->getSmsTemplate($msg_sku);
                //////////

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

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

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

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

                //////////


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

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

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

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

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

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

    /**
     *
     * @return ViewModel
     */
    public function featureAction() {
        $sessionContainer = new Container('vehiclePayData');
        $payData = $sessionContainer->vehiclePaymentData;
        $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'];
        }
        $viewModel = new ViewModel(['data' => $data,'heading'=> $heading]);
        $viewModel->setTemplate('local-hire/index/feature.phtml');
        $viewModel->setTerminal(true);
        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'];
        $data = $payData[$vehicleId];
        $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() {

    }

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

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

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

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

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

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

    public function fetchGoogleApiDistance($origin_lat, $origin_lng, $destiny_lat, $destiny_lng) {
        $url = $this->config()->getConfig()->google_map->distUrl . "?origin=" . $origin_lat . ',' . $origin_lng . "&destination=" . $destiny_lat . ',' . $destiny_lng . "&key=" . $this->config()->getConfig()->google_map->key;
        $curl_handle = curl_init();
        curl_setopt($curl_handle, CURLOPT_URL, $url);
        curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 50);
        curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 199130000);
        $result = curl_exec($curl_handle);
        $result = curl_exec($curl_handle);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($curl_handle));
        }
        curl_close($curl_handle);
        return $result;
    }

    public function fetchFareDetails($city_id, $master_package_type, $pickupTime, $distance, $duration, $estimated_time, $adults, $childs, $luggages) {
        $sessionUserContainer = new Container('userlogin');
        $userData = $sessionUserContainer->userData;
        //echo '<pre>';print_r($userData);die();
        $sessionContainer = new Container('vehiclePayData');
        $response = [];
        $data = [
            'city_id' => $city_id,
            'master_package_id' => $master_package_type,
            'pickup_time' => $pickupTime,
            'distance' => $distance,
            'duration' => $duration,
            'estimated_time' => $estimated_time,
            '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,
            'master_booking_type_id' => $this->config()->getConfig()->masterBookTypeId[1],
        ];

        $url = $this->apiUrl() . "/local_hire/faredetails";
        $resp = $this->post($url, $data);
        $packageFareData = Json::decode($resp->getBody(), true);
        //echo '<pre>';print_r($packageFareData);die();
        if (!empty($packageFareData)) {
            if ($packageFareData['responsedata']['status'] == "success") {
                $response = $packageFareData['responsedata']['data'];
                //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;
    }

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

    public function fetchFareDetailsOld($city_id, $master_package_type, $pickupTime, $distance, $duration, $estimated_time) {
        $sessionUserContainer = new Container('userlogin');
        $userData = $sessionUserContainer->userData;
        $sessionContainer = new Container('vehiclePayData');
        $response = [];
        $url = $this->apiUrl() . "/point-to-point/packageFareDetail?city_id=" . $city_id . "&package_id=" . $master_package_type;
        $resp = $this->get($url);
        $packageFareData = Json::decode($resp->getBody(), true);

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

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


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

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

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

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


                /* Peak Time Charge Calculation Starts Here */
                $peaks = $this->pointModel->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->pointModel->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);

                $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,
                    "duration" => $duration,
                    "estimated_distance" => $distance,
                    "approx_waiting_charge" => '',
                    "approx_waiting_minute" => '',
                    "created_date" => date('Y-m-d H:i:s'),
                ];

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

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

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

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

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

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

    public function 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);
                //print_r($resp);
                if ($resp['response']['changedRows'] == 1) {
                    $data['user_id'] = $paymentData['user_id'];
                    $data['booking_id'] = $bookingId;
                    $data['booking_transaction_no'] = $this->getBookingTransNo($bookingId, $this->config()->getConfig()->company->companyInitial);
                    $data['amount'] = $paymentData['booking_amt_paid'];
                    $data['current_balance'] = $paymentData['wallet_updated_amount'];
                    $data['payment_type_id'] = 3;
                    $data['payment_status'] = 1;
                    $data['created_date'] = date('Y-m-d');
                    $data['created_by'] = $paymentData['user_id'];
                    $this->userTransactionUpdate($data);
                }
            } else {
                    $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'] = 1;
                    $data['payment_status'] = 1;
                    $data['created_date'] = date('Y-m-d');
                    $data['created_by'] = $paymentData['user_id'];
                    $this->userTransactionUpdate($data);
            }
            $this->redirect()->toRoute('point-to-point', ['action' => 'success', 'param' => $bookingRefNo]);
        }
    }

    public function atomPaymentGateway($paymentData, $bookingRefNo, $walletStatus) {
        $data = [];

        $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['txnamt'] = $paymentData['booking_amt_paid'];
        $data['clientcode'] = $paymentData['client_id'];
        $data['transid'] = $bookingRefNo;
        $data['datepick'] = date('d/m/Y');
        $data['custacc'] = $this->config()->getConfig()->atom_payment->custacc;
        $data['udf1'] = $paymentData['first_name'];
        $data['udf2'] = $paymentData['email'];
        $data['udf3'] = $paymentData['mobile'];
        $data['udf4'] = 'karol bagh';
        $data['ru'] = $this->config()->getConfig()->base_url->url . "point-to-point/payment-response/" . $walletStatus;
        //Debug::dump(json_encode($data));
        $resp = $this->post($url, $data);
        $response = Json::decode($resp->getBody(), true);
        //Debug::dump($response);
        //exit;
        if ($response['response']['status'] == true) {
            $this->redirect()->toUrl($response['response']['url']);
        }
    }

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

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

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

    public function successAction() {
        $bookingRef = $this->params()->fromRoute('param');
        $viewModel = new ViewModel(['bookingRef' => $bookingRef]);
        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);
        $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);
        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 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":{"and": [{"city_id": "'.$city.'"},{"area": {"like": "' . $term . '%"}}]},"limit":10}';
        $val = '{"where": {"nationality": {"like": "' . $term . '%"}},"limit":10}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/country?&filter=" . $val;
        $resp = $this->get($url);

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

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

    /**
     *
     * @return ViewModel
     */
    public function getLatLngAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $term = $postData['term'];
        $googleData = $this->fetchGoogleApiData($term);
        $googleAddressData = Json::decode($googleData);
        /* if ($googleAddressData->status== 'OK') {
          $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 getCountryId($country_name) {
        $val = '{"where": {"nationality": "' . $country_name . '"}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/country?filter=" . $val;
        $resp = $this->get($url);
        $countryId = Json::decode($resp->getBody(), true);
        $countryIdData = $countryId[0]['id'];
        return $countryIdData;
    }

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

                $lat = $googleAddressData->results[0]->geometry->location->lat;
                $lng = $googleAddressData->results[0]->geometry->location->lng;
                $data = [
                    'north_east_lat' => $north_east_lat,
                    'north_east_lng' => $north_east_lng,
                    'south_west_lat' => $south_west_lat,
                    'south_west_lng' => $south_west_lng,
                    'lat' => $lat,
                    'lng' => $lng
                ];
                $response = ["status" => true, "data" => $data];
            } else {
                $response = ["status" => false, "data" => ''];
            }
        }
        return $response;
    }

    public function updateLatLng($data) {
        $data=[
            'city_id'=>$data['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;
    }

}
