<?php

namespace Guide\Controller;

use Application\Controller\RestAPIClientController;
use Guide\Model\Guide;
use Guide\Form\{
    VehicleSearchForm,
    TravellerForm,
    LocalGuideSearchForm,
    MultiCityGuideSearchForm,
    GuestForm
};
use Zend\View\Model\{
    ViewModel,
    JsonModel
};
use Zend\Debug\Debug;
use Zend\Session\Container;
use Zend\Json\Json;

class IndexController extends RestAPIClientController {

    public function __construct() {
        $this->guideModel = new Guide();
    }

    private $itemCount = 2;
    //private $onWayType = 1;
    private $localType = 1;
    private $multiCityType = 2;
    private $masterPackageType = 6;
    private $pickupAreaMsg = "Please enter valid Pickup City";
    private $dropAreaMsg = "Please enter valid Drop City";
    private $pickupAddressMsg = "Please enter valid Pickup Address";
    private $extras = 'extras';
    private $peakTimeCharge = 'peak_time_charges';

    public function indexAction() {
        //create form object
        $form = new VehicleSearchForm();

        //get request object
        $request = $this->getRequest();
        //if request will be post
        if ($request->isPost()) {
            $form->setData($request->getPost());
            if ($form->isValid()) {
                $post = $request->getPost()->toArray();
                return $this->redirect()->toRoute('guide', ['action' => 'guide-listing']);
            } else {
                //$aa =   $form->getMessages();
                //echo "<pre>";print_r($aa); exit;
            }
        }

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

    public function localAction() {
        LocalGuideSearchForm:: $lang = $this->guideModel->getLanguageList();
        LocalGuideSearchForm:: $tourType = $this->guideModel->getTourTypeList();
        $form = new LocalGuideSearchForm();
        $form->get('module_type')->setValue($this->localType);
        $form->get('master_package_type')->setValue($this->masterPackageType);
        $request = $this->getRequest();

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

            if ($form->isValid()) {
                $pickupAddressData = $this->fetchGoogleApiData($post['pickup_address']);
                $pickupAddressData = Json::decode($pickupAddressData);
                if ($pickupAddressData->status == 'OK') {

                    $sessionVehContainer = new Container('vehicleSearchData');
                    unset($sessionVehContainer->vehicleSearchData);
                    $sessionVehContainer->vehicleSearchData = $post;
                    $this->redirect()->toRoute('guide-booking', [
                        'action' => 'local-guide-listing'
                            ], ['query' => [
                            'pickup_city' => $post['pickup_city'],
                            'pickup_date' => $post['pickup_date'],
                            'pickup_time' => $post['pickup_time'],
                            'pickup_address' => $post['pickup_address'],
                            'adults' => $post['adults'],
                            'childs' => $post['childs'],
                            'guides' => $post['guides'],
                            'guide_package' => $post['guide_package'],
                            'tour_type' => $post['tour_type'],
                            'guide_language' => $post['guide_language'],
                            'agree_terms' => $post['agree_terms'],
                            'city_id' => $post['city_id'],
                            'master_package_type' => $post['master_package_type'],
                            'module_type' => $post['module_type'],
                            'city_latitude' => $post['city_latitude'],
                            'city_longitude' => $post['city_longitude'],
                            'city_northeast_latitude' => $post['city_northeast_latitude'],
                            'city_northeast_longitude' => $post['city_northeast_longitude'],
                            'city_southwest_latitude' => $post['city_southwest_latitude'],
                            'city_southwest_longitude' => $post['city_southwest_longitude'],
                            'nationality' => $post['nationality']
                        ]]
                    );
                } else {
                    if ($pickupAddressData->status != 'OK') {
                        $form->get('pickup_address')->setMessages([$this->pickupAddressMsg]);
                    }
                }
            }
        }

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

    public function localGuideListingAction() {
        $sessionVehContainer = new Container('vehicleSearchData');
        $data = $sessionVehContainer->vehicleSearchData;
        $estimated_time = "";
        $data = [];
        LocalGuideSearchForm:: $lang = $this->guideModel->getLanguageList();
        LocalGuideSearchForm:: $tourType = $this->guideModel->getTourTypeList();
        $form = new LocalGuideSearchForm();
        $guestForm = new GuestForm();
        $data = $this->params()->fromQuery();
        //echo '<pre>';print_r($data);die();
        $form->setData($data);
        $form->get('module_type')->setValue($this->localType);
        $form->get('master_package_type')->setValue($this->masterPackageType);

        $request = $this->getRequest();
        if ($request->isPost()) {
            $data = "";
            $data = $request->getPost()->toArray();
            $form->setData($request->getPost());

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



        //$vehicleList = $this->fetchFareDetails($data['pickcity_id'], $data['master_package_type'], date('H:i:s', strtotime($data['pickup_time'])), isset($data['distance']) ? $data['distance'] : 0, isset($data['duration']) ? $data['duration'] : 0, $estimated_time, $total_days, '');
        //Debug::dump($vehicleList); exit;
        //$vehicleType = $this->forward()->dispatch(IndexController::class, array('action' => 'getVehicleType'));
        $lngType = $this->guideModel->getLanguageList();
        $currencyList = $this->guideModel->getCurrencyList();
        $data['guide_language_name'] = $this->guideModel->getLanguageName($data['guide_language']);

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

        $viewModel = new ViewModel([
            'data' => $data,
            'form' => $form,
            //'vehicleList' => $vehicleList,
            //'vehicle_type' => $vehicleType,
            'lng_type' => $lngType,
            'currency_list' => $currencyList,
            'guestForm' => $guestForm,
            //'outstation_type' => 'one-way',
            'google_map_url' => $this->config()->getConfig()->google_map->url,
            'google_map_key' => $this->config()->getConfig()->google_map->key,
        ]);
        return $viewModel;
    }

    public function multiCityAction() {
        MultiCityGuideSearchForm:: $lang = $this->guideModel->getLanguageList();
        MultiCityGuideSearchForm:: $tourType = $this->guideModel->getTourTypeList();
        $form = new MultiCityGuideSearchForm('product-form', null);
        $form->get('module_type')->setValue($this->multiCityType);
        $form->get('master_package_type')->setValue($this->masterPackageType);
        $request = $this->getRequest();
        if ($this->getRequest()->isPost()) {
            // Fill in the form with POST data
            $data = $this->params()->fromPost();
            //Debug::dump($data);exit;
            //Debug::dump($data['new-product']['items']);
            //Debug::dump($items);die;
            $form->setData($data);
            // Validate form
            if ($form->isValid()) {
                // Get filtered and validated data
                $data = $form->getData();
                //Debug::dump($data['new-product']['items']); //exit;
                $items = $this->getItemsDetails($data['new-product']['items']);
                //Debug::dump($items); exit;
                $this->redirect()->toRoute('guide-booking', [
                    'action' => 'multi-city-guide-listing',
                        ], ['query' => [
                        'items' => $items,
                        'pickup_address' => $data['pickup_address'],
                        'adults' => $data['adults'],
                        'childs' => $data['childs'],
                        'guides' => $data['guides'],
                        'guide_package' => $data['guide_package'],
                        'tour_type' => $data['tour_type'],
                        'guide_language' => $data['guide_language'],
                        'agree_terms' => $data['agree_terms'],
                        'master_package_type' => $data['master_package_type'],
                        'module_type' => $data['module_type'],
                        'pickcity_id' => $data['pickcity_id'],
                        'city_latitude' => $data['city_latitude'],
                        'city_longitude' => $data['city_longitude'],
                        'city_northeast_latitude' => $data['city_northeast_latitude'],
                        'city_northeast_longitude' => $data['city_northeast_longitude'],
                        'city_southwest_latitude' => $data['city_southwest_latitude'],
                        'city_southwest_longitude' => $data['city_southwest_longitude'],
                        'nationality' => $data['nationality']
                    ]]
                );
            }
        }

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

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

        $data = [];
        MultiCityGuideSearchForm:: $lang = $this->guideModel->getLanguageList();
        MultiCityGuideSearchForm:: $tourType = $this->guideModel->getTourTypeList();
        $form = new MultiCityGuideSearchForm('product-form', null);

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

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

            if ($form->isValid()) {

            }

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

        //$vehicleList = $this->fetchFareDetails($data['items'][0]['pickcity_id'], $data['master_package_type'], date('H:i:s', strtotime($data['items'][0]['pickup_time'])), $data['distance'], isset($data['duration']) ? $data['duration'] : 0, $estimated_time, $total_days, $this->multiCityType);
        //echo '<pre>';print_r($vehicleList);die();
        //$vehicleType = $this->forward()->dispatch(IndexController::class, array('action' => 'getVehicleType'));
        $lngType = $this->guideModel->getLanguageList();
        $currencyList = $this->guideModel->getCurrencyList();
        $data['guide_language_name'] = $this->guideModel->getLanguageName($data['guide_language']);

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

        $viewModel = new ViewModel([
            'data' => $data,
            'form' => $form,
            //'vehicleList' => $vehicleList,
            //'vehicle_type' => $vehicleType,
            'lng_type' => $lngType,
            'currency_list' => $currencyList,
            'guestForm' => $guestForm,
            //'outstation_type' => 'one-way',
            'google_map_url' => $this->config()->getConfig()->google_map->url,
            'google_map_key' => $this->config()->getConfig()->google_map->key,
        ]);
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
    public function paymentAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $vehicleId = $postData['vehicle_id'];
        $view = new JsonModel($data);
        return $view;
    }

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

    /**
     *
     * @return ViewModel
     */
    public function localGuideTravellerAction() {
        $form = new TravellerForm();
        $viewModel = new ViewModel([
            'form' => $form,
            'captchaKey' => $this->config()->getConfig()->googleCaptcha->siteKey
        ]);
        return $viewModel;
    }

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



        $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;
                $clientData = $this->getUserId($userArray);
                $paymentData['client_id'] = $clientData['data']['user_id'];

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

                $finalData = [];
                $finalData = array_merge($paymentData, $post, $vehcilePaymentData);
                //$finalData = array_merge($paymentData, $post);
                //Debug::dump($finalData); exit;
                unset($sessionContainer->vehicleData);
                $sessionContainer->vehicleData = $finalData;
                if ($guest_id == "") {
                    $this->redirect()->toRoute('outstation', ['action' => 'login']);
                } else {
                    $this->redirect()->toRoute('outstation', ['action' => 'checkout']);
                }
            }
        }

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

