<?php

namespace PointToPoint\Controller;

use Application\Controller\RestAPIClientController;
use PointToPoint\Model\Point;
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();
    }

    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() {
        $cityData = $this->getRequest()->getQuery()->toArray();
        $form = new VehicleSearchForm();
        $form->get('master_package_type')->setValue($this->masterPackageType);
        $request = $this->getRequest();
        if (!empty($cityData)) {
            $form->get('pickup_city')->setValue($cityData['city']);
            $form->get('city_id')->setValue($cityData['city_id']);
        }
        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);

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

        $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_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_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]);
                    }
                }
            }
            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);
        //Debug::dump($vehicleList);
        //exit;
        $vehicleType = $this->forward()->dispatch(IndexController::class, array('action' => 'getVehicleType'));
        $fuelType = $this->forward()->dispatch(IndexController::class, array('action' => 'getFuelType'));


        $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() {
        $sessionContainer = new Container('vehicle');
        $paymentData = $this->getRequest()->getPost();

        $sessionContainer->vehicleData = $paymentData;
        $form = new TravellerForm();
        $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['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'];
                    $guestData = $this->getUserId($guestArray);
                    $paymentData['user_id'] = $guestData['data']['responsedata'][0]['user_id'];
                } else {
                    $paymentData['user_id'] = $guest_id;
                }

                $userArray['user_type_id'] = 2;
                $userArray['company_id'] = $this->config()->getConfig()->company->companyId;
                $userArray['first_name'] = $post['first_name'];
                $userArray['last_name'] = $post['last_name'];
                $userArray['mobile'] = $post['mobile'];
                $userArray['email'] = $post['email'];
                $userArray['password'] = md5($post['mobile']);
                //$userArray['gender'] = $post['gender'];
                $userArray['nationality'] = $this->getCountryId($paymentData['nationality']);
                $clientData = $this->getUserId($userArray);
                $paymentData['client_id'] = $clientData['data']['responsedata'][0]['user_id'];

                //exit;
                //Debug::dump($paymentData); exit;
                $finalData = [];
                $finalData = array_merge($paymentData, $post, $vehcilePaymentData);
                //Debug::dump($finalData); exit;
                unset($sessionContainer->vehicleData);
                $sessionContainer->vehicleData = $finalData;
                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();
            if ($post['booking_amt_percentage'] == '25') {
                $post['booking_amt_paid'] = round($twentyFivePercent);
                $post['booking_amt_balance'] = $paymentData['total_charge'] - round($twentyFivePercent);
            } else if ($post['booking_amt_percentage'] == '50') {
                $post['booking_amt_paid'] = round($fiftyPercent);
                $post['booking_amt_balance'] = $paymentData['total_charge'] - round($fiftyPercent);
            } else {
                $post['booking_amt_paid'] = $paymentData['total_charge'];
                $post['booking_amt_balance'] = 0;
            }

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

                $walletStatus = 1;
                if ($walletData < $post['booking_amt_paid']) {
                    $walletAmt = 0;
                    $post['booking_amt_paid'] = $post['booking_amt_paid'] - $walletData;
                    $paymentData['wallet_data'] = $walletData;
                    $paymentStatus = 1;
                } else {
                    $walletAmt = $walletData - $post['booking_amt_paid'];
                    $paymentData['wallet_data'] = 0;
                    if ($walletAmt < 0) {
                        $paymentStatus = 1;
                    } else {
                        $paymentStatus = 0;
                    }
                }
            } else {

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

                $paymentStatus = 1;
            }

            $paymentData['wallet_updated_amount'] = $walletAmt;

            $finalData = [];
            $finalData = array_merge($paymentData, $post);
            //Debug::dump($finalData);
            //exit;
            $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)) {
                $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() {
        $data = $this->params()->fromQuery('data');
        $viewModel = new ViewModel([
            'data' => $data
        ]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }

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

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

    /**
     *
     * @return ViewModel
     */
    public function amenitiesAction() {
        $data = $this->params()->fromQuery('data');
        $viewModel = new ViewModel([
            'data' => $data
        ]);
        $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 = $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 (!empty($couponData['validateCoupon'])) {
            $status = true;
            $msg = "Coupon Code is Valid";
            $coupon_id = $couponData['validateCoupon'][0]['id'];
            if ($couponData['validateCoupon'][0]['discount_type'] == 'Rs') {
                $couponDiscount = $couponData['validateCoupon'][0]['discount_amount'];
                $totalPrice = $totalPrice - $couponDiscount;
            } else {
                $couponDiscount = $totalPrice * $couponData['validateCoupon'][0]['discount_amount'] / 100;
                $totalPrice = $totalPrice - $couponDiscount;
            }
        } else {
            $status = false;
            $msg = "Coupon code is In-Valid";
            $couponDiscount = 0;
            $totalPrice = $totalPrice - $couponDiscount;
            $coupon_id = "";
        }
        $data = [
            'status' => $status,
            "msg" => $msg,
            "total_price" => $totalPrice,
            "coupon_discount" => $couponDiscount,
            "coupon_id" => $coupon_id,
        ];
        $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;
        $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']];
            }
        } 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) {
        $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()) {
            $response = ["status" => true, "message" => "Insert Successfully", "data" => Json::decode($resp->getBody(), true)];
        } 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);
                }
            }
            $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'] = 3;
            $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['response']['insertId'];
        $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);

        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']);
        }
        //return $response;
        //exit;
    }

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

    public function failAction() {
        $viewModel = new ViewModel();
        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 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'] = '';

        $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": {"name": {"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['name'], "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;
    }

    public function getCountryId($country_name) {
        $val = '{"where": {"name": "' . $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;
    }
}
