<?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\ForgetPasswordForm;
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;

class IndexController extends RestAPIClientController {

    /**
     *
     * @return ViewModel
     */
    public function indexAction() {
       $viewModel = new ViewModel();
       //$viewModel->setTerminal(true);
       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'] . '  (' . $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 getServiceTypeAction() {
        $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 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'
        ];
        //Debug::dump($compJsonData);
        //die;
        $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 getCompanySetupDetails($id) {
        $url = $this->apiUrl() . "/company-setup/" . $id;
        $resp = $this->get($url);
        $compJsonData = Json::decode($resp->getBody(), true);
        return $compJsonData;
    }

    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');
        $pageData = $this->getCmsPageData($pageType);
        if (isset($pageData[0]) == "") {
            $pageData[0] = '';
        }
        $captchaerror = '';
        if ($pageType == 'contact-us') {
            $id = $this->config()->getConfig()->company->companyId;
            $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->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 = "";
        }
        $viewModel = new ViewModel([
            'pageData' => $pageData[0],
            'form' => $form,
            'status' => $status,
            'error' => $captchaerror,
            'captchaKey' => $this->config()->getConfig()->googleCaptcha->siteKey
        ]);
        $viewModel->setTemplate('application/index/' . $pageType . '.phtml');
        return $viewModel;
    }

    public function getCmsPageData($pageType) {
        $id = $this->config()->getConfig()->company->companyId;
        $val = '{"where":{"and": [{"company_setup_id": "' . $id . '"},{"page_type": "' . $pageType . '"}]}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/cms-pages/?filter=" . $val;
        $resp = $this->get($url);
        $data = Json::decode($resp->getBody(), true);
        return $data;
    }

