<?php

namespace User\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\JsonModel;
use Zend\Debug\Debug;
use Zend\View\Model\ViewModel;
use User\Form\{
    LoginForm,
    LoginRedirectForm,
    PopupRegistrationForm,
    ConfirmOtpForm,
    ConfirmLoginOtpForm,
    TicketForm,
    RegistrationForm

};
use Zend\Form\Element\Submit;
use Application\Controller\RestAPIClientController;
use Zend\Validator\{
    NotEmpty,
    Digits
};
use Zend\Session\Container;
use Zend\Json\Json;
use \Zend\Validator\StringLength;
use Zend\Config\Config;
use Zend\Config\Factory;
use User\Model\Registration;
use Dashboard\Model\User;

class IndexController extends RestAPIClientController {


    public function __construct() {
        $this->registrationModel = new Registration();
        $this->userModel = new User();
    }
    public function indexAction() {
        $sessionUser = new Container('userlogin');
        $user_id = $sessionUser->userData['user_id'];
        if ($user_id != "") {
            $this->redirect()->toRoute('home');
        }
        $viewModel = new ViewModel();
        return $viewModel;
    }

    public function affilateRegistrationAction() {
        $viewModel = new ViewModel();
        return $viewModel;
    }

    public function registrationCompleteAction() {

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

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

        $loginForm = new LoginForm();
        $request = $this->getRequest();
        //echo "niharika";die;

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

            // $post = $request->getPost()->toArray();

            if ($loginForm->isValid()) {

                $password = md5($post['password']);
                $userName = $post['username'];
                $valid_mobile = preg_match('/^[0-9]{10}+$/', $username);
                $validate_email = filter_var($username, FILTER_VALIDATE_EMAIL);

                if ($valid_mobile) {
                    $validator = new StringLength();
                    $validator->setMin(10);
                    $validator->setMax(10);
                    $valide_mobile = $validator->isValid("$username");
                }


                if ($valide_mobile || $validate_email) {


                    $password = $loginData['password'];
                    $validator = new StringLength();
                    $validator->setMin(6);
                    $validator->setMax(20);
                    $valid = $validator->isValid("$password");

                    if ($valid) {

                        $finalData = [
                            'username' => $userName,
                            'password' => $password
                        ];

                        $url = $this->apiAdminUrl() . "auth/login";
                        $val = $this->post($url, $finalData);
                        $JsonData = $val->getBody();
                        $JsonData = Json::decode($locationJsonData, true);

                        if ((!empty($JsonData)) && (!$JsonData['error'])) {

                            $status = $JsonData["status"];
                            if ($status == true) {
                                $this->redirect()->toRoute('dashboard', ['action' => 'index']);
                            } else {
                                $msg = "username and password are not matched";
                            }
                        }
                    } else {
                        $msg = "password should be greater than 6 and smaller than 20";
                    }
                } else {
                    $msg = "Username should be valid Mobil no. or valid emailid";
                }
                $data = $this->redirectfunc($JsonData);
                $jsonModel = new JsonModel($data);
                return $jsonModel;
                exit();
            } else {
                return new JsonModel(['error' => $JsonData['error']]);
                exit();
            }

//            if($userName!='' && $password!=''){
//                $url = $this->apiUrl()."auth/login";
//                $val = $this->post($url, $finalData);
//                $locationJsonData = $val->getBody();
//                $locationJsonData = Json::decode($locationJsonData, true);
//
//                echo '<pre>';print_r($locationJsonData);die;
//
//              if (!empty($locationJsonData) && !$locationJsonData['error']) {
//                  $data  = $this->redirectfunc($locationJsonData);
//                  $jsonModel = new JsonModel($data);
//                  return $jsonModel;
//                  exit();
//               }else{
//                  return new JsonModel(['error' =>$locationJsonData['error']]);
//                  exit();
//               }
//           }
        }
        $viewModel = new ViewModel(['form' => $loginForm]);
        // $viewModel->setTemplate('/user/login/login');
        $viewModel->setTerminal(true);