        $viewModel = new ViewModel([
            'form' => $form,
            'error' => $recaptcha_error,
            'captchaKey' => $this->config()->getConfig()->googleCaptcha->siteKey
        ]);
        $viewModel->setTemplate('guide/index/local-guide-traveller.phtml');
        return $viewModel;
    }

    /**
     *
     * @return ViewModel
     */
    public function multiCityGuideTravellerAction() {
        $form = new TravellerForm();
        $viewModel = new ViewModel([
            'form' => $form,
            'captchaKey' => $this->config()->getConfig()->googleCaptcha->siteKey
        ]);
        return $viewModel;
    }

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

        $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;
                $clientData = $this->getUserId($userArray);
                $paymentData['client_id'] = $clientData['data']['user_id'];

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

                $finalData = [];
                $finalData = array_merge($paymentData, $post, $vehcilePaymentData);
                //$finalData = array_merge($paymentData, $post);
                //Debug::dump($finalData); exit;
                unset($sessionContainer->vehicleData);
                $sessionContainer->vehicleData = $finalData;
                if ($guest_id == "") {
                    $this->redirect()->toRoute('outstation', ['action' => 'login']);
                } else {
                    $this->redirect()->toRoute('outstation', ['action' => 'checkout']);
                }
            }
        }

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

        $viewModel = new ViewModel([
            'form' => $form,
            'error' => $recaptcha_error,
            'captchaKey' => $this->config()->getConfig()->googleCaptcha->siteKey
        ]);
        $viewModel->setTemplate('guide/index/multi-city-guide-traveller.phtml');
        return $viewModel;
    }

    public function bookingAction() {

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

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

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

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

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

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



        $sessionContainer = new Container('vehicle');
        $paymentData = $this->getRequest()->getPost();
        $sessionContainer->vehicleData = $paymentData;
        //echo '<pre>';print_r($paymentData);die();
        $form = new TravellerForm();
        $viewModel = new ViewModel([
            'form' => $form,
            'paymentData' => $paymentData
        ]);
        return $viewModel;
    }

    public function guideListingAction() {



        $form = new VehicleSearchForm();



        $request = $this->getRequest();

        //if request will be post
        if ($request->isPost()) {
            $form->setData($request->getPost());
            if ($form->isValid()) {
                $post = $request->getPost()->toArray();
                return $this->redirect()->toRoute('guide-booking', ['action' => 'guide-listing']);
            } else {
                //$aa =   $form->getMessages();
                //echo "<pre>";print_r($aa); exit;
            }
        }

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

    public function paymentDetailAction() {

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

    /**
     *
     * @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'],
                    "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 countryListAction() {
        $request = $this->getRequest();
        $postdata = $request->getPost();
        $term = $postdata['term'];
        $val = '{"where": {"nationality": {"like": "' . $term . '%"}},"limit":10}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/country?&filter=" . $val;
        $resp = $this->get($url);
        $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 City Json
     */
    public function getToCityListAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $term = $postData['term'];
        //$val = '{"where":{"and": [{"city_id": "'.$city.'"},{"area": {"like": "' . $term . '%"}}]},"limit":10}';
        $val = '{"where": {"name": {"like": "' . $term . '%"}},"limit":10}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/city?&filter=" . $val;
        $resp = $this->get($url);
        $cityJsonData = Json::decode($resp->getBody(), true);
        if (!empty($cityJsonData)) {
            foreach ($cityJsonData as $value) {
                $data[] = ["label" => $value['name'], "city_id" => $value['id']];
            }
        } else {
            $data[] = ["label" => 'Not Exist'];
        }
        $view = new JsonModel($data);
        return $view;
    }

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

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

    public function getItemsDetails($items) {
        $data = [];
        $estimated_time = 0;
        $i = 0;
        foreach ($items as $item) {

            $pickAreaData = $this->fetchGoogleApiData($item['pickup_city']);
            $pickAreaData = json_decode($pickAreaData);
            $pickAreaLat = $pickAreaData->results[0]->geometry->location->lat;
            $pickAreaLng = $pickAreaData->results[0]->geometry->location->lng;

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

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

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

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

            $pickcity_id = $this->getCityId($item['pickup_city']);
            $dropcity_id = $this->getCityId($item['drop_city']);

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

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

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

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

}