    public function referEarnAction() {
        $session = new Container('userlogin');
        $user_id = $session->userData['user_id'];
        $referral_key = $session->userData['referral_key'];
        $referralData = $this->getReferralAmt();
        $id = $this->config()->getConfig()->company->companyId;
        $compJsonData = $this->getCompanySetupDetails($id);
        $template = $this->getSmsTemplate('refer_earn');       
        // Array containing search string  
        $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->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->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 getReferralAmt() {
        $val = '{"where": {"user_type":1}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/referral-discount-amount?filter=" . $val;
        $resp = $this->get($url);
        $data = Json::decode($resp->getBody(), true);
        return $data;
    }

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

    public function getOffers() {
        $id = $this->config()->getConfig()->company->companyId;
        $val = '{"where": {"company_id":"' . $id . '"}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/coupon-list?filter=" . $val;
        $resp = $this->get($url);
        $data = Json::decode($resp->getBody(), true);
        return $data;
    }

    public function getDaysArray() {
        $data = ['1' => 'SU', '2' => 'M', '3' => 'T', '4' => 'W', '5' => 'TH', '6' => 'F', '7' => 'SA'];
        return $data;
    }

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

    /**
     * @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";
        }
        $form->get('ticket_type')->setValue($type);
        $otpform->get('ticket_type')->setValue($type);
        $viewModel = new ViewModel(['type' => $type, 'heading' => $heading, 'form' => $form, 'otpform' => $otpform]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function submitTicketAction() {
        $viewModel = new ViewModel();
        $request = $this->getRequest();
        $form = new TicketForm();
        $msg = '';
        if ($request->isXmlHttpRequest()) {
            $postdata = $request->getPost()->toArray();
            $form->setData($postdata);
            if ($form->isValid()) {
                $session = new Container("print_ticket");
                $session->getManager()->getStorage()->clear('print_ticket');
                $bookingNo = trim($postdata['booking_no']);
                $mobileNo = trim($postdata['mobile_no']);
                $ticketType = $postdata['ticket_type'];

                $apiParams = ['booking_id' => $bookingNo, 'user_mobile' => $mobileNo];
                $url = $this->apiUrl() . "/booking/bookingList";
                $resp = $this->post($url, $apiParams);
                $bookingList = Json::decode($resp->getBody(), true);

                if ($bookingList['responsedata']['status']=='success') {
                    $bookinginfo  = $bookingList['responsedata']['data'];
                    $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->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()];
            }
            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->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->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;
        $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";
        }
        $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'];
            $otp = '1234';
            $smsparam = ['template_name' => 'acc_verify_code', 'mobile' => $mobileNo, 'user_name' => $user_name, 'otp' => $otp];
            $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,
                '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_c' => 20
            ];
            $res = $this->updateBookingStatus($data);
            //echo '<pre>';print_r($res);die();
            if ($res['response']['affectedRows'] > 0) {
                $status = true;
                $msg = "Booking Cancel Successfully";
            } else {
                $status = false;
                $msg = "Bookign not Cancelled";
            }

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

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

    public function insertOtp($data) {
        $url = $this->apiUrl() . "/activation";
        $resp = $this->post($url, $data);
        $response = Json::decode($resp->getBody(), true);
        //Debug::dump($response);
        //exit;
        return $response;
    }

    public function fetchOtp($data) {
        $user_id = $data['user_id'];
        $otp = $data['confirm_otp'];
        $val = '{"where":{"and": [{"UID": "' . $user_id . '"},{"Verification_code": "' . $otp . '"},{"isUsed": 0}]}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/activation?&filter=" . $val;
        $resp = $this->get($url);
        $response = Json::decode($resp->getBody(), true);
        return $response;
    }

    public function updateOtp($data) {
        $url = $this->apiUrl() . "/activation";
        $resp = $this->put($url, $data);
        $response = Json::decode($resp->getBody(), true);
        //Debug::dump($response);
        //exit;
        return $response;
    }

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

    public function submitFeedbackAction() {
        $viewModel = new ViewModel();
        $session = new Container('userlogin');
        $user_id = $session->userData['user_id'];
        $request = $this->getRequest();
        if ($request->isXmlHttpRequest()) {
            $postdata = $request->getPost()->toArray();
            $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];
            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() {
        $pageData = $this->getCmsPageData('terms-of-use');
        $viewModel = new ViewModel(['pageData' => $pageData[0]]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }

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

    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 forgotPasswordAction() {
        $status_type = "";
        $msg = "";
        $sessionUser = new Container('userlogin');
        $user_id = $sessionUser->userData['user_id'];
        if ($user_id != "") {
            $this->redirect()->toRoute('home');
        }
            $form = new ForgetPasswordForm();
            $request = $this->getRequest();
            if ($request->isPost()) {
                $post = $request->getPost()->toArray();
                //echo '<pre>';print_r($post);die();
                $status_type = $post['forget_password'];
                if($post['forget_password']=='forget_userid'){
                   $form->getInputFilter()->get('password_user_name')->setRequired(false);
                   $form->getInputFilter()->get('password_email_mobile')->setRequired(false);
                   $form->getInputFilter()->get('email_mobile_user_name')->setRequired(false);
                }else if($post['forget_password']=='forget_password'){
                   $form->getInputFilter()->get('user_type')->setRequired(false);
                   $form->getInputFilter()->get('userid_email_mobile')->setRequired(false);
                   $form->getInputFilter()->get('email_mobile_user_name')->setRequired(false);
                }else if($post['forget_password']=='forget_email_mobile'){
                   $form->getInputFilter()->get('user_type')->setRequired(false);
                   $form->getInputFilter()->get('userid_email_mobile')->setRequired(false);
                   $form->getInputFilter()->get('password_user_name')->setRequired(false);
                   $form->getInputFilter()->get('password_email_mobile')->setRequired(false);
                }
                $form->setData($post);
                if ($form->isValid()) {
                    //echo '<pre>';print_r($post);die();
                    $email = "";
                    $user_name= "";
                    $user_type = "";
                    
                    if($post['forget_password']=='forget_userid'){
                        $user_type= $post['user_type'];
                        $email= $post['userid_email_mobile'];
                    } else if($post['forget_password']=='forget_password'){
                        $email= $post['password_email_mobile'];
                        $user_name= $post['password_user_name'];
                    } else if($post['forget_password']=='forget_email_mobile'){
                        $user_name= $post['email_mobile_user_name'];
                    }
                    $data = [
                        'user_type'=> $user_type,
                        'email_mobile'=> $email,
                        'user_name'=> $user_name,
                        'status_type'=>$status_type
                    ];
                    //echo '<pre>';print_r($data);die();
                    $url = $this->apiUrl() . "/user/forgetPasswordNew";
                    $val = $this->post($url,$data);
                    $JsonData = $val->getBody();
                    $JsonData = Json::decode($JsonData, true);
                    $msg = $JsonData['responsedata']['message'];
                    //die;
                    //echo '<pre>';print_r($JsonData);die();
                }else{
                    //$sm = $form->getMessages();
                    //echo '<pre>';print_r($sm);die();
                }
            }
        $viewModel = new ViewModel([
            'form'=>$form,
            'status_type'=>$status_type,
            'msg'=>$msg                
        ]);
        return $viewModel;
    }

}