        return $viewModel;
    }

    public function loginOldMohitAction() {
        $loginForm = new LoginForm();
        $request = $this->getRequest();

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


        if ($request->isPost()) {
            $result = [];

            if ($request->isXmlHttpRequest()) {


                $loginForm->setData($request->getPost());
                $post = $request->getPost()->toArray();

                if ($loginForm->isValid()) {

                    $post['password'] = md5($post['password']);
                    $data = $this->userLogin($post);

                    if (isset($data['data']['responsedata']['error']) && $data['data']['responsedata']['error']) {
                        $errorMsg = $data['data']['responsedata']['error'];
                        $result = ['status' => 'error1', 'msg' => $errorMsg];
                        $view = new JsonModel($result);
                        return $view;
                    } elseif ($data['status'] == 000) {
                        $result = ['status' => 'error1', 'msg' => $data['data']];
                        $view = new JsonModel($result);
                        return $view;
                    } else {
                        $sessionUser = new Container('userlogin');
                        //$sessionUser->userData = $data['data']['responsedata'];
                        $sessionUser->user_id = $data['data']['responsedata']['user_id'];
                        $user_id = $data['data']['responsedata']['user_id'];
                        $url = $this->apiUrl() . "/user/userpersonalinfo?user_id=" . $user_id;
                        $resp = $this->get($url);
                        $response = Json::decode($resp->getBody(), true);
                        $sessionUser->userData = $response['responsedata']['data'];
                        $result = ['status' => 'success'];
                        $view = new JsonModel($result);
                        return $view;
                    }
                } else {

                    $result = ['status' => 'error', 'msg' => $loginForm->getMessages()];
                    $view = new JsonModel($result);
                    return $view;
                }
            }
        }





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

        $viewModel = new ViewModel(['form' => $loginForm]);
        $viewModel->setTerminal(true);

        return $viewModel;
    }


        public function login1Action() {
        $loginForm = new LoginForm();
        $request = $this->getRequest();
        $otpform = new ConfirmLoginOtpForm();

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


        if ($request->isPost()) {
            $result = [];

            if ($request->isXmlHttpRequest()) {


                $loginForm->setData($request->getPost());
                $post = $request->getPost()->toArray();

                if ($loginForm->isValid()) {

                    $post['password'] = ($post['password']);
                    $data = $this->userLogin($post);
                    //echo '<pre>';print_r($data);die();
                    if (isset($data['error']) && $data['error']) {
                        $errorMsg = $data['error'];
                        $result = ['status' => 'error1', 'msg' => $errorMsg];
                        $view = new JsonModel($result);
                        return $view;
                    } elseif ($data['status'] == 000) {
                        $result = ['status' => 'error1', 'msg' => $data['error']];
                        $view = new JsonModel($result);
                        return $view;
                    } else {
                        $userTypeArr = $this->config()->getConfig()->loginUserType;
                        $userTypeArr = $userTypeArr->toArray();
                        $user_type_id = $data['data']['user_type_id'];
                        if (in_array($user_type_id, $userTypeArr)) {
                        $sessionUser = new Container('userlogin');
                        //$sessionUser->userData = $data['data']['responsedata'];
                        $sessionUser->user_id = $data['data']['user_id'];
                        $user_id = $data['data']['user_id'];
                        $url = $this->apiUrl() . "/user/userpersonalinfo?user_id=" . $user_id;
                        $resp = $this->get($url);
                        $response = Json::decode($resp->getBody(), true);
                        $sessionUser->userData = $response['responsedata']['data'];
                        $result = ['status' => 'success'];
                         } else {
                            $result = ['status' => 'error1', 'msg' => 'Unauthorized-Access'];
                        }
                        $view = new JsonModel($result);
                        return $view;
                    }
                } else {
                    $result = ['status' => 'error', 'msg' => $loginForm->getMessages()];
                    $view = new JsonModel($result);
                    return $view;
                }
            }
        }
        ////////////

        $viewModel = new ViewModel(['form' => $loginForm,'otpform' => $otpform]);
        $viewModel->setTerminal(true);

        return $viewModel;
    }

    
        public function guestLoginAction() {
        RegistrationForm::$countryprefix = $this->userModel->getCountryCodePrefix();
        $registrationForm = new RegistrationForm();
        $loginForm = new LoginForm();
        $otpform = new ConfirmLoginOtpForm();
        $request = $this->getRequest();
        /////////////////

        $registrationForm->getInputFilter()->get('password')->setRequired(false);
        $registrationForm->getInputFilter()->get('confirm_password')->setRequired(false);
        $registrationForm->getInputFilter()->get('prefix_contact_no')->setRequired(false);
        $registrationForm->getInputFilter()->get('agreeterms')->setRequired(false);
        if ($request->isPost()) {
            $result = [];

            if ($request->isXmlHttpRequest()) {
                $registrationForm->setData($request->getPost());
                $post = $request->getPost()->toArray();
                //echo '<pre>';print_r($post);die();

                if ($registrationForm->isValid()) {

                    $userTypeArr = $this->config()->getConfig()->userTypeId;
                    $userTypeArr = $userTypeArr->toArray();
                    $userTypeId = $userTypeArr['unregister-user'];

                    $first_name = (trim($post['first_name']));
                    $last_name = (trim($post['last_name']));
                    $email = trim($post['email']);
                    $contact_no = trim($post['contact_no']);
                    $mobile_prefix = $post['prefix_contact_no'];
                    $registrationType = $userTypeId;

                    $JsonData = $this->registrationModel->verifyUser($email, $contact_no, $registrationType);
                    //echo '<pre>';print_r($JsonData);die();
                    if((!empty($JsonData)) && ($JsonData['responsedata']['status'])=="success") {
                        $errorMsg = $JsonData['responsedata']['message'];
                        $result = ['status' => 'success', 'msg' => $errorMsg];
                        $view = new JsonModel($result);
                        return $view;
                    }else if((!empty($JsonData)) && ($JsonData['responsedata']['status'])=="failed") {                                                    $finalData = [];
                            $finalData = [
                                'company_id' => $this->config()->getConfig()->company->companyId,
                                'first_name' => $first_name,
                                'last_name' => $last_name,
                                'email' => $email,
                                'mobile' => $contact_no,
                                'mobile_prefix' => $mobile_prefix,
                                'user_type_id' => $registrationType,
                                'password' => $contact_no,
                                'user_grade' => $this->config()->getConfig()->userGrade->defaultGrade,
                            ];
                            $finalData = array_filter($finalData);
                            $finalData['parent_id'] = 0;
                            //echo '<pre>';print_r($finalData);die();
                           // $url = $this->apiUrl() . "/user/userRegistration";
                            //$resp = $this->post($url, $finalData);
                            //$JsonData = Json::decode($resp->getBody(), true);
                            $JsonData = $this->registrationModel->userNewSignup($finalData);
                            //echo '<pre>';print_r($JsonData);die();
                            if (!empty($JsonData)) {
                                if ($JsonData['responsedata']['status'] == 'failed') {
                                    $errorMsg = $JsonData['responsedata']['message'];
                                    $result = ['status' => 'record_exist', 'msg' => 'User Already Exist'];
                                    $view = new JsonModel($result);
                                    return $view;
                                } else if ($JsonData['responsedata']['status'] == 'success') {
                                    $user_id = $JsonData['responsedata']['user_id'];
                                    $sessionUser = new Container('userlogin');
                                    $sessionUser->user_id = $user_id;
                                    //$sessionUser->user_token = $data['data']['token'];
                                    $url = $this->apiUrl() . "/user/userpersonalinfo?user_id=" . $user_id;
                                    $resp = $this->get($url);
                                    $response = Json::decode($resp->getBody(), true);
                                    $sessionUser->userData = $response['responsedata']['data'];
                                    $result = ['status' => 'successLogin'];
                                    $view = new JsonModel($result);
                                    return $view;
                                }
                            } else {
                                    $errorMsg = "Registration not done";
                                    $result = ['status' => 'error1', 'msg' => $errorMsg];
                                    $view = new JsonModel($result);
                                    return $view;
                            }

                            /*$errorMsg = $JsonData['responsedata']['error'];
                            $result = ['status' => 'error1', 'msg' => $errorMsg];
                            $view = new JsonModel($result);
                            return $view;*/
                    }

                } else {
                    //echo '<pre>';print_r($registrationForm->getMessages());die();
                    $result = ['status' => 'error', 'msg' => $registrationForm->getMessages()];
                    $view = new JsonModel($result);
                    return $view;
                }
            }
        }

        $viewModel = new ViewModel(['registrationForm'=>$registrationForm,'form' => $loginForm,'otpform' => $otpform]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }


    public function guestAutoLoginAction() {

        $request = $this->getRequest();
        if ($request->isPost()) {
            $result = [];

            if ($request->isXmlHttpRequest()) {
                $post = $request->getPost()->toArray();
                //echo '<pre>';print_r($post);die();


                    $userTypeArr = $this->config()->getConfig()->userTypeId;
                    $userTypeArr = $userTypeArr->toArray();
                    $userTypeId = $userTypeArr['unregister-user'];

                    $first_name = (trim($post['first_name']));
                    $last_name = (trim($post['last_name']));
                    $email = trim($post['email']);
                    $contact_no = trim($post['contact_no']);
                    $mobile_prefix = $post['prefix_contact_no'];
                    $registrationType = $userTypeId;

                    $JsonData = $this->registrationModel->verifyUser($email, $contact_no, $registrationType);
                    //echo '<pre>';print_r($JsonData);die();
                    if((!empty($JsonData)) && ($JsonData['responsedata']['status'])=="success") {
                        $user_id = $JsonData['responsedata']['data']['user_id'];
                        $sessionUser = new Container('userlogin');
                        $sessionUser->user_id = $user_id;
                        //$sessionUser->user_token = $data['data']['token'];
                        $url = $this->apiUrl() . "/user/userpersonalinfo?user_id=" . $user_id;
                        $resp = $this->get($url);
                        $response = Json::decode($resp->getBody(), true);
                        $sessionUser->userData = $response['responsedata']['data'];
                        $result = ['status' => 'successLogin'];
                        $view = new JsonModel($result);
                        return $view;
                    }else{
                            $finalData = [];
                            $finalData = [
                                'company_id' => $this->config()->getConfig()->company->companyId,
                                'first_name' => $first_name,
                                'last_name' => $last_name,
                                'email' => $email,
                                'mobile' => $contact_no,
                                'mobile_prefix' => $mobile_prefix,
                                'user_type_id' => $registrationType,
                                'password' => $contact_no,
                                'user_grade' => $this->config()->getConfig()->userGrade->defaultGrade,
                            ];
                            $finalData = array_filter($finalData);
                            $finalData['parent_id'] = 0;
                           
                            $JsonData = $this->registrationModel->userNewSignup($finalData);
                            
                            if (!empty($JsonData)) {
                                if ($JsonData['responsedata']['status'] == 'failed') {
                                    $errorMsg = $JsonData['responsedata']['message'];
                                    $result = ['status' => 'record_exist', 'msg' => 'User Already Exist'];
                                    $view = new JsonModel($result);
                                    return $view;
                                } else if ($JsonData['responsedata']['status'] == 'success') {
                                    $user_id = $JsonData['responsedata']['user_id'];
                                    $sessionUser = new Container('userlogin');
                                    $sessionUser->user_id = $user_id;                                    
                                    $url = $this->apiUrl() . "/user/userpersonalinfo?user_id=" . $user_id;
                                    $resp = $this->get($url);
                                    $response = Json::decode($resp->getBody(), true);
                                    $sessionUser->userData = $response['responsedata']['data'];
                                    $result = ['status' => 'successLogin'];
                                    $view = new JsonModel($result);
                                    return $view;
                                }
                            
                        }
                }


            }
        }

        $viewModel = new ViewModel();
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function loginAction() {
        $loginForm = new LoginForm();
        RegistrationForm::$countryprefix = $this->userModel->getCountryCodePrefix();
        $registrationForm = new RegistrationForm();
        $request = $this->getRequest();
        $otpform = new ConfirmLoginOtpForm();
        /////////////////


        if ($request->isPost()) {
            $result = [];

            if ($request->isXmlHttpRequest()) {


                $loginForm->setData($request->getPost());
                $post = $request->getPost()->toArray();

                if ($loginForm->isValid()) {
                    $post['password'] = ($post['password']);
                    $post['sms_send_status'] = "true";
                    $post['ip'] = $_SERVER['REMOTE_ADDR'];

                    $visitorLatitude = isset($_COOKIE['visitor_latitude'])? $_COOKIE['visitor_latitude']:'';
                    $visitorLongitude = isset($_COOKIE['visitor_longitude'])? $_COOKIE['visitor_longitude']:'';
                    $post['lat'] = $visitorLatitude;
                    $post['log'] = $visitorLongitude;
                    $content =   $this->fetchGoogleApiData($post['lat'],$post['log']);
                    $metadata = Json::decode($content, true);
                    if(count($metadata['results']) > 0) {
                        $result = $metadata['results'][0];
                        $post['login_location'] = $result['formatted_address'];
                    }
                    else {
                        $post['login_location'] = "";
                    }
                    $post['callfrom']='web';
                    $data = $this->userLogin($post);
                    //echo '<pre>';print_r($data);die();
                    if (isset($data['error']) && $data['error']) {
                        $errorMsg = $data['error'];
                        $result = ['status' => 'error1', 'msg' => $errorMsg];
                        $view = new JsonModel($result);
                        return $view;
                    } elseif ($data['status'] == 000) {
                        $result = ['status' => 'error1', 'msg' => $data['error']];
                        $view = new JsonModel($result);
                        return $view;
                    } else {
                        $userTypeArr = $this->config()->getConfig()->loginUserType;
                        $userTypeArr = $userTypeArr->toArray();
                        $user_type_id = $data['data']['user_type_id'];

                        $alluserArr = $this->config()->getConfig()->userTypeId;
                        $alluserArr = $alluserArr->toArray();
                        $usertype = array_search ($user_type_id, $alluserArr);


                        $sessionUser = new Container('userlogin');
                        $sessionUser->user_id = $data['data']['user_id'];
                        $sessionUser->mobile = $data['data']['mobile'];
                        $sessionUser->first_name = $data['data']['first_name'];
                        $sessionUser->last_name = $data['data']['last_name'];
                        $sessionUser->email = $data['data']['email'];

                        if (in_array($user_type_id, $userTypeArr)) {

                            $login_otp_status  =   $data['data']['login_otp_status'];

                            $signup_status = $data['data']['signup_status'];
                            if ($signup_status == 1) {
                                $result = ['signup_status' => $signup_status,'redirecturl'=>$usertype."/confirmotp"];
                                //$this->redirect()->toRoute($usertype, ['action' => 'confirmotp']);
                            }
                            else if ($signup_status == 2) {
                                $result = ['signup_status' => $signup_status,'redirecturl'=>$usertype."/personal-info"];
                               // $this->redirect()->toRoute($usertype, ['action' => 'personal-info']);
                            } else if ($signup_status == 3) {
                                $result = ['signup_status' => $signup_status,'redirecturl'=>$usertype."/company-info"];
                                //$this->redirect()->toRoute($usertype, ['action' => 'company-info']);
                            }else if($data['data']['login_otp_status']==1){
                            $sessionUser = new Container('confirmuserlogin');
                            $sessionUser->user_id = $data['data']['user_id'];
                            $user_id = $data['data']['user_id'];
                            $mobile = $data['data']['mobile'];
                            $first_name = $data['data']['first_name'];
                            $sessionUser->user_token = $data['data']['token'];

                            //Send SMS To user
                            //$otp = $this->generateOtp();
                            //$templateName = 'acc_verify_code';

                            //$smsparam = ['template_name' => $templateName, 'mobile' => $mobile, 'user_name' => $first_name, 'otp' => $otp];

                            //$this->sendTxtMsg($smsparam);
                            /* End */


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

                            $result = ['status' => 'success'];
                            }else{
                                $user_id = $data['data']['user_id'];
                                $sessionUser = new Container('userlogin');
                                $sessionUser->user_id = $user_id;
                                $sessionUser->user_token = $data['data']['token'];
                                $sessionUser->login_location = $post['login_location'];
                                $url = $this->apiUrl() . "/user/userpersonalinfo?user_id=" . $user_id;
                                $resp = $this->get($url);
                                $response = Json::decode($resp->getBody(), true);
                                $sessionUser->userData = $response['responsedata']['data'];
                                $result = ['status' => 'successLogin'];
                            }
                        } else {
                            $result = ['status' => 'error1', 'msg' => 'Unauthorized-Access'];
                        }
                        $view = new JsonModel($result);
                        return $view;
                    }
                } else {

                    $result = ['status' => 'error', 'msg' => $loginForm->getMessages()];
                    $view = new JsonModel($result);
                    return $view;
                }
            }
        }

        $viewModel = new ViewModel(['form' => $loginForm, 'otpform' => $otpform, 'registrationForm'=>$registrationForm]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }

      public function confirmLoginOtpAction() {
        $sessionUserLogin = new Container('userlogin');
        $user_id = $sessionUserLogin->user_id;
        $token = $sessionUserLogin->user_token;
//        if ($user_id == "") {
//            return $this->redirect()->toRoute('home');
//        }
        $otpform = new ConfirmLoginOtpForm();
        $request = $this->getRequest();
        /////////////////
        if ($request->isPost()) {
            $result = [];
            if ($request->isXmlHttpRequest()) {
                $otpform->setData($request->getPost());
                $post = $request->getPost()->toArray();
                //echo '<pre>';print_r($post);die();
                //if($post['confirm_otp'])
                if($post['type']=='confirm'){

                if ($otpform->isValid()) {
                    $data = [
                        'user_id' => $user_id,
                        'confirm_otp' => $post['confirm_otp']
                    ];
                    //echo '<pre>';print_r($data);die();
                    $rep = $this->fetchOtp($data);
                    //echo '<pre>';print_r($rep);die();
                    if ($rep['status'] == "success") {
                        //unset($sessionUserLogin->user_id);
                        $sessionUser = new Container('userlogin');
                        $sessionUser->user_id = $user_id;
                        $sessionUser->login_location = $user_id;
                        $sessionUser->user_token = $token;
                        $sessionUser->login_location = $sessionUserLogin->login_location;

                        $url = $this->apiUrl() . "/user/userpersonalinfo?user_id=" . $user_id;
                        $resp = $this->get($url);
                        $response = Json::decode($resp->getBody(), true);
                        $sessionUser->userData = $response['responsedata']['data'];
                        $data = ['id' => $rep['data']['id'], 'UID' => $rep['data']['UID'], 'Verification_code' => $rep['data']['Verification_code'], 'isUsed' => 1];
                        $this->updateOtp($data);
                        $result = ['status' => 'success'];
                        $view = new JsonModel($result);
                        return $view;
                    } else {
                        $msg = "Please enter the correct OTP";
                        $response = array();
                        $response["confirm_otp"] = array($msg);
                        $result = ['status' => 'error', 'msg' => $response];
                        $view = new JsonModel($result);
                        return $view;
                    }
                } else {
                    $result = ['status' => 'error', 'msg' => $otpform->getMessages()];
                    $view = new JsonModel($result);
                    return $view;
                }
                }else {
                        $resentotpresp = $this->registrationModel->resentOtp($user_id);

                       /* $url = $this->apiUrl() . "/user/userpersonalinfo?user_id=" . $user_id;
                        $resp = $this->get($url);
                        $response = Json::decode($resp->getBody(), true);
                        $data   =   $response['responsedata']['data'];

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

                        //echo '<pre>';print_r($compJsonData);die();
                        $otp = $this->generateOtp();
                        $smsparam = [
                            'template_name' => 'acc_verify_code',
                            'user_id'=> $data['user_id'],
                            'mobile' => $data['mobile'],
                            //'mobile' => '9313504429',
                            'user_name' => $data['first_name'],
                            'otp' => $otp,
                            'company_name' => $compJsonData['com_name'],
                            'site_url'=>$compJsonData['site_url'],
                            'sms_param' =>[$data['first_name'],$compJsonData['com_name'],$compJsonData['site_url']]
                        ];

                        //echo '<pre>';print_r($smsparam);die();
                        $this->sendResendOtp($smsparam);
                        //$this->sendTxtMsg($smsparam);
                        //$otpData = ['UID' => $user_id, 'Verification_code' => $otp];
                        //$this->insertOtp($otpData);*/
                        $msg = ($resentotpresp['responsedata']['message']!='')?$resentotpresp['responsedata']['message']:'';
                        $result = ['status' => $resentotpresp['responsedata']['status'], 'msg' => $msg];
                        $view = new JsonModel($result);
                        return $view;
                        /// END

                }
            }
        }

        $viewModel = new ViewModel(['otpform' => $otpform]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }
   /* public function confirmLoginOtpAction() {
        //$sessionUserLogin = new Container('confirmuserlogin');
        $sessionUserLogin = new Container('userlogin');
        $user_id = $sessionUserLogin->user_id;
        $token = $sessionUserLogin->user_token;
//        if ($user_id == "") {
//            return $this->redirect()->toRoute('home');
//        }
        $otpform = new ConfirmLoginOtpForm();
        $request = $this->getRequest();
        /////////////////
        if ($request->isPost()) {
            $result = [];
            if ($request->isXmlHttpRequest()) {
                $otpform->setData($request->getPost());
                $post = $request->getPost()->toArray();
                //echo '<pre>';print_r($post);die();
                //if($post['confirm_otp'])
                if ($post['type'] == 'confirm') {

                    if ($otpform->isValid()) {
                        $data = [
                            'user_id' => $user_id,
                            'confirm_otp' => $post['confirm_otp']
                        ];
                        //echo '<pre>';print_r($data);die();
                        $rep = $this->fetchOtp($data);
                        //echo '<pre>';print_r($rep);die();
                        if ($rep['status'] == "success") {
                            //unset($sessionUserLogin->user_id);
                            $sessionUser = new Container('userlogin');
                            $sessionUser->user_id = $user_id;
                            $sessionUser->user_token = $token;

                            $url = $this->apiUrl() . "/user/userpersonalinfo?user_id=" . $user_id;
                            $resp = $this->get($url);
                            $response = Json::decode($resp->getBody(), true);
                            $sessionUser->userData = $response['responsedata']['data'];
                            $data = ['id' => $rep['data']['id'], 'UID' => $rep['data']['UID'], 'Verification_code' => $rep['data']['Verification_code'], 'isUsed' => 1];
                            $this->updateOtp($data);
                            $result = ['status' => 'success'];
                            $view = new JsonModel($result);
                            return $view;
                        } else {
                            $msg = "Please enter the correct OTP";
                            $response = array();
                            $response["confirm_otp"] = array($msg);
                            $result = ['status' => 'error', 'msg' => $response];
                            $view = new JsonModel($result);
                            return $view;
                        }
                    } else {
                        $result = ['status' => 'error', 'msg' => $otpform->getMessages()];
                        $view = new JsonModel($result);
                        return $view;
                    }
                } else {


                    $url = $this->apiUrl() . "/user/userpersonalinfo?user_id=" . $user_id;
                    $resp = $this->get($url);
                    $response = Json::decode($resp->getBody(), true);
                    $data = $response['responsedata']['data'];

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

                    //echo '<pre>';print_r($compJsonData);die();
                    $otp = $this->generateOtp();
                    $smsparam = [
                        'template_name' => 'acc_verify_code',
                        'user_id' => $data['user_id'],
                        'mobile' => $data['mobile'],
                        //'mobile' => '9313504429',
                        'user_name' => $data['first_name'],
                        'otp' => $otp,
                        'company_name' => $compJsonData['com_name'],
                        'site_url' => $compJsonData['site_url'],
                        'sms_param' => [$data['first_name'], $compJsonData['com_name'], $compJsonData['site_url']]
                    ];

                    //echo '<pre>';print_r($smsparam);die();
                    $this->sendResendOtp($smsparam);
                    //$this->sendTxtMsg($smsparam);
                    //$otpData = ['UID' => $user_id, 'Verification_code' => $otp];
                    //$this->insertOtp($otpData);
                    $msg = "OTP Resend Successfully";
                    $result = ['status' => 'success', 'msg' => $msg];
                    $view = new JsonModel($result);
                    return $view;
                    /// END
                }
            }
        }

        $viewModel = new ViewModel(['otpform' => $otpform]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }*/

    /* public function loginSearchAction() {
      $loginForm = new LoginForm();
      PopupRegistrationForm:: $nationalityList = $this->getCountryList();
      $personalInfoForm = new PopupRegistrationForm();
      $otpform = new ConfirmOtpForm();
      $request = $this->getRequest();

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


      if ($request->isPost()) {
      $result = [];

      if ($request->isXmlHttpRequest()) {
      print_r($request->getPost()); die;
      $loginForm->setData($request->getPost());
      $post = $request->getPost()->toArray();

      if ($loginForm->isValid()) {

      $post['password'] = md5($post['password']);
      $data = $this->userLogin($post);

      if ($data['data']['responsedata']['status'] == true) {
      $sessionUser = new Container('userlogin');
      $sessionUser->userData = $data['data']['responsedata'];
      $sessionUser->user_id = $data['data']['responsedata']['user_id'];
      //$this->setconfiguration();
      $result = ['status' => 'success'];
      $view = new JsonModel($result);
      return $view;
      } else {
      $errorMsg = $data['data']['responsedata']['error'];

      $result = ['status' => 'error1', 'msg' => $errorMsg];
      $view = new JsonModel($result);
      return $view;
      }
      } else {
      //Debug::dump($loginForm->getMessages());
      $result = ['status' => 'error', 'msg' => $loginForm->getMessages()];
      $view = new JsonModel($result);
      return $view;
      }
      }
      }

      $viewModel = new ViewModel(['form' => $loginForm, 'personalform' => $personalInfoForm, 'otpform' => $otpform]);
      $viewModel->setTerminal(true);

      return $viewModel;
      } */

    public function redirectfunc($locationJsonData) {
        if (!empty($locationJsonData[userdata][0])) {

            $user_type_id = $locationJsonData[userdata][0]['user_type_id'];
            $user_id = $locationJsonData[userdata][0]['id'];
            $phone_no = $locationJsonData[userdata][0]['mobile'];
            $first_name = $locationJsonData[userdata][0]['first_name'];
            $email = $locationJsonData[userdata][0]['email'];

            $sessionContainer = new Container('login_redirect');
            $sessionContainer->user_type_id = $user_type_id;
            $sessionContainer->user_id = $user_id;
            $sessionContainer->phone_no = $phone_no;
            $sessionContainer->first_name = $first_name;
            $sessionContainer->email = $email;
        }

        if ($user_type_id == 1 || $user_type_id == 2 || $user_type_id == 3) {
            return $return = ['redirect' => 'dashboard'];
        }
    }

    public function logoutAction() {
        $sessionUser = new Container('userlogin');
        $user_tokendata = $this->userToken();
        //echo'<pre>';print_r($user_tokendata);die();
        unset($sessionUser->user_id);
        unset($sessionUser->userData);
        unset($sessionUser->login_location);
        unset($sessionUser->user_token);
        return $this->redirect()->toRoute('home');
    }

    public function userLogin($data) {
        $val = [];

        $url = $this->apiUrl() . "/user/login";
        $resp = $this->post($url, $data);
        $response = Json::decode($resp->getBody(), true);

//        if(isset($response['response_status']) && !empty($response['response_status'])){
//            return  $val = ["status" => $response['response_status']['status'], "data" =>$response['response_status']['message']];
//        }

        $responseStatus = $response['responsedata']['status'];

        if ($responseStatus == "success") {
            $val = ["status" => true, "data" => $response['responsedata']['data']];
        } else {
            $val = ["status" => false, "error" => $response['responsedata']['error']];
        }
        return $val;
        //Debug::dump($response);
        //exit;
    }

    public function setconfiguration() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];
        $comp_id = $loginData['company_id'];
        $compData = $this->getCompanySetupDetails($comp_id);
        //echo '<pre>';print_r($compData);//die();
        $filename = getcwd() . '/config/autoload/customconfig.php';
        $configFile = Factory::fromFile($filename);
        $configFile['site_name'] = $compData['site_name'];
        $configFile['site_title'] = $compData['site_title'];
        $configFile['global_email'] = $compData['global_email'];
        $configFile['admin_footer'] = $compData['admin_footer'];
        $configFile['admin_footer_url'] = $compData['admin_footer_url'];
        $configFile['frontend_footer'] = $compData['frontend_footer'];
        $configFile['frontend_footer_url'] = $compData['frontend_footer_url'];
        $configFile['admin_header_logo'] = $compData['admin_header_logo'];
        $configFile['frontend_header_logo'] = $compData['frontend_header_logo'];
        $configFile['admin_favicon'] = $compData['admin_favicon'];
        $configFile['frontend_favicon'] = $compData['frontend_favicon'];


        if (!Factory::toFile($filename, $configFile)) {
            $result = ['result' => false, 'message' => 'Can\'t put content to ' . $filename . 'due to file permission issue.'];
        } else {
            $result = ['result' => true, 'message' => 'Cofiguration content has been set successfully.'];
        }
        return $result;
    }

    public function getCountryList() {
        $countryJsonDataArray = [];
        $url = $this->apiUrl() . "/country";
        $resp = $this->get($url);
        $countryJsonData = Json::decode($resp->getBody(), true);
        foreach ($countryJsonData as $res) {
            $countryJsonDataArray[$res['id']] = $res['name'];
        }
        return $countryJsonDataArray;
    }

    /* @type : text */

    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 sendTxtMsg($paramData = array()) {
        $smsparam = ['template_name' => $paramData['template_name'], 'mobile' => $paramData['mobile'], 'user_name' => $paramData['user_name'], 'otp' => $paramData['otp']];
        //Debug::dump($smsparam); exit;
        $this->sendSMS($smsparam);
    }

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

    /** @Description  : Dashboard Login
     *  @createdDate  : 03-May-2019
     *  */
    /*public function dashboardLoginAction() {
        $sessionUser = new Container('userlogin');
        $user_id = $sessionUser->userData['user_id'];
        if ($user_id != "") {
            $this->redirect()->toRoute('dashboard');
        }
        $errorMsg = "";
        $captchaerror = '';
        $form = new LoginForm();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $form->setData($request->getPost());
            if ($post['g-recaptcha-response'] == '') {
                $captchaerror = 'Please check the captcha';
            }
            //$form->getInputFilter()->get('user_type_id')->setRequired(false);
            if ($form->isValid() && $captchaerror == '') {
                $post['password'] = ($post['password']);
                $post['sms_send_status'] = "false";
                $data = $this->userLogin($post);
                //echo '<pre>';print_r($data);//die();
                if (isset($data['error']) && $data['error']) {
                    $errorMsg = $data['error'];
                } elseif ($data['status'] == 000) {
                    $errorMsg = $data['error'];
                } else {
                    $userTypeArr = $this->config()->getConfig()->loginUserType;
                    $userTypeArr = $userTypeArr->toArray();
                    $user_type_id = $data['data']['user_type_id'];

                    if (!in_array($user_type_id, $userTypeArr)) {
                        $sessionUser = new Container('userlogin');
                        $sessionUser->user_id = $data['data']['user_id'];
                        $sessionUser->user_token = $data['data']['token'];

                        $user_id = $data['data']['user_id'];
                        $url = $this->apiUrl() . "/user/userpersonalinfo?user_id=" . $user_id;
                        $resp = $this->get($url);
                        $response = Json::decode($resp->getBody(), true);
                        $sessionUser->userData = $response['responsedata']['data'];
                        $this->redirect()->toRoute('dashboard');
                    } else {
                        $errorMsg = 'Unauthorized-Access';
                    }
                }
            } else {
                //$msg=$form->getMessages();
                //echo '<pre>';print_r($msg);die();
            }
        }

        $viewModel = new ViewModel([
            'form' => $form,
            'errorMsg' => $errorMsg,
            'error' => $captchaerror,
            'captchaKey' => $this->config()->getConfig()->googleCaptcha->siteKey
        ]);
        //$this->layout()
        $viewModel->setTerminal(true);
        return $viewModel;
    }*/

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

    /** @Description  : Dashboard Login
     *  @createdDate  : 03-May-2019
     *  */
    /*public function supplierAction() {
        $sessionUser = new Container('userlogin');
        $user_id = $sessionUser->userData['user_id'];
        if ($user_id != "") {
            $this->redirect()->toRoute('dashboard');
        }
        $viewModel = new ViewModel();
        $viewModel->setTerminal(true);
        return $viewModel;
    }*/

    public function userToken() {
        $sessionUser = new Container('userlogin');
        $userid = $sessionUser->userData['user_id'];
        $user_token = $sessionUser->user_token;
        $location   =   $sessionUser->login_location;
        if ($user_token != '' && $userid != '') {
            $url = $this->apiUrl() . "/user/logout?user_id=" . $userid . "&token=" . $user_token . "&logout_location=abc";
            //$url = rawurlencode($url);
            $resp = $this->get($url);
            //echo '<pre>';print_r($resp);die();
            $response = Json::decode($resp->getBody(), true);
            return $response;
        }
    }

    public function loginSearchAction() {
        $param = $this->getRequest()->getQuery()->toArray();
        $errorMsg = "";
        $sessionUser = new Container('userlogin');
        $user_id = $sessionUser->user_id;
        if ($user_id != "") {
            return $this->redirect()->toRoute('home');
        }
        $form = new LoginRedirectForm();
        $form->get('link_type')->setValue(isset($param['type']) ? $param['type'] : '');
        $request = $this->getRequest();
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $form->setData($request->getPost());
            if ($form->isValid()) {
                $data1['username'] = ($post['username_redirect']);
                $data1['password'] = ($post['password_redirect']);
                $data1['sms_send_status'] = "true";
                $data = $this->userLogin($data1);
                if (isset($data['error']) && $data['error']) {
                    $errorMsg = $data['error'];
                } elseif ($data['status'] == 000) {
                    $errorMsg = $data['error'];
                } else {
                    $userTypeArr = $this->config()->getConfig()->loginUserType;
                    $userTypeArr = $userTypeArr->toArray();
                    $user_type_id = $data['data']['user_type_id'];
                    if (in_array($user_type_id, $userTypeArr)) {
                        $sessionUser = new Container('confirmuserlogin');
                        $sessionUser->user_id = $data['data']['user_id'];
                        $sessionUser->link_type = $post['link_type'];
                        $user_id = $data['data']['user_id'];
                        $mobile = $data['data']['mobile'];
                        $first_name = $data['data']['first_name'];
                        $sessionUser->user_token = $data['data']['token'];
                        //Send SMS To user
                        $otp = $this->generateOtp();
                        $templateName = 'acc_verify_code';
                        $smsparam = ['template_name' => $templateName, 'mobile' => $mobile, 'user_name' => $first_name, 'otp' => $otp];
                        $this->sendTxtMsg($smsparam);
                        /* End */
                        // Insert OTP in database
                        $otpData = ['UID' => $user_id, 'Verification_code' => $otp];
                        $this->insertOtp($otpData);
                        /// END
                        return $this->redirect()->toRoute('confirmRedirectLoginOtp');
                    } else {
                        $errorMsg = 'Unauthorized-Access';
                    }
                }
            } else {
                $msg = $form->getMessages();
            }
        }
        $viewModel = new ViewModel(['form' => $form, 'errorMsg' => $errorMsg]);
        return $viewModel;
    }

    public function confirmRedirectLoginOtpAction() {
        $errorMsg = "";
        $sessionUserLogin = new Container('confirmuserlogin');
        $user_id = $sessionUserLogin->user_id;
        $link_type = $sessionUserLogin->link_type;
        $token = $sessionUserLogin->user_token;
        $sessionUser = new Container('userlogin');
        $userId = $sessionUser->user_id;
        if ($user_id == "" || $userId != "") {
            return $this->redirect()->toRoute('home');
        }
        $otpform = new ConfirmLoginOtpForm();
        $request = $this->getRequest();
        /////////////////
        if ($request->isPost()) {
            $result = [];
            $otpform->setData($request->getPost());
            $post = $request->getPost()->toArray();
            //echo '<pre>';print_r($post);die();
            if ($otpform->isValid()) {
                $data = [
                    'user_id' => $user_id,
                    'confirm_otp' => $post['confirm_otp']
                ];
                $rep = $this->fetchOtp($data);
                if ($rep['status'] == "success") {
                    unset($sessionUserLogin->user_id);
                    $sessionUser = new Container('userlogin');
                    $sessionUser->user_id = $user_id;
                    $sessionUser->user_token = $token;

                    $url = $this->apiUrl() . "/user/userpersonalinfo?user_id=" . $user_id;
                    $resp = $this->get($url);
                    $response = Json::decode($resp->getBody(), true);
                    $sessionUser->userData = $response['responsedata']['data'];
                    $data = ['id' => $rep['data']['id'], 'UID' => $rep['data']['UID'], 'Verification_code' => $rep['data']['Verification_code'], 'isUsed' => 1];
                    $this->updateOtp($data);
                    if ($link_type == 'my-profile') {
                        return $this->redirect()->toRoute('profile');
                    } else if ($link_type == 'manage-bookings') {
                        return $this->redirect()->toRoute('bookinghistory');
                    }
                } else {
                    $errorMsg = "Please enter the correct OTP";
                }
            } else {
                $msg = $otpform->getMessages();
            }
        }

        $viewModel = new ViewModel(['form' => $otpform, 'errorMsg' => $errorMsg]);
        return $viewModel;
    }
        public function makePaymentAction() {
        $errorMsg = "";
        $captchaerror = '';
        $form = new TicketForm();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $postdata = $request->getPost()->toArray();
            $form->setData($postdata);
            if ($postdata['g-recaptcha-response'] == '') {
                $captchaerror = 'Please check the captcha';
            }
            if ($form->isValid() && $captchaerror == '') {
                 $bookingNo = trim($postdata['booking_no']);
                 $mobileNo = trim($postdata['mobile_no']);
                 $apiParams = ['booking_id' => $bookingNo, 'user_mobile' => $mobileNo];
                 $url = $this->apiUrl() . "/booking/bookingListSearch";
                 $resp = $this->post($url, $apiParams);
                 $bookingList = Json::decode($resp->getBody(), true);
                 

                 $url = $this->apiUrl() . "/booking/getbookingadvanceamtpaid?booking_id=".$bookingNo;
                 $resp2 = $this->get($url);
                 $bookingpaidamount = Json::decode($resp2->getBody(), true);
                 if ($bookingList['responsedata']['status']=='success') {
                    $bookinginfo  = $bookingList['responsedata']['data'];
                    $makePaymentContainer = new Container('make_payment');
                    $makePaymentContainer->booking_detail = $bookinginfo[0];
                    //echo '<pre>';print_r($makePaymentContainer->booking_detail);die();
                    return $this->redirect()->toRoute('checkout');
                } else {
                    $errorMsg = "Invalid Booking no. or Mobile no.";
                }
            } else {
                $msg = $form->getMessages();
            }
        }
        $viewModel = new ViewModel(['form' => $form,
            'error' => $captchaerror,
            'captchaKey' => $this->config()->getConfig()->googleCaptcha->siteKey,
            'errorMsg' => $errorMsg
        ]);
        return $viewModel;
    }

    public function checkoutAction() {
        $sessionUser = new Container('userlogin');
        $user_id = $sessionUser->user_id;
        $makePaymentContainer = new Container('make_payment');
        $bookingInfo = $makePaymentContainer->booking_detail;
        if($user_id!=""){
        $walletData = $this->getWalletAmt($user_id);
        $bookingInfo['user_id']=$user_id;
        }else{
        $walletData = "";
        $bookingInfo['user_id']=$bookingInfo['client_id'];
        }
        //echo '<pre>';print_r($bookingInfo);die();
        $twentyFivePercent = ($bookingInfo['estimated_final_price'] * 25 / 100);
        $fiftyPercent = ($bookingInfo['estimated_final_price'] * 50 / 100);
        $bookingInfo['twenty_five_percent'] = round($twentyFivePercent);
        $bookingInfo['fifty_percent'] = round($fiftyPercent);

        $request = $this->getRequest();
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            //echo '<pre>';print_r($post);//die();
            if ($post['booking_amt_percentage'] == '25') {
                $post['booking_amt_paid'] = round($twentyFivePercent);
                $post['booking_amt_balance'] = $bookingInfo['estimated_final_price'] - round($twentyFivePercent);
            } else if ($post['booking_amt_percentage'] == '50') {
                $post['booking_amt_paid'] = round($fiftyPercent);
                $post['booking_amt_balance'] = $bookingInfo['estimated_final_price'] - round($fiftyPercent);
            } else {
                $post['booking_amt_paid'] = $bookingInfo['booking_amt_balance'];
                $post['booking_amt_balance'] = 0;
            }
            //echo $post['wallet_amount'];
            //echo $post['booking_amt_paid'];
            if (!empty($post['wallet_amount'])) {
                //echo "Mohit";
                $walletStatus = 1;
                if ($walletData < $post['booking_amt_paid']) {
                    $walletAmt = 0;
                    $post['booking_amt_paid'] = $post['booking_amt_paid'] - $walletData;
                    $paymentData['wallet_data'] = $walletData;
                    $paymentStatus = 1;
                } else {
                    $walletAmt = $walletData - $post['booking_amt_paid'];
                    $paymentData['wallet_data'] = 0;
                    if ($walletAmt < 0) {
                        $paymentStatus = 1;
                    } else {
                        $paymentStatus = 0;
                    }
                }
            } else {
                //echo "Jain";
                $walletStatus = 0;
                $walletAmt = $walletData;
                $bookingInfo['wallet_data'] = 0;
                /* if ($walletAmt > $post['booking_amt_paid']) {
                  $paymentStatus = 1;
                  } else {
                  $paymentStatus = 0;
                  } */
                $paymentStatus = 1;
            }

            $bookingInfo['wallet_updated_amount'] = $walletAmt;
            //echo $walletAmt.'<br/>';
            //echo $paymentStatus.'<br/>';
            //echo $walletStatus.'<br/>';
            //echo $post['booking_amt_paid'];
            //Debug::dump($post);
            $finalData = [];
            $finalData = array_merge($bookingInfo, $post);
            //Debug::dump($finalData);
            //exit;

            //$finalBooking = $this->finalBookingSubmission($finalData);
            //$lastInsertId = $finalBooking['data']['response']['insertId'];
            $companyInitial = $this->config()->getConfig()->company->companyInitial;
            //$finalData['booking_id'] = $lastInsertId;
            //Debug::dump($finalData);
            //exit;

            unset($makePaymentContainer->booking_detail);
            $makePaymentContainer->booking_detail = $finalData;
            //echo '<pre>';print_r($finalData);//die();
            //echo $walletStatus.'<br>';
            //echo $finalData['ref'].'<br>';
            //echo $paymentStatus;
            //die;

            $this->checkPayment($walletStatus, $paymentStatus, $finalData, $finalData['ref'],$finalData['id']);
        }



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

    }

    public function getWalletAmt($user_id) {
        $url = $this->apiUrl() . "/user/walletamount?user_id=" . $user_id;
        $resp = $this->get($url);
        $response = Json::decode($resp->getBody(), true);
        $walletAmt = $response['responsedata']['data']['wallet_amount'];
        if ($walletAmt != "") {
            $data = $response['responsedata']['data']['wallet_amount'];
        } else {
            $data = 0;
        }
        return $data;
    }

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

    public function getBookingTransNo($val, $initial) {
        $dateYear = date('y');
        $dateMonth = date('m');
        $trans_no = $initial . '' . $dateYear . '' . $dateMonth . '' . $val;
        return $trans_no;
    }

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

   /* @commentby  - Mohit verma
    * @description - booking paid amount not use in booking estimation table.
    *
    *  public function userBookingUpdate($data) {
        $url = $this->apiUrl() . "/booking/getBookingAmtBalance?booking_id=".$data['booking_id'];
        $resp = $this->get($url);
        $response = Json::decode($resp->getBody(), true);
        if($response['responsedata']['status']=="success"){
           if($data['booking_amt_percentage']!='100'){
           $booking_amt_percentage=$response['responsedata']['data']['booking_amt_percentage']+$data['booking_amt_percentage'];
           $booking_amt_paid=$response['responsedata']['data']['booking_amt_paid']+$data['booking_amt_paid'];
           $booking_amt_balance=$response['responsedata']['data']['booking_amt_balance']-$data['booking_amt_paid'];
           }else{
           $booking_amt_percentage=$data['booking_amt_percentage'];
           $booking_amt_paid=$data['estimated_final_price'];
           $booking_amt_balance=0;
           }
        $data1=[
            'booking_id'=>$data['booking_id'],
            'booking_amt_percentage'=>$booking_amt_percentage,
            'booking_amt_paid'=>$booking_amt_paid,
            'booking_amt_balance'=>$booking_amt_balance
        ];

        $url1 = $this->apiUrl() . "/booking/updatebookingAmtBalance";
        $resp1 = $this->post($url1, $data1);
        $response1 = Json::decode($resp1->getBody(), true);
        }
        return $response1;
    }*/



    public function checkPayment($walletStatus, $paymentStatus, $paymentData, $bookingRefNo, $bookingId) {
        //Debug::dump($paymentData);
        //echo $paymentStatus;
        //echo $walletStatus;
        //exit;
        if ($paymentStatus == 1) {
            //echo "Go on Payment Gateway";
            $atomPayment = $this->atomPaymentGateway($paymentData, $bookingRefNo, $walletStatus);
        } else {
            //echo "No Payment Gateway";
            if ($walletStatus == 1) {
                $data['user_id'] = $paymentData['user_id'];
                $data['wallet_amount'] = $paymentData['wallet_updated_amount'];
                $resp = $this->getWalletAmtUpdate($data);
                //print_r($resp);
                if ($resp['response']['changedRows'] == 1) {
                    $data['user_id'] = $paymentData['user_id'];
                    $data['booking_id'] = $bookingId;
                    $data['booking_transaction_no'] = $this->getBookingTransNo($bookingId, $this->config()->getConfig()->company->companyInitial);
                    $data['amount'] = $paymentData['booking_amt_paid'];
                    $data['current_balance'] = $paymentData['wallet_updated_amount'];
                    $data['payment_type_id'] = 3;
                    $data['payment_status'] = 1;
                    $data['created_date'] = date('Y-m-d');
                    $data['created_by'] = $paymentData['user_id'];
                    $this->userTransactionUpdate($data);
                    //$this->userBookingUpdate($paymentData);
                }
            }
            $this->redirect()->toRoute('user', ['action' => 'success', 'param' => $bookingRefNo]);
        }
        //exit;
    }


        public function atomPaymentGateway($paymentData, $bookingRefNo, $walletStatus) {
        $data = [];
        //echo $walletStatus;
        //Debug::dump($paymentData);
        //exit;
        $url = $this->apiUrl() . "/payment/Atom";
        $data['login'] = $this->config()->getConfig()->atom_payment->login;
        $data['pass'] = $this->config()->getConfig()->atom_payment->pass;
        $data['ttype'] = $this->config()->getConfig()->atom_payment->ttype;
        $data['prodid'] = $this->config()->getConfig()->atom_payment->prodid;
        $data['amt'] = $paymentData['booking_amt_paid'];
        $data['txncur'] = $this->config()->getConfig()->atom_payment->txncur;
        $data['txnamt'] = $paymentData['booking_amt_paid'];
        $data['clientcode'] = $paymentData['client_id'];
        $data['transid'] = $bookingRefNo;
        $data['datepick'] = date('d/m/Y');
        $data['custacc'] = $this->config()->getConfig()->atom_payment->custacc;
        $data['udf1'] = $paymentData['first_name'];
        $data['udf2'] = $paymentData['email'];
        $data['udf3'] = $paymentData['mobile'];
        $data['udf4'] = 'karol bagh';

        $data['ru'] = $this->config()->getConfig()->base_url->url . "payment-response/" . $walletStatus;
        //Debug::dump(json_encode($data));
        $resp = $this->post($url, $data);
        $response = Json::decode($resp->getBody(), true);

        //Debug::dump($response);
        //exit;
        if ($response['response']['status'] == true) {
            $this->redirect()->toUrl($response['response']['url']);
        }
    }


        public function paymentResponseAction() {
        $makePaymentContainer = new Container('make_payment');
        $paymentData = $makePaymentContainer->booking_detail;
        //echo '<pre>';print_r($paymentData);die();
        $postData = $this->getRequest()->getPost()->toArray();
        $walletStatus = $this->params()->fromRoute('param');
        $url = $this->apiUrl() . "/payment/Atomresponse";
        $resp = $this->post($url, $postData);
        $response = Json::decode($resp->getBody(), true);
        //Debug::dump($response);
        //exit;
        $response['response']['data']['date'] = date('Y-m-d H:i:s', strtotime($response['response']['data']['date']));
        $url1 = $this->apiUrl() . "/payment/Transactionresp";
        $resp1 = $this->post($url1, $response['response']['data']);
        $response1 = Json::decode($resp1->getBody(), true);

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

        if ($walletStatus == 1) {
            $data['user_id'] = $paymentData['user_id'];
            $data['wallet_amount'] = $paymentData['wallet_updated_amount'];
            $resp = $this->getWalletAmtUpdate($data);
        }
        if ($paymentData['wallet_data'] != 0) {
            $data['user_id'] = $paymentData['user_id'];
            $data['booking_id'] = $paymentData['booking_id'];
            $data['booking_transaction_no'] = $this->getBookingTransNo($paymentData['booking_id'], $this->config()->getConfig()->company->companyInitial);
            $data['amount'] = $paymentData['wallet_data'];
            $data['current_balance'] = $paymentData['wallet_updated_amount'];
            $data['payment_type_id'] = 3;
            $data['payment_status'] = 1;
            $data['created_date'] = date('Y-m-d');
            $data['created_by'] = $paymentData['user_id'];
            $this->userTransactionUpdate($data);
            //$this->userBookingUpdate($paymentData);
        }

        $data['user_id'] = $paymentData['user_id'];
        $data['booking_id'] = $paymentData['booking_id'];
        $data['booking_transaction_no'] = $this->getBookingTransNo($paymentData['booking_id'], $this->config()->getConfig()->company->companyInitial);
        $data['amount'] = $paymentData['booking_amt_paid'];
        $data['current_balance'] = $paymentData['wallet_updated_amount'];
        $data['payment_response_id'] = $response1['response']['insertId'];
        $data['payment_type_id'] = 4;
        $data['payment_status'] = 1;
        $data['created_date'] = date('Y-m-d');
        $data['created_by'] = $paymentData['user_id'];
        $this->userTransactionUpdate($data);
        //$this->userBookingUpdate($paymentData);
        if ($response['response']['data']['f_code'] == 'Ok') {
            $this->redirect()->toRoute('user', ['action' => 'success', 'param' => $response['response']['data']['mer_txn']]);
        } else {
            $this->redirect()->toRoute('user', ['action' => 'fail', 'param' => $response['response']['data']['mer_txn']]);
        }
    }

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

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

    public function fetchGoogleApiData($lat,$long) {
        $url = $this->config()->getConfig()->google_map->apiData . '?latlng='.$lat.','.$long.'&key=' . $this->config()->getConfig()->google_map->key;
        //https://maps.googleapis.com/maps/api/geocode/json?latlng=28.653158399999995,77.18912&key=AIzaSyBiFNtCEUrKPHbCUOdqVKMCsq9-uPB5sc4
        $curl_handle = curl_init();
        curl_setopt($curl_handle, CURLOPT_URL, $url);
        curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT, 10);
        curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl_handle);
        $result = curl_exec($curl_handle);
        if ($result === FALSE) {
            die('Curl failed: ' . curl_error($curl_handle));
        }
        curl_close($curl_handle);
        return $result;
    }


}
