<?php

namespace Application\Controller;

use Zend\Http\Client;
use Zend\Http\Client\Adapter\Curl;
use Application\Form\ContactForm;
use Application\Form\TicketForm;
use Application\Form\EnquiryForm;
use Application\Form\JobEnquiryForm;
use User\Form\ConfirmOtpForm;
use Application\Controller\RestAPIClientController;
use Zend\View\Model\{
    ViewModel,
    JsonModel
};
use Zend\Json\Json;
use Zend\Debug\Debug;
use Zend\Mail\Message;
use Zend\Mail\Transport\Smtp as SmtpTransport;
use Zend\Mime\Message as MimeMessage;
use Zend\Mime\Part as MimePart;
use Zend\Mail\Transport\SmtpOptions;
use Zend\View\Renderer\PhpRenderer;
use Zend\View\Resolver\TemplateMapResolver;
use Zend\Session\Container;
use Application\Model\CommonModel;

class IndexController extends RestAPIClientController {

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

    private $oneWayPackageType = 5;
    /**
     *
     * @return ViewModel
     */
    public function indexAction() {
        $fareList = [];
        $session = new Container('userlogin');
        $user_id = $session->userData['user_id'];
        if(isset($user_id) && $user_id>0){
        $id = $this->config()->getConfig()->company->companyId;
        $compJsonData = $this->getCompanySetupDetails($id);
        if(!empty($compJsonData)){
          $country_id  = $compJsonData['country_id'];
        }
        $param = ['country_id'=>$country_id];
        $fareList   =   $this->CommonModel->getLowestOneWayFareList($param);
        }
        return new ViewModel(['fareList' => $fareList]);

    }

    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'] . ' (' . $value['state_name'] . ')', "city_id" => $value['city_id'], "city_name" => $value['city_name']];
            }
        } else {
            $data[] = ["label" => 'Not Exist'];
        }
        $view = new JsonModel($data);
        return $view;
    }

    public function getServicesTypeAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $city_name = $postData['city_name'];
        $city_name = rawurlencode($city_name);
        $url = $this->apiUrl() . "/city_active_package/city?cityName=" . $city_name;
        $resp = $this->get($url);
        $moduleJsonData = Json::decode($resp->getBody(), true);
        if (!empty($moduleJsonData['responsedata'])) {
            foreach ($moduleJsonData['responsedata'] as $value) {
                $data[] = ["module_name" => $value['name'], "module_icon" => $value['icon'], "city_name" => $value['city_name'], "city_id" => $value['city_id']];
            }
            $response = ["status" => true, "data" => $data];
        } else {
            $response = ["status" => false, "data" => "Not Exist"];
        }
        $viewModel = new ViewModel([
            'data' => $data
        ]);
        $viewModel->setTemplate('application/index/service.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function getServiceTypeOldAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $city_name = $postData['city_name'];
        $city_name = rawurlencode($city_name);
        $url = $this->apiUrl() . "/city_active_package/city?cityName=" . $city_name;
        $resp = $this->get($url);
        $moduleJsonData = Json::decode($resp->getBody(), true);
        if (!empty($moduleJsonData['responsedata'])) {
            foreach ($moduleJsonData['responsedata'] as $value) {
                $data[] = ["module_name" => $value['name'], "module_icon" => $value['icon'], "city_name" => $value['city_name'], "city_id" => $value['city_id']];
            }
            $response = ["status" => true, "data" => $data];
        } else {
            $response = ["status" => false, "data" => "Not Exist"];
        }
        $viewModel = new ViewModel([
            'data' => $data
        ]);
        $viewModel->setTemplate('application/index/service.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function getServiceTypeAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $city_name = $postData['city_name'];
        $val = '{"where": {"name": "' . $city_name . '"}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/city?&filter=" . $val;
        $resp = $this->get($url);
        $moduleJsonData = Json::decode($resp->getBody(), true);
        //echo '<pre>';print_r($moduleJsonData);die();
        if (!empty($moduleJsonData)) {
            $city_id = $moduleJsonData[0]['id'];
            $data = '/city/'.$city_name;
            $response = ["status" => true, "data" => $data];
        } else {
            $response = ["status" => false, "data" => "Not Exist"];
        }
        $view = new JsonModel($response);
        return $view;
    }

    public function fareStructureAction() {
        echo "jbnj";
        die;
    }

    public function sendMail1Action() {
        //echo $_SERVER['SERVER_NAME']; exit;
        $id = $this->config()->getConfig()->company->companyId;

        $compJsonData = $this->getCompanySetupDetails($id);
        //$templateName = $this->getRequest()->getPost('templateName');

        $templateName = 'whats-new';
        $user_info = [
            'user_name' => 'Mohit',
            'user_email' => 'mohit@gmail.com',
            'user_password' => '123456',
            'refer_amount' => '200'
        ];

        $params = [
            'company_info' => $compJsonData,
            'user_info' => $user_info,
            'template_name' => $templateName,
            'designed_by' => $this->config()->getConfig()->designedBy->url
        ];

        $template = $this->getEmailTemplate1($params);
        echo $template;
        exit;

        $fromName = $compJsonData['site_title'];
        $fromEmail = $compJsonData['global_email'];
        $email = "php@hello42cab.com";
        $subject = "Test Mail";
        //$template="hello How r u";

        $transport = new SmtpTransport();
        $options = new SmtpOptions(array(
            'host' => $this->config()->getConfig()->smtpMail->host,
            'connection_class' => 'login',
            'connection_config' => array(
                'tls' => 'tls',
                'username' => $this->config()->getConfig()->smtpMail->username,
                'password' => $this->config()->getConfig()->smtpMail->password,
            ),
            'port' => $this->config()->getConfig()->smtpMail->port,
        ));

        $html = new MimePart($template);
        $html->type = "text/html";
        $body = new MimeMessage();
        //$body->addPart($html);
        $body->setParts(array($html,));

        $mail = new Message();
        $mail->setBody($body);
        $mail->setFrom($fromEmail, $fromName);
        $mail->setTo($email);
        $mail->setSubject($subject);
        $transport->setOptions($options);
        $transport->send($mail);
        Debug::dump($transport);
        exit;
    }

    ////

    public function sendSMS1Action() {
        $templateName = 'acc_verify_code';
        $mobileNumber = '9313504429';
        $userName = 'Mohit';
        $code = '1234';



        $id = $this->config()->getConfig()->company->companyId;
        $compJsonData = $this->getCompanySetupDetails($id);

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


        $template = $this->getSmsTemplate($templateName);
        //Debug::dump($template); //exit;

        if ($templateName == "acc_verify_code") {
            $array = explode('<variable>', $template);
            $array[0] = $array[0] . $userName;
            $array[1] = $array[1] . $code;
            $array[2] = $compJsonData['site_title'];
            $array[3] = $compJsonData['site_name'];
            $message = urlencode(implode("", $array));
        }


        //$message='Hi <variable>, Welcome to Hello42! To activate enter the verification code <variable>on<variable>  or Log on';
        $apiId = $this->config()->getConfig()->smsApi->apiId;
        $url = $this->apiUrl() . "/sms_apis/" . $apiId;
        $resp = $this->get($url);
        $sms_api = Json::decode($resp->getBody(), true);

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

        $api_base_uri = $sms_api['api_base_uri'];
        $api_username = $sms_api['api_username'];
        $api_password = $sms_api['api_password'];
        $api_sender_id = $sms_api['api_sender_id'];
        $url = "$api_base_uri?username=$api_username&password=$api_password&to=91$mobileNumber&from=$api_sender_id&udh=&text=$message&dlr-mask=19&dlr-url";
        /* $curl_handle=curl_init();
          curl_setopt($curl_handle,CURLOPT_URL,$url);
          curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
          curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
          $result = curl_exec($curl_handle);
          if ($result === FALSE) {
          die('Curl failed: ' . curl_error($curl_handle));
          }
          curl_close($curl_handle);
          echo $result; */
        $client = new Client($url, array(
            'maxredirects' => 0,
            'timeout' => 30
        ));
        $client->setAdapter(Curl::class);
        // Performing a POST request
        $client->setMethod('POST');
        //Set data
        $response = $client->send();
        if ($response->isSuccess()) {
            echo $response->getBody();
        } else {
            echo 'Request is failed';
        }
    }



    public function getEmailTemplate1($arrData = array()) {
        $compData = $arrData['company_info'];
        $templateName = $arrData['template_name'];
        $userInfo = $arrData['user_info'];
        $designed_by = $arrData['designed_by'];

        /* $val = '{"where": {"type": "' . $templateType . '"}}';
          $val = rawurlencode($val);
          $url = $this->apiUrl() . "/email-templates/?filter=" . $val;
          $resp = $this->get($url);
          $emailTemplateData = Json::decode($resp->getBody(), true);

          $template = $emailTemplateData[0]['description']; exit; */

        $view = new PhpRenderer();
        $resolver = new TemplateMapResolver();

        $header = $resolver->setMap(array(
            'mailTemplate' => __DIR__ . '/../../view/application/emailtemplate/' . $templateName . '.phtml',
        ));

        $view->setResolver($resolver);
        $viewModel = new ViewModel(['user_info' => $userInfo, 'comp_info' => $compData, 'designed_by' => $designed_by]);
        $viewModel->setTemplate('mailTemplate');
        $template = $view->render($viewModel);
        return $template;
    }

    //////

    public function getSmsTemplate($templateName) {
        $val = '{"where": {"msg_sku": "' . $templateName . '"}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/sms_template/?filter=" . $val;
        $resp = $this->get($url);
        $smsTemplateData = Json::decode($resp->getBody(), true);

        $template = $smsTemplateData[0]['message'];
        return $template;
    }

    public function servicesAction() {
        return new ViewModel();
    }

    public function cmsPagesAction() {
        $status = '';
        $pageType = $this->params()->fromRoute('page');
        $pageTypes = $this->params()->fromRoute('page-type');
        $id = $this->config()->getConfig()->company->companyId;
        $pageData = $this->CommonModel->getCmsPageData($pageType,$id);
        if (isset($pageData[0]) == "") {
            $pageData[0] = '';
        }
        $captchaerror = '';
        if ($pageType == 'contact-us') {
            $compJsonData = $this->getCompanySetupDetails($id);
            $form = new ContactForm();
            $request = $this->getRequest();
            if ($request->isPost()) {
                $post = $request->getPost()->toArray();
                $form->setData($request->getPost());

                if ($post['g-recaptcha-response'] == '') {
                    $captchaerror = 'Please check the captcha';
                }

                if ($form->isValid() && $captchaerror == '') {


                    $data = [
                        'name' => $post['contact_name'],
                        'email' => $post['contact_email'],
                        'mobile' => $post['contact_mobile'],
                        'company' => $post['contact_comp_name'],
                        'subject' => $post['contact_subject'],
                        'message' => $post['contact_msg'],
                        'created_date' => date('Y-m-d H:i:s'),
                        'ip' => $_SERVER['REMOTE_ADDR']
                    ];
                    $this->CommonModel->insertContactDetails($data);
                    $sendMailParam = [
                        'user_name' => $post['contact_name'],
                        'user_email' => $post['contact_email'],
                        'template_name' => 'contact',
                        'subject' => 'Contact Us'
                    ];
                    $this->sendMail($sendMailParam);
                    $sendMailAdminParam = [
                        'user_name' => 'Admin',
                        'user_email' => $compJsonData['global_email'],
                        //'user_email' => 'mohitjain2007@gmail.com',
                        'template_name' => 'contact-email',
                        'subject' => 'Contact Us',
                        'name' => $post['contact_name'],
                        'email' => $post['contact_email'],
                        'mobile' => $post['contact_mobile'],
                        'company' => $post['contact_comp_name'],
                        'subject' => $post['contact_subject'],
                        'message' => $post['contact_msg'],
                    ];
                    $mail = $this->sendMail($sendMailAdminParam);
                    if ($mail == 'success') {
                        $status = "true";
                    } else {
                        $status = "false";
                    }
                }
            }
        } else {
            $form = "";
            $status = "";
        }

        if ($pageType == 'we-are-hiring') {
            $departmentList =   $this->CommonModel->getAllDepartmentList();
        }

        if($pageTypes=="city"){
        $cityModule = new Container('cityModule');
        unset($cityModule->city_id);
        unset($cityModule->city_name);
        $val = '{"where": {"name": "' . $pageType . '"}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() ."/city?&filter=" . $val;
        $resp = $this->get($url);
        $data = Json::decode($resp->getBody(), true);
        if(!empty($data[0])){
            $cityModule = new Container('cityModule');
            unset($cityModule->city_id);
            unset($cityModule->city_name);
            $cityModule->city_id = $data[0]['id'];
            $cityModule->city_name = $pageType;
        }else{
            $this->redirect()->toRoute('home');
        }
         $session = new Container('userlogin');
        $user_id = $session->userData['user_id'];
        if($user_id>0){
            $param = ['city_id'=>$data[0]['id']];
            $fareList   =   $this->CommonModel->getLowestOneWayFareList($param);
         }
        }

        $viewModel = new ViewModel([
            'pageData' => $pageData[0],
            'form' => $form,
            'status' => $status,
            'error' => $captchaerror,
            'captchaKey' => $this->config()->getConfig()->googleCaptcha->siteKey,
            'departmentList' => isset($departmentList)?$departmentList:'',
            'moduleData' => isset($moduleData)?$moduleData:'',
            'fareList' =>isset($fareList)? $fareList:''
        ]);
        if($pageTypes=="city"){
        $viewModel->setTemplate('application/index/city-page.phtml');
        }else{
        $viewModel->setTemplate('application/index/' . $pageType . '.phtml');
        }
        return $viewModel;
    }

    public function referEarnAction() {
        $session = new Container('userlogin');
        $user_id = $session->userData['user_id'];
        $referral_key = $session->userData['referral_key'];
        $referralData = $this->CommonModel->getReferralAmt();
        $id = $this->config()->getConfig()->company->companyId;
        $compJsonData = $this->getCompanySetupDetails($id);
        $template = $this->getSmsTemplate('refer_earn');
        $searchVal = array("<%= username %>", "<%= user_referral_code %>", "<%= referral_amount %>", "<%= app_link %>");
        // Array containing replace string from  search string
        $replaceVal = array("", $referral_key, $referralData[0]['installation_amount_user'], $compJsonData['driver_app_url']);
        // Function to replace string
        $referral_msg = str_replace($searchVal, $replaceVal, $template);
        $viewModel = new ViewModel(['referralData' => $referralData,'referral_msg'=>$referral_msg]);
        return $viewModel;
    }

    public function emailInviteAction() {
        $session = new Container('userlogin');
        $user_id = $session->userData['user_id'];
        $data = [];
        $postData = $this->getRequest()->getPost();
        $email_id = $postData['email_id'];
        $url = $this->apiUrl() . "/user/verifyregister?username=" . $email_id;
        $val = $this->get($url);
        $JsonData = $val->getBody();
        $JsonData = Json::decode($JsonData, true);

        if ($JsonData['responsedata']['status']!= 'success') {
            $referralData = $this->CommonModel->getReferralAmt();
            $sendMailParam = [
                'user_name' => 'User',
                'referral_key' => $session->userData['referral_key'],
                'referral_amt' => $referralData[0]['installation_amount_user'],
                'user_email' => $postData['email_id'],
                'template_name' => 'booking-referral',
                'subject' => 'Refer & Earn'
            ];
            $this->sendMail($sendMailParam);
            $data = ['status' => true];
        } else {
            $data = ['status' => false];
        }
        $view = new JsonModel($data);
        return $view;
    }

    public function mobileInviteAction() {
        $session = new Container('userlogin');
        $user_id = $session->userData['user_id'];
        $data = [];
        $postData = $this->getRequest()->getPost();
        $mobile = $postData['mobile_no'];
        $url = $this->apiUrl() . "/user/verifyregister?username=" . $mobile;
        $val = $this->get($url);
        $JsonData = $val->getBody();
        $JsonData = Json::decode($JsonData, true);

        if ($JsonData['responsedata']['status'] == 'success') {
            $referralData = $this->CommonModel->getReferralAmt();
            $smsparam = [
                'template_name' => 'refer_earn',
                'mobile' => $mobile,
                'user_name' => 'User',
                'referral_key' => $session->userData['referral_key'],
                'referral_amt' => $referralData[0]['installation_amount_user'],
            ];
            $this->sendSMS($smsparam);
            $data = ['status' => true];
        } else {
            $data = ['status' => false];
        }
        $view = new JsonModel($data);
        return $view;
    }

    public function offersAction() {
        $id = $this->config()->getConfig()->company->companyId;
        $couponList = $this->CommonModel->getOffers($id);
        $daysList = $this->CommonModel->getDaysArray();
        $viewModel = new ViewModel(['couponList' => $couponList, 'daysList' => $daysList]);
        return $viewModel;
    }

    /**
     * @return ViewModel
     */
    public function generateTicketAction() {
        $form = new TicketForm();
        $otpform = new ConfirmOtpForm();
        $data = $this->getRequest()->getPost();
        $type = $data['type'];
        if ($type == "track-car") {
            $heading = "Track Car";
        } else if ($type == "print-sms") {
            $heading = "Print/SMS Booking";
        } else if ($type == "cancel-ticket") {
            $heading = "Cancel Booking";
        } else if ($type == "refund") {
            $heading = "Refund Booking";
        } else if ($type == "change-travel-date") {
            $heading = "Change Travel Date";
        }
        $form->get('ticket_type')->setValue($type);
        $otpform->get('ticket_type')->setValue($type);
        $viewModel = new ViewModel([
            'type' => $type,
            'heading' => $heading,
            'form' => $form,
            'otpform' => $otpform,
            'captchaKey' => $this->config()->getConfig()->googleCaptcha->siteKey
        ]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function submitTicketAction() {
        $sessionUserContainer = new Container('userlogin');
        $userData = $sessionUserContainer->userData;
        //echo '<pre>';print_r($userData);die();
        $viewModel = new ViewModel();
        $request = $this->getRequest();
        $form = new TicketForm();
        $msg = '';
        $captchaerror = '';
        if ($request->isXmlHttpRequest()) {
            $postdata = $request->getPost()->toArray();
            if(isset($userData['user_id']) && !empty($userData['user_id'])){
                $form->getInputFilter()->get('mobile_no')->setRequired(false);
            }
            $form->setData($postdata);
            if ($postdata['g-recaptcha-response'] == '') {
                $captchaerror = 'Please check the captcha';
            }
            if ($form->isValid() && $captchaerror == '') {
                $session = new Container("print_ticket");
                $session->getManager()->getStorage()->clear('print_ticket');
                $bookingNo = trim($postdata['booking_no']);
                if(isset($userData['user_id']) && !empty($userData['user_id'])){
                $mobileNo = $userData['mobile'];
                }else{
                $mobileNo = trim($postdata['mobile_no']);
                }
                $ticketType = $postdata['ticket_type'];

                $apiParams = ['booking_id' => $bookingNo, 'user_mobile' => $mobileNo];
                $url = $this->apiUrl() . "/booking/bookingListSearch";
                $resp = $this->post($url, $apiParams);
                $bookingList = Json::decode($resp->getBody(), true);
                //echo '<pre>';print_r($bookingList); //die();
                if ($bookingList['responsedata']['status'] == 'success') {
                    $bookinginfo = $bookingList['responsedata']['data'];
                    if ($ticketType == 'change-travel-date') {
                        //$bookinginfo[0]['ordertime'].'<br>'; //die;
                        $orderDate = strtotime(date('Y-m-d', strtotime($bookinginfo[0]['ordertime'])));
                        $orderTime = date('H:i:s', strtotime($bookinginfo[0]['ordertime']));
                        $currDate = strtotime(date('Y-m-d'));
                        $currTime = strtotime(date('H:i:s'));
                        $consTime = $this->config()->getConfig()->changeTravelTime->timeCons;
                        $secs = strtotime($consTime) - strtotime("00:00:00");
                        $resultTime = strtotime(date("H:i:s", strtotime($orderTime) - $secs));
                        //echo $currDate.'<br>';
                        //echo $orderDate.'<br>';
                        //echo $currTime.'<br>';
                        //echo $resultTime.'<br>';
                        //echo $result;
                        //die;
                        $data = [
                            'booking_status' => $bookinginfo[0]['status_id'],
                            'current_date' => $currDate,
                            'order_date' => $orderDate,
                            'current_time' => $currTime,
                            'result_time' => $resultTime
                        ];
                        $dateStatus = $this->CommonModel->checkChangeTravelDateStatus($data);
                        //echo $dateStatus; die;
                        if ($dateStatus == "true") {
                            $user_name = $bookinginfo[0]['user_name'];
                            $user_id = $bookinginfo[0]['user_id'];

                            $printTicketContainer = new Container('print_ticket');
                            $printTicketContainer->booking_detail = $bookinginfo[0];
                            $printTicketContainer->ticket_type = $ticketType;

                            $otp = $this->generateOtp();
                            /* Insert OTP in database */
                            $otpData = ['UID' => $user_id, 'Verification_code' => $otp];
                            $this->CommonModel->insertOtp($otpData);
                            /* END */

                            $smsparam = ['template_name' => 'acc_verify_code', 'mobile' => $mobileNo, 'user_name' => $user_name, 'otp' => $otp];
                            $this->sendSMS($smsparam);

                            $result = ['result' => true, 'message' => $msg, 'popup' => 'show-otp', 'mobile_no' => $mobileNo];
                        } else {
                            $msg = "Time Limit is Over to change Travel Date";
                            $result = ['result' => false, 'message' => $msg];
                        }
                    } else {
                        $user_name = $bookinginfo[0]['user_name'];
                        $user_id = $bookinginfo[0]['user_id'];

                        $printTicketContainer = new Container('print_ticket');
                        $printTicketContainer->booking_detail = $bookinginfo[0];
                        $printTicketContainer->ticket_type = $ticketType;

                        $otp = $this->generateOtp();
                        /* Insert OTP in database */
                        $otpData = ['UID' => $user_id, 'Verification_code' => $otp];
                        $this->CommonModel->insertOtp($otpData);
                        /* END */

                        $smsparam = ['template_name' => 'acc_verify_code', 'mobile' => $mobileNo, 'user_name' => $user_name, 'otp' => $otp];
                        $this->sendSMS($smsparam);

                        $result = ['result' => true, 'message' => $msg, 'popup' => 'show-otp', 'mobile_no' => $mobileNo];
                    }
                } else {
                    $msg = "Invalid Booking no. or Mobile no.";
                    $result = ['result' => false, 'message' => $msg];
                }
            } else {
                $result = ['result' => false, 'message' => $form->getMessages(), 'error' => $captchaerror];
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }
    }

    public function confirmTicketOtpAction() {
        $viewModel = new ViewModel();
        $uri = $this->getRequest()->getUri();
        $baseUrl = sprintf('%s://%s/', $uri->getScheme(), $uri->getHost());
        $sessionContainer = new Container('print_ticket');
        $booking_details = $sessionContainer->booking_detail;
        $user_id = $booking_details['user_id'];
        $request = $this->getRequest();
        $otpform = new ConfirmOtpForm();
        $msg = '';
        if ($request->isXmlHttpRequest()) {
            $postdata = $request->getPost()->toArray();
            $otpform->setData($postdata);
            if ($otpform->isValid()) {
                $data = [
                    'user_id' => $user_id,
                    'confirm_otp' => $postdata['confirm_otp']
                ];
                $rep = $this->CommonModel->fetchOtp($data);

                if ($rep['status'] == "success") {
                    //echo '<pre>';print_r($rep['data']);die();
                    $data = ['id' => $rep['data']['id'], 'UID' => $rep['data']['UID'], 'Verification_code' => $rep['data']['Verification_code'], 'isUsed' => 1];
                    $this->CommonModel->updateOtp($data);

                    $redPath = $baseUrl . 'application/ticket-detail';
                    $result = ['result' => true, 'message' => '', 'redirectUrl' => $redPath];
                } else {
                    $msg = "Please enter the correct OTP";

                    /** When Ajax form submit reference */
                    if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                        $viewModel = new JsonModel();
                        $response = array();
                        $response["confirm_otp"] = array($msg);
                        $result = ['result' => false, 'message' => $response];
                        $viewModel->setVariables(['data' => $result]);
                        return $viewModel;
                    }
                }
                //$this->redirect()->toRoute('ticket-detail', ['action' => 'ticket-detail']);
            } else {
                $result = ['result' => false, 'message' => $otpform->getMessages()];
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }
    }

    public function ticketDetailAction() {
        $sessionContainer = new Container('print_ticket');
        $booking_details = $sessionContainer->booking_detail;
        //echo '<pre>';print_r($booking_details);die();
        $ticket_type = $sessionContainer->ticket_type;
        if ($ticket_type == "track-car") {
            $heading = "Track Car";
        } else if ($ticket_type == "print-sms") {
            $heading = "Print/SMS Ticket";
        } else if ($ticket_type == "cancel-ticket") {
            $heading = "Cancel Ticket";
        } else if ($ticket_type == "refund") {
            $heading = "Refund Status";
        } else if ($ticket_type == "change-travel-date") {
            $heading = "Change Travel Date";
        }
        $viewModel = new ViewModel(['booking_details' => $booking_details, 'ticket_type' => $ticket_type, 'heading' => $heading]);
        return $viewModel;
    }

    public function ticketSmsAction() {
        $viewModel = new ViewModel();
        $sessionContainer = new Container('print_ticket');
        $booking_details = $sessionContainer->booking_detail;
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $mobileNo = $booking_details['user_mobile'];
            //$mobileNo = '9313504429';
            $user_name = $booking_details['user_name'];
            $smsparam = ['template_name' => 'acc_verify_code', 'mobile' => $mobileNo, 'user_name' => $user_name, 'otp' => '1234'];
            /*$smsparam = [
                'template_name' => 'booking',
                'mobile' => $mobileNo,
                'user_name' => $user_name,
                'booking_ref_no' => $booking_details['ref'],
                'pickup_time' => $booking_details['ordertime'],
                'estimated_price' => $booking_details['estimated_final_price'],
            ];*/
            $res = $this->sendSMS($smsparam);
            if ($res == "Sent.") {
                $status = true;
                $msg = "SMS Sent Successfully";
            } else {
                $status = false;
                $msg = "SMS not Sent";
            }
            $result = ['result' => $status, 'message' => $msg];
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }
    }

    public function ticketMailAction() {
        $viewModel = new ViewModel();
        $sessionContainer = new Container('print_ticket');
        $booking_details = $sessionContainer->booking_detail;

        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $data = $this->getRequest()->getPost();
            $email = $data['email'];
            //echo '<pre>';print_r($booking_details);die();
            /////////////////

            $id = $this->config()->getConfig()->company->companyId;
            $compJsonData = $this->getCompanySetupDetails($id);

            $fromName = $compJsonData['site_title'];
            $fromEmail = $compJsonData['global_email'];
            $subject = 'Booking Ticket';
            $transport = new SmtpTransport();

            $options = new SmtpOptions(array(
                //'host' => $this->config()->getConfig()->smtpMail->host,
                'host' => $compJsonData['smtp_host'],
                'connection_class' => 'login',
                'connection_config' => array(
                    'ssl' => 'tls',
                    //'username' => $this->config()->getConfig()->smtpMail->username,
                    //'password' => $this->config()->getConfig()->smtpMail->password,
                    'username' => $compJsonData['smtp_username'],
                    'password' => $compJsonData['smtp_password'],
                ),
                'port' => $compJsonData['smtp_port'],
            ));

            /* $options = new SmtpOptions(array(
              'host' => $this->config()->getConfig()->smtpMail->host,
              'connection_class' => 'login',
              'connection_config' => array(
              'tls' => 'tls',
              'username' => $this->config()->getConfig()->smtpMail->username,
              'password' => $this->config()->getConfig()->smtpMail->password,
              ),
              'port' => $this->config()->getConfig()->smtpMail->port,
              )); */
            $template = "Hello Please find the Booking Ticket";
            $html = new MimePart($template);
            $html->type = "text/html";
            $body = new MimeMessage();
            //$body->addPart($html);
            $body->setParts(array($html,));

            $mail = new Message();
            $mail->setBody($body);
            $mail->setFrom($fromEmail, $fromName);
            $mail->setTo($email);
            $mail->setSubject($subject);
            $transport->setOptions($options);
            $sent = true;
            try {
                $transport->send($mail);
            } catch (\Zend\Mail\Transport\Exception\ExceptionInterface $e) {
                $sent = false;
            }
            if ($sent) {
                $status = true;
                $msg = "Mail Sent Successfully";
            } elseif (!$sent) {
                $status = false;
                $msg = "Mail not Sent";
            }

            /////////////////

            $result = ['result' => $status, 'message' => $msg];
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }
    }

    public function ticketCancelAction() {
        $viewModel = new ViewModel();
        $sessionContainer = new Container('print_ticket');
        $booking_details = $sessionContainer->booking_detail;

        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $data = $this->getRequest()->getPost();
            $booking_id = $data['booking_id'];

            $data = [
                'booking_id' => $booking_id,
                'status' => 20
            ];
            $res = $this->CommonModel->cancelBooking($data);
            //echo '<pre>';print_r($res);die();
            if ($res['response']['affectedRows'] > 0) {
                $status = true;
                $msg = "Booking Cancel Successfully";
            } else {
                $status = false;
                $msg = "Booking not Cancelled";
            }

            /////////////////

            $result = ['result' => $status, 'message' => $msg];
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }
    }

    public function changeTravelDateAction() {
        $viewModel = new ViewModel();
        $sessionContainer = new Container('print_ticket');
        $booking_details = $sessionContainer->booking_detail;

        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $data = $this->getRequest()->getPost();
            $booking_id = $data['booking_id'];
            $booking_date = $data['booking_date'];
            $booking_time = $data['booking_time'];

            $data = [
                'booking_id' => $booking_id,
                'pickup_date' => date('Y-m-d', strtotime($data['booking_date'])),
                'pickup_time' => $data['booking_time']
            ];
            //echo '<pre>';print_r($data);die();
            $res = $this->updateBookingDate($data);

            if ($res['response']['affectedRows'] > 0) {
                $status = true;
                $msg = "Booking Date Change Successfully";
            } else {
                $status = false;
                $msg = "Booking Date not Changed";
            }

            /////////////////

            $result = ['result' => $status, 'message' => $msg];
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }
    }

    public function giveFeedbackAction() {
        $viewModel = new ViewModel(['captchaKey' => $this->config()->getConfig()->googleCaptcha->siteKey]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function submitFeedbackAction() {
        $captchaerror = '';
        $viewModel = new ViewModel();
        $session = new Container('userlogin');
        $user_id = $session->userData['user_id'];
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $postdata = $request->getPost()->toArray();
            if ($postdata['g-recaptcha-response'] == '') {
                $captchaerror = 'Please check the captcha';
            }
            if ($captchaerror == '') {
                $data = [
                    'reservation' => $postdata['reservation'],
                    'web_booking_rate' => $postdata['web_booking_rate'],
                    'web_confirm_rate' => $postdata['web_confirm_rate'],
                    'web_service_rate' => $postdata['web_service_rate'],
                    'android_app_rate' => $postdata['android_app_rate'],
                    'android_booking_rate' => $postdata['android_booking_rate'],
                    'android_confirm_rate' => $postdata['android_confirm_rate'],
                    'android_service_rate' => $postdata['android_service_rate'],
                    'call_book_rate' => $postdata['call_book_rate'],
                    'call_agent_rate' => $postdata['call_agent_rate'],
                    'call_instruction_rate' => $postdata['call_instruction_rate'],
                    'call_confirmation_rate' => $postdata['call_confirmation_rate'],
                    'call_services_rate' => $postdata['call_services_rate'],
                    'vehicle_rate' => $postdata['vehicle_rate'],
                    'requested_rate' => $postdata['requested_rate'],
                    'instruction_follow_rate' => $postdata['instruction_follow_rate'],
                    'vehicle_condition' => $postdata['vehicle_condition'],
                    'aircondition_effective_rate' => $postdata['aircondition_effective_rate'],
                    'cleanness_rate' => $postdata['cleanness_rate'],
                    'grooming_rate' => $postdata['grooming_rate'],
                    'accuracy_rate' => $postdata['accuracy_rate'],
                    'invoice_time_rate' => $postdata['invoice_time_rate'],
                    'receivingInv_rate' => $postdata['receivingInv_rate'],
                    'user_id' => $user_id,
                    'created_date' => date('Y-m-d'),
                    'ip' => $_SERVER['REMOTE_ADDR']
                ];
                $res = $this->insertFeedbackData($data);
                if ($res != "") {
                    $status = true;
                    $msg = "Feedback Submit Successfully";
                } else {
                    $status = false;
                    $msg = "Feedback not Submitted";
                }
                $result = ['result' => $status, 'message' => $msg];
            } else {
                $result = ['result' => false, 'error' => $captchaerror];
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }
    }

    public function insertFeedbackData($data) {
        $url = $this->apiUrl() . "/feedback";
        $resp = $this->post($url, $data);
        $data = Json::decode($resp->getBody(), true);
        return $data;
    }

    public function termsConditionAction() {
        $id = $this->config()->getConfig()->company->companyId;
        $pageData = $this->CommonModel->getCmsPageData('terms-of-use',$id);
        $viewModel = new ViewModel(['pageData' => $pageData[0]]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function updateBookingStatus($data) {
        $url = $this->apiUrl() . "/Booking/updatebookingstatus";
        $resp = $this->post($url, $data);
        $data = Json::decode($resp->getBody(), true);
        return $data;
    }



    public function updateBookingDate($data) {
        //echo '<pre>';print_r($data);die();
        $url = $this->apiUrl() . "/Booking/updatePickupDateTime";
        $resp = $this->post($url, $data);
        $data = Json::decode($resp->getBody(), true);
        return $data;
    }

    public function resetPasswordOldAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $email_id = $postData['email_id'];
        $url = $this->apiUrl() . "/user/verifyregister?username=" . $email_id;
        $val = $this->get($url);
        $JsonData = $val->getBody();
        $JsonData = Json::decode($JsonData, true);
        //echo '<pre>';print_r($JsonData);die();
        if ($JsonData['responsedata']['status'] == 'success') {
            $password = $this->generateOtp();
            $sendMailParam = [
                'user_name' => 'User',
                'password' => $password,
                'user_email' => $email_id,
                'template_name' => 'reset-password',
                'subject' => 'Reset Password'
            ];
            $mail = $this->sendMail($sendMailParam);
            if ($mail == "success") {
                $finalData = [];
                $finalData = [
                    'password' => md5($password),
                    'id' => $JsonData['responsedata']['data']['user_id']
                ];
                $url = $this->apiUrl() . "/user/changePassword";
                $val = $this->put($url, $finalData);
                $JsonData1 = $val->getBody();
                $JsonData1 = Json::decode($JsonData1, true);
                $data = ['status' => true];
            }
        } else {
            $data = ['status' => false];
        }
        $view = new JsonModel($data);
        return $view;
    }

    public function resetPasswordAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $email_id = $postData['email_id'];
        $url = $this->apiUrl() . "/user/forgetPassword?emailid=" . $email_id;
        $val = $this->get($url);
        $JsonData = $val->getBody();
        $JsonData = Json::decode($JsonData, true);
        //echo '<pre>';print_r($JsonData);die();
        if ($JsonData['responsedata']['status'] == 'success') {
            $data = ['status' => true,'message'=> $JsonData['responsedata']['message']];
        } else {
            $data = ['status' => false,'message'=> $JsonData['responsedata']['message']];
        }
        $view = new JsonModel($data);
        return $view;
    }



    public function holidayEnquiryAction() {
        $viewModel = new ViewModel();
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function offerEnquiryAction() {
        EnquiryForm::$packages = $this->CommonModel->getPackage();
        EnquiryForm::$budget = $this->CommonModel->getBudget();
        EnquiryForm::$vehicleType = $this->CommonModel->getVehicleType();
        $form = new EnquiryForm();



        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $data = $this->getRequest()->getPost();
            $type = $data['type'];
            $form->get('enquiry_type')->setValue($type);
            if ($type == "self-drive") {
                $heading = "Self Drive Enquiry";
            } elseif ($type == "mice") {
                $heading = "Vehicle for Mice";
            } elseif ($type == "wedding") {
                $heading = "Vehicle for Wedding";
            } elseif ($type == "conference") {
                $heading = "Vehicle for Conference";
            } elseif ($type == "luxury") {
                $heading = "Luxury Car";
            } elseif ($type == "tours") {
                $heading = "Vehicle for Tours";
            } elseif ($type == "hotel") {
                $heading = "Hotel Enquiry";
            } elseif ($type == "international-destination") {
                $heading = "International Destination";
            } elseif ($type == "holiday_enquiry") {
                $heading = "Holiday Enquiry";
            }
        }

        $viewModel = new ViewModel([
            'captchaKey' => $this->config()->getConfig()->googleCaptcha->siteKey,
            'heading' => $heading,
            'type' => $type,
            'form' => $form
        ]);
        /* if ($type == "self-drive") {
          $viewModel->setTemplate('application/index/self-drive.phtml');
          }elseif ($type == "mice" || $type == "wedding" || $type == "conference") {
          $viewModel->setTemplate('application/index/mice-wedding.phtml');
          }elseif ($type == "luxury") {
          $viewModel->setTemplate('application/index/luxury.phtml');
          }elseif ($type == "tours") {
          $viewModel->setTemplate('application/index/tours.phtml');
          }elseif ($type == "hotel") {
          $viewModel->setTemplate('application/index/hotel-enquiry.phtml');
          } */
        $viewModel->setTemplate('application/index/enquiry.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function relationshipManagerAction() {
        $session = new Container('userlogin');
        $user_id = $session->userData['user_id'];
        if ($user_id == "") {
            $this->redirect()->toRoute('home');
        }
        $user_id = '1551';
        // Need to Call API ///
        $url = $this->apiUrl() . "/user-management/userRelationManager?id=" . $user_id;
        $val = $this->get($url);
        $JsonData = $val->getBody();
        $val = Json::decode($JsonData, true);
        $data = $val['responsedata'];
        if(!empty($data)){
        $session->userData['userRelationManager']=$data;

        }
        // Need to Call API ///
        $viewModel = new ViewModel(['data' => $data]);
        return $viewModel;
    }



    public function getToCityListAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $term = $postData['term'];
        $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 submitEnquiryAction() {

        $viewModel = new ViewModel();
        $request = $this->getRequest();
        $form = new EnquiryForm();
        $msg = '';
        $captchaerror = '';
        if ($request->isXmlHttpRequest()) {
            //echo "Mohit"; die;
            $postdata = $request->getPost()->toArray();
            $form->setData($postdata);
            if ($postdata['g-recaptcha-response'] == '') {
                $captchaerror = 'Please check the captcha';
            }
            if ($form->isValid() && $captchaerror == '') {
                //echo '<pre>';print_r($postdata);die();

                $params = [
                    'firstname' => $postdata['customer_name'],
                    'email' => $postdata['customer_email'],
                    'mobile' => $postdata['customer_mobile'],
                    'cf_864' => $postdata['origin_city'],
                    'cf_868' => $postdata['start_date'],
                    'cf_870' => $postdata['start_time'],
                    'cf_872' => $postdata['end_date'],
                    'cf_874' => $postdata['end_time'],
                    'cf_852' => $postdata['package_name'],
                    'cf_876' => $postdata['budget'],
                    'cf_856' => $postdata['adults'],
                    'cf_858' => $postdata['childs'],
                    'cf_860' => $postdata['luggages'],
                    'cf_866' => $postdata['enquiry_type'],
                    'cf_878' => isset($postdata['vehicle_type']) ? $postdata['vehicle_type'] : '',
                    'assigned_user_id' => 'administrator'
                ];

                //////// Code to Insert Lead in VTiger CRM ///////////

                $val    =   $this->insertEnquiryDetails($params);
                if($val['message']=="success"){
                    $status = true;
                    $msg = $val['message'];
                }else{
                    $status = false;
                    $msg = $val['message'];
                }
                $result = ['result' => $status, 'message' => $msg];

                //////// Code to Insert Lead in VTiger CRM ///////////
            } else {
                $result = ['result' => false, 'message' => $form->getMessages(), 'error' => $captchaerror];
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }
    }

    public function insertEnquiryDetails($params) {
        $serveraddress = $this->config()->getConfig()->vTigerCrm->url;
        $crm_username = $this->config()->getConfig()->vTigerCrm->username;
        $crm_userpassword = $this->config()->getConfig()->vTigerCrm->password;
        $crm_useraccesskey = $this->config()->getConfig()->vTigerCrm->accesskey;

        $token_url = $serveraddress . "/webservice.php?operation=getchallenge&username=" . $crm_username;
        $token_data = json_decode(file_get_contents($token_url));
        //echo '<pre>';print_r($token_data);die();

        if ($token_data->success == 1) {
            $crm_token = $token_data->result->token;
            // Attempt Login
            $service_url = $serveraddress . "/webservice.php";
            $curl = curl_init($service_url);
            $curl_post_data = array(
                'operation' => 'login',
                'username' => $crm_username,
                'accessKey' => md5($crm_token . $crm_useraccesskey),
            );
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $curl_post_data);
            $curl_response = json_decode(curl_exec($curl));
            if ($curl_response->success == 1) {
                $crm_session = $curl_response->result->sessionName;

                // Create Contact through API POST request
                $curl1 = curl_init($service_url);

                $objectJson = json_encode($params);
                $moduleName = 'Leads';
                $curl_post_data1 = array(
                    'sessionName' => $crm_session,
                    'operation' => 'create',
                    'element' => $objectJson,
                    'elementType' => $moduleName,
                );

                curl_setopt($curl1, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($curl1, CURLOPT_POST, true);
                curl_setopt($curl1, CURLOPT_POSTFIELDS, $curl_post_data1);

                $curl_response1 = json_decode(curl_exec($curl1));
                $message    =   'success';
                // response to display
                $response = [
                    'status' => 200,
                    'payload' => $params,
                    'message' => $message
                ];
            } else {
                $message    =   'Invalid user credentials';
                $response = [
                    'status' => 200,
                    'payload' => '',
                    'message' => $message
                ];
            }
        } else {
                $message    =   'Access denied';
                $response = [
                    'status' => 200,
                    'payload' => '',
                    'message' => $message
                ];
        }
        //$response   =   json_encode($response);
        //echo '<pre>';print_r($response);die();
        return $response;
    }

    public function jdDetailsAction() {
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $data = $this->getRequest()->getPost();
            $post_id = $data['post_id'];
            $jobsData   =   $this->CommonModel->getJobsDataByPostId($post_id);
        }
        $viewModel = new ViewModel([
            'jobsData' => $jobsData,
        ]);
        $viewModel->setTemplate('application/index/job-description.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function jobEnquiryAction() {
        $form = new JobEnquiryForm();
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $data = $this->getRequest()->getPost();
            $post_id = $data['post_id'];
            $jobsData   =   $this->CommonModel->getJobsDataByPostId($post_id);
            $form->get('post_name')->setValue($jobsData['position_name']);
        }

        $viewModel = new ViewModel([
            'captchaKey' => $this->config()->getConfig()->googleCaptcha->siteKey,
            'jobsData' => $jobsData,
            'form' => $form
        ]);
        $viewModel->setTemplate('application/index/job-enquiry.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function submitJobEnquiryAction() {
        $viewModel = new ViewModel();
        $request = $this->getRequest();
        $form = new JobEnquiryForm();
        $msg = '';
        $captchaerror = '';
        if ($request->isXmlHttpRequest()) {
            //echo "Mohit"; die;
            $postdata = $request->getPost()->toArray();
            $form->setData($postdata);
            if ($postdata['g-recaptcha-response'] == '') {
                $captchaerror = 'Please check the captcha';
            }
            if ($form->isValid() && $captchaerror == '') {
                //echo '<pre>';print_r($postdata);die();

                $params = [
                    'firstname' => $postdata['customer_name'],
                    'email' => $postdata['customer_email'],
                    'mobile' => $postdata['customer_mobile'],
                    'description' => $postdata['description'],
                    'cf_880' => $postdata['experience'],
                    'cf_866' => 'Job posting',
                    'designation' => $postdata['post_name'],
                    'assigned_user_id' => 'administrator'
                ];

                //////// Code to Insert Lead in VTiger CRM ///////////

                $val    =   $this->insertEnquiryDetails($params);
                if($val['message']=="success"){
                    $status = true;
                    $msg = $val['message'];
                }else{
                    $status = false;
                    $msg = $val['message'];
                }
                $result = ['result' => $status, 'message' => $msg];

                //////// Code to Insert Lead in VTiger CRM ///////////
            } else {
                $result = ['result' => false, 'message' => $form->getMessages(), 'error' => $captchaerror];
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }
    }

    public function oneWaySearchAction() {
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $data = $this->getRequest()->getPost();
            $distance=0;
            //echo '<pre>';print_r($data);//die();
                $pickAreaData = $this->CommonModel->fetchGoogleApiData($data['from_city']);
                $pickAreaData = json_decode($pickAreaData);


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

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

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

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

                    $dataDistance = $this->CommonModel->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;
                        $estimated_time = $res->legs[0]->duration->value;
                    }
                    $cityDistance = $this->CommonModel->getCityDistance($data['from_city_id'], $data['to_city_id']);
                    if ($cityDistance > $distance) {
                        $distance = $cityDistance;
                    }
                }
             $fareList = $this->fetchFareDetails($data['from_city_id'], $this->oneWayPackageType, date('H:i:s'), isset($distance) ? $distance : 0, isset($duration) ? $duration : 0, isset($estimated_time) ? $estimated_time : 0, '', '');
             //echo '<pre>';print_r($fareList);die();
        }

        $viewModel = new ViewModel([
            'data' => $data,
            'fareList' => $fareList
                ]);
        $viewModel->setTemplate('application/index/one-way-listing.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }


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

    /** Function to change VEHICLE TYPE STATUS */
    public function removeRecentlyViewedAction() {
        $data1 = [];
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $data = $this->getRequest()->getPost();
        //print_r($data); die;
        $val = ['user_id' => $user_id, 'id' => $data['id'] , 'ip' => $_SERVER['REMOTE_ADDR']];
        $this->CommonModel->deleteRecentViewedItems($val);
        $viewModel = new ViewModel();
        $viewModel->setTemplate('application/index/recent-view.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }
    
    
    public function partnerAction(){      
            $this->redirect()->toUrl('http://b2b.bookingcabs.com');
    }
}