<?php

namespace User\Controller;

use Application\Controller\RestAPIClientController;
use User\Form\{
    RegistrationForm,
    PersonalRegistrationForm,
    DutyRegistrationForm,
    CompanyRegistrationForm,
    VehicleRegistrationForm,
    ConfirmOtpForm,
    PopupRegistrationForm
};
use Zend\Validator\File\Size;
use Zend\View\Model\{
    ViewModel,
    JsonModel
};
use Zend\Session\Container;
use Zend\Debug\Debug;
use Zend\Json\Json;
use \Zend\Validator\StringLength;
use User\Model\Registration;
use Dashboard\Model\User;

class RegistrationController extends RestAPIClientController {

    public function __construct() {
        $this->registrationModel = new Registration();
        $this->userModel = new User();
    }

    /**
     * Index...
     * @return ViewModel
     */

    /** @Created_date: 15-OCT-2019
     *  @Created_By : Mohit Verma
     *  @Description : New Signup process
     */
    public function indexAction() {
        $sessionUser = new Container('userlogin');
        $user_id = $sessionUser->userData['user_id'];
        if ($user_id != "") {
            $this->redirect()->toRoute('home');
        }
        $msg = "";
        $valide_mobile = '';
        $request = $this->getRequest();
        $uristring = $request->getUriString();
        $link_array = explode('/', $uristring);
        $usertype = end($link_array);
        //echo $usertype; die;

        $userTypeArr = $this->config()->getConfig()->userTypeId;
        $userTypeArr = $userTypeArr->toArray();
        $userTypeId = $userTypeArr[$usertype];

        RegistrationForm::$countryprefix = $this->userModel->getCountryCodePrefix();

        $loginDetailForm = new RegistrationForm();
        $loginDetailForm->get('registration_type')->setValue($userTypeId);

        if ($request->isPost()) {
            $loginDetailForm->setData($request->getPost());

            $loginformData = $this->getRequest()->getPost();
            $loginformData = $loginformData->toArray();

            if ($loginDetailForm->isValid()) {

                $first_name = (trim($loginformData['first_name']));
                $last_name = (trim($loginformData['last_name']));
                //$username = strtolower(trim($loginformData['username']));
                $email = trim($loginformData['email']);
                $contact_no = trim($loginformData['contact_no']);
                $refer_by = trim($loginformData['reference_name']);
                $password = trim($loginformData['password']);
                $registrationType = $loginformData['registration_type'];
                $confirmPassword = trim($loginformData['confirm_password']);
                $nationality = trim($loginformData['nationality_value']);
                $mobile_prefix = $loginformData['prefix_contact_no'];

                //$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) {

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

                if ($valid) {

                    if ($confirmPassword == $password) {
                        /* Create Session For Get Data on next page */
                        $sessionContainer = new Container('userlogin');
                        $sessionContainer->first_name = $first_name;
                        $sessionContainer->last_name = $last_name;
                        //$sessionContainer->username = $username;
                        $sessionContainer->email = $email;
                        $sessionContainer->mobile = $contact_no;
                        $sessionContainer->password = $password;
                        $sessionContainer->usertype = $usertype;
                        $sessionContainer->userTypeId = $registrationType;
                        $sessionContainer->mobile_prefix = $mobile_prefix;

                        /* End */

                        $finalData = [];
                        $finalData = [
                            'username' => $email,
                            'user_type_id' => $registrationType
                        ];

                        $JsonData = $this->registrationModel->verifyUser($email, $contact_no, $registrationType);
                        //echo '<pre>';print_r($JsonData);die();
                        if ((!empty($JsonData)) && ($JsonData['responsedata']['status']) == 'success') {

                            $responseData = $JsonData['responsedata']['data'];
                            $user_id = $responseData["user_id"];
                            $userTypeId = $responseData["user_type_id"];
                            $is_active = $responseData["is_active"];

                            if (isset($user_id) && $user_id > 0) {
                                $userData = $this->registrationModel->getUserPersonalInfo($user_id);
                                //echo '<pre>';print_r($userData['responsedata']['data']);die();
                                $userData = $userData['responsedata']['data'];
                                //$sessionContainer = new Container('userdata');
                                $sessionContainer = new Container('userlogin');
                                $sessionContainer->mobile_no = $userData['mobile'];
                                $sessionContainer->first_name = $userData['first_name'];
                                $sessionContainer->last_name = $userData['last_name'];
                                $sessionContainer->email = $userData['email'];
                                $sessionContainer->referralBy = $userData['refer_by'];
                                $sessionContainer->referral_code = $userData['referral_key'];
                                $sessionContainer->username = $userData['username'];
                                $sessionContainer->password = $password;
                                $sessionContainer->user_id = $user_id;
                                $sessionContainer->signup_status = $userData['signup_status'];
                                $sessionContainer->mobile_prefix = $mobile_prefix;
                            }

                            $signup_status = $responseData['signup_status'];
                            if ($signup_status == 1) {
                                $this->redirect()->toRoute($usertype, ['action' => 'confirmotp']);
                            } else if ($signup_status == 2) {
                                $this->redirect()->toRoute($usertype, ['action' => 'personal-info']);
                            } else if ($signup_status == 3) {
                                $this->redirect()->toRoute($usertype, ['action' => 'company-info']);
                            } else if ($signup_status == 4) {
                                $this->redirect()->toRoute($usertype, ['action' => 'vehicle-info']);
                            } else if ($signup_status == 5) {
                                $this->redirect()->toRoute($usertype, ['action' => 'duty-info']);
                            } else if ($signup_status == 6) {
                                $this->redirect()->toRoute($usertype, ['action' => 'duty-info']);
                            } else if ($signup_status > 0 && $signup_status == 10 && $is_active == 0) {
                                $msg = 'Account is not active,Contact with admin';
                            } else if ($signup_status > 0 && $signup_status == 10 && $is_active == 1) {
                                $msg = 'Account Already Created';
                            }
                        } else {

                            $roleTypeArr = $this->config()->getConfig()->role_id->toArray();
                            if (!empty($roleTypeArr)) {
                                $role_id = $roleTypeArr[$registrationType];
                            }
                            $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' => $userTypeId,
                                'password' => $password,
                                'refer_by' => $refer_by,
                                'nationality' => $nationality,
                                'user_grade' => $this->config()->getConfig()->userGrade->defaultGrade,
                            ];
                            $finalData = array_filter($finalData);
                            $finalData['parent_id'] = 0;
                            //echo '<pre>';print_r($finalData);die();
                            $JsonData = $this->registrationModel->userNewSignup($finalData);
                            //echo '<pre>';print_r($JsonData);die();
                            if (!empty($JsonData)) {
                                if ($JsonData['responsedata']['status'] == 'failed') {
                                    $msg = $JsonData['responsedata']['message'];
                                } else {
                                    $user_id = $JsonData['responsedata']['user_id'];
                                    $sessionContainer = new Container('userlogin');
                                    $sessionContainer->user_id = $user_id;
                                    $this->redirect()->toRoute($usertype, ['action' => 'confirmotp']);
                                }
                            } else {
                                $msg = "Registration not done";
                            }
                        }
                    } else {
                        $msg = "password and confirm password did't match";
                    }
                } else {
                    $msg = "password should be greater than 6 and smaller than 20";
                }
//                } else {
//                    $msg = "Username should be valid Mobile no. or valid emailid";
//                }
            } else {
                //$msg = "All fields are mandatory";
            }
        }
        //echo $msg; die;
        $viewModel = new ViewModel(
                [
            'form' => $loginDetailForm,
            'error_msg' => $msg
        ]);
        //Debug::dump($viewModel); exit;
        return $viewModel;
    }

    /**
     * @CreatedDate : 12-Oct-2018
     * @createdBy   : Mohit Verma
     * @description : Insert User Personal Information
     * @
     */
    public function personalInfoAction() {
        $guide_certificate = '';
        $error = '';
        $sessionuserData = new Container('userlogin');
        //$loginData = $sessionContainer->loginData;
        $first_name = $sessionuserData->first_name;
        $last_name = $sessionuserData->last_name;
        //$username = $sessionuserData->username;
        $email = $sessionuserData->email;
        $mobile = $sessionuserData->mobile;
        // $password = $sessionuserData->password;
        $userTypeId = $sessionuserData->userTypeId;
        $usertype = $sessionuserData->usertype;
        $user_id = $sessionuserData->user_id;
        $mobile_prefix = $sessionuserData->mobile_prefix;

        $companyId = $this->config()->getConfig()->company->companyId;
        $docTypeNameObj = $this->config()->getConfig()->document_file_upload_name;
        $docTypeNameArr = $docTypeNameObj->toArray();

        /* $roleTypeArr = $this->config()->getConfig()->role_id->toArray();
          if (!empty($roleTypeArr) && $userTypeId != '') {
          $role_id = $roleTypeArr[$userTypeId];
          } */

        $request = $this->getRequest();
        PersonalRegistrationForm::$countryprefix = $this->userModel->getCountryCodePrefix();
        $personalInfoForm = new PersonalRegistrationForm();
        $loginDetailForm = new RegistrationForm();

        $personalInfoForm->get('first_name')->setValue($first_name);
        $personalInfoForm->get('last_name')->setValue($last_name);
        $personalInfoForm->get('email')->setValue($email);
        $personalInfoForm->get('contact_no')->setValue($mobile);
        $personalInfoForm->get('prefix_contact_no')->setValue($mobile_prefix);
        $personalInfoForm->get('prefix_alt_contact_no')->setValue($mobile_prefix);

        $personalInfoForm->get('email')->setAttribute('disabled', 'true');
        $personalInfoForm->getInputFilter()->get('email')->setRequired(false);
        $personalInfoForm->get('contact_no')->setAttribute('disabled', 'true');
        $personalInfoForm->getInputFilter()->get('contact_no')->setRequired(false);
        $personalInfoForm->get('registration_type')->setValue($userTypeId);
        /* if (ctype_digit($username)) {
          $personalInfoForm->get('contact_no')->setValue($username);
          $personalInfoForm->get('contact_no')->setAttribute('disabled', 'true');
          $personalInfoForm->getInputFilter()->get('contact_no')->setRequired(false);
          $email = "";
          $contact_no=$username;
          } else {
          $personalInfoForm->get('email')->setValue($username);
          $personalInfoForm->get('email')->setAttribute('disabled', 'true');
          $personalInfoForm->getInputFilter()->get('email')->setRequired(false);
          $email = $username;
          $contact_no="";
          } */

        if ($request->isPost()) {
            $postData = $this->getRequest()->getPost()->toArray();
            $error = '';
            if ($postData['g-recaptcha-response'] == '') {
                $error = 'Please check the captcha';
            }
            $postData = array_filter($postData);
            //echo '<pre>';print_r($postData);die();
            $personalInfoForm->setData($postData);

            if ($personalInfoForm->isValid() && $error == '') {
                /* $fileNameRpProof = $postData['residential_proof']['name'];
                  $fileTmpNameRpProof = $postData['residential_proof']['tmp_name'];
                  $rpProofImageName = date("d-m-Y") . "-" . time() . $fileNameRpProof;
                  $targetPath = "public/upload/commonuser/rcproof/" . $rpProofImageName;
                  move_uploaded_file($fileTmpNameRpProof, $targetPath);

                  $fileNameLicenseProof = $postData['license_proof']['name'];
                  $fileTmpNameLicenseProof = $postData['license_proof']['tmp_name'];
                  $licenseProofImageName = date("d-m-Y") . "-" . time() . $fileNameLicenseProof;
                  $targetPath = "public/upload/commonuser/licenseproof/" . $icenseProofImageName;
                  move_uploaded_file($fileTmpNameLicenseProof, $targetPath); */
                //file end

                $guide_certificate = (isset($_FILES['guide_certificate']['name']) != '') ? 'guide_certificate' : '';
                $license_proof = (isset($_FILES['license_proof']['name']) != '') ? 'license_proof' : '';
                $police_proof = (isset($_FILES['police_proof']['name']) != '') ? 'police_proof' : '';



                /** GET State id AND country id from city id */
                if (isset($postData['city_value']) && $postData['city_value'] != '') {
                    $city_id = $postData['city_value'];
                    $url = $this->apiUrl() . "/city/stateCountry?city_id=" . $city_id;
                    $val = $this->get($url);
                    $JsonData = $val->getBody();
                    $JsonData = Json::decode($JsonData, true);
                    if (!empty($JsonData['response'])) {
                        $statecountryData = $JsonData['response'][0];
                        $stateId = $statecountryData['state_id'];
                        $countryId = $statecountryData['country_id'];
                    }
                }
                /* END */
                $referralBy = isset($postData['referral_by']) ? $postData['referral_by'] : '';

                $finalData = [];
                $finalData = [
                    //'parent_id' => '0',
                    //'company_id' => $companyId,
                    //'role_id' => $role_id,
                    //'department_id' => 1,
                    'first_name' => $postData['first_name'],
                    'last_name' => $postData['last_name'],
                    'email' => isset($postData['email']) ? $postData['email'] : '',
                    'mobile' => isset($postData['contact_no']) ? $postData['contact_no'] : '',
                    //'father_name' => $postData['father_name'],
                    //'user_type_id' => $userTypeId,
                    //'password' => md5($password),
                    'alternate_mobile' => isset($postData['alt_contact_no']) ? $postData['alt_contact_no'] : '',
                    //'reference_name' => isset($postData['reference_name']) ? $postData['reference_name'] : '',
                    'dob' => date('Y-m-d', strtotime($postData['dob'])),
                    'gender' => $postData['gender'],
                    'address' => $postData['residential_address'],
                    'city' => $postData['city_value'],
                    'state' => $stateId,
                    'country_id' => $countryId,
                    'pincode' => $postData['pincode'],
                    'vehicle_code' => isset($postData['vehicle_code']) ? $postData['vehicle_code'] : '',
                    'vehicle_number' => isset($postData['vehicle_number']) ? $postData['vehicle_number'] : '',
                    'license_no' => isset($postData['license_no']) ? $postData['license_no'] : '',
                    //'agreeterms' => $postData['agreeterms'],
                    //'created_date' => date('Y-m-d h:i:s'),
                    'user_id' => $user_id,
                    'signup_status' => 2
                ];
                /* Add registration user */

                $finalData = array_filter($finalData);
                //$finalData['parent_id']=0;
                //echo '<pre>';print_r($finalData);die();
                $JsonData = $this->registrationModel->updatePersonalInfo($finalData);
                //echo '<pre>';print_r($JsonData);die();
                /* END */

                if (!empty($JsonData) && ($JsonData['response']['status']) == 'success') {

                    $data = $JsonData['response']['status'];
                    //$user_id = $JsonData['responsedata']['user_id'];
                    $sessionuserData->user_id = $user_id;

                    /* Update Referral Key
                      $referralParams = array('user_id' => $user_id, 'first_name' => $postData['first_name']);
                      $referralCode = $this->generateReferralCode($referralParams);
                      $update_referal_key = $this->apiUrl() . "/user/updateReferralCode";
                      $referral_key_param = ['id' => $user_id, 'referral_code' => $referralCode];
                      $this->put($update_referal_key, $referral_key_param);

                      //$finalData2 = ['user_id' => $user_id, 'signup_status' => 3];
                      //$this->registrationModel->updateSignupStatus($finalData2);
                      /* END */

                    /* User registration data */
                    $loginuserData = new Container('userdata');
                    $loginuserData->user_id = $user_id;
                    $loginuserData->mobile_no = $postData['contact_no'];
                    $loginuserData->first_name = $contact_no;
                    $loginuserData->userTypeId = $userTypeId;
                    //$loginuserData->email = $postData['email'];
                    $loginuserData->email = $email;
                    $loginuserData->referralBy = $referralBy;
                    $loginuserData->referral_code = $referralCode;
                    //$loginuserData->username = $username;
                    //$loginuserData->password = $password;

                    /* END */

                    /* Upload Guide Certificate */
                    if ($guide_certificate != '') {
                        $arrData = array('file_name' => $guide_certificate, 'user_id' => $user_id);
                        $uploadDataArr = $this->uploadFile($arrData);
                    }
                    /* END - Upload guide */



                    /* Upload license proff */
                    if (isset($police_proof) && $police_proof != '') {
                        $arrData = array('file_name' => $police_proof, 'user_id' => $user_id);
                        $uploadDataArr = $this->uploadFile($arrData);
                    }
                    /* END- License Proof */

                    $refparam = ['user_type_id' => $userTypeId];
                    $referral_amount = $this->getReferralAmount($refparam);

                    /* Send Welcome Mail Starts Here */

                    $sendMailParam = [
                        'user_id' => $user_id,
                        //'user_name' => $postData['first_name'],
                        'user_name' => $email,
                        //'user_email' => $postData['email'],
                        'user_email' => $email,
                        'username' => $username,
                        'user_password' => $password,
                        'referral_code' => $referralCode,
                        'user_type_id' => $userTypeId,
                        'template_name' => 'welcome',
                        'refer_amount' => $referral_amount[0]['installation_amount_user'],
                        'subject' => 'Welcome to hello42cab'
                    ];

                    //$this->sendMail($sendMailParam);

                    /* END Mail */
                    if ($data == 'success') {
                        switch ($usertype) {
                            case "driver":
                                $this->redirect()->toRoute($usertype, ['action' => 'company-info']);
                                break;
                            case "vendor":
                                $this->redirect()->toRoute($usertype, ['action' => 'company-info']);
                                break;
                            case "corporate-user":
                                $this->redirect()->toRoute($usertype, ['action' => 'company-info']);
                                break;
                            case "travel-agent":
                                $this->redirect()->toRoute($usertype, ['action' => 'company-info']);
                                break;
                            case "hotel":
                                $this->redirect()->toRoute($usertype, ['action' => 'company-info']);
                                break;
                            case "guide":
                                $this->redirect()->toRoute($usertype, ['action' => 'duty-info']);
                                break;
                            case "normal-user":
                                /* Update Signup Status */
                                $finalData2 = ['user_id' => $user_id, 'signup_status' => 10];
                                $this->registrationModel->updateSignupStatus($finalData2);
                                /* End */

                                $commondata = ['user_id' => $user_id,
                                    'user_type_id' => $userTypeId,
                                    'mobile' => $postData['contact_no'],
                                    'email' => $email,
                                    'user_name' => $postData['first_name'],
                                    'referralBy' => $referralBy,
                                    'template_name' => 'acc_verify_code',
                                    'username' => $username,
                                    'password' => $password,
                                    'referral_code' => $referralCode
                                ];
                                $this->commonRedirect($commondata);



                                $this->redirect()->toRoute($usertype, ['action' => 'thanks']);
                                //$this->redirect()->toRoute($usertype, ['action' => 'confirmotp']);

                                break;
                        }
                    }
                } else {

                    $this->redirect()->toRoute($usertype, ['action' => 'thanks']);
                    return new ViewModel(['form' => $personalInfoForm, 'error' => $JsonData['response']['message'], 'usertype' => $usertype, 'captchaKey' => $this->config()->getConfig()->googleCaptcha->siteKey]);
                }
            }
//            else {
//
//
//                $msg = $personalInfoForm->getMessages();
//                \Zend\Debug\Debug::dump($msg);die;
//            }
        }
        $viewModel = new ViewModel([
            'form' => $personalInfoForm,
            'usertype' => $usertype,
            'loginForm' => $loginDetailForm,
            'error' => $error,
            'captchaKey' => $this->config()->getConfig()->googleCaptcha->siteKey
        ]);
        return $viewModel;
    }

    function commonRedirect($arrval = array()) {
        $user_id = $arrval['user_id'];
        $user_type_id = $arrval['user_type_id'];
        $first_name = $arrval['user_name'];
        $email = $arrval['email'];
        $mobile = $arrval['mobile'];
        $username = $arrval['username'];
        $password = $arrval['password'];
        $templateName = $arrval['template_name'];
        $referralBy = $arrval['referralBy'];
        $referralCode = $arrval['referral_code'];


        /* Send SMS To user */
        //$otp = $this->generateOtp();
        //$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 */

        /* Insert Referral Amount In user account */
        $refparam = ['user_type_id' => $user_type_id];
        $referral_amount = $this->getReferralAmount($refparam);
        if ($referralBy != '') {
            if (!empty($referral_amount)) {
                $signup_user_amount = $referral_amount[0]['installation_amount_user'];
                $referral_user_amount = $referral_amount[0]['installation_amount_referer'];
                $created_date = date('Y-m-d H:i:s');

                $addRefParam = ['user_id' => $user_id, 'referer_id' => $referralBy, 'user_amount' => $signup_user_amount, 'referer_amount' => $referral_user_amount, 'created' => $created_date];
                $this->addReferralAmount($addRefParam);
            }

            /* Add user wallet transaction */
            $exipry_date = date('Y-m-d', strtotime('+1 month'));
            $adduserwallet = ['user_id' => $user_id, 'amount' => $signup_user_amount, 'expiry_date' => $exipry_date];
            $this->addUserWalletTransaction($adduserwallet);

            $add_refferal_user = ['user_id' => $referralBy, 'amount' => $referral_user_amount, 'expiry_date' => $exipry_date];
            $this->addUserWalletTransaction($add_refferal_user);
            /* End */


            /* Update  wallet transaction amount */
            $apiUrl = $this->apiUrl() . "/user/walletamount?user_id=" . $user_id;
            $val = $this->get($apiUrl);
            $JsonData = $val->getBody();
            $userwallectdata = Json::decode($JsonData, true);
            if (!empty($userwallectdata)) {
                $wallet_amount = $userwallectdata['responsedata']['wallet_amount'];
                $wallet_amount = $wallet_amount + $signup_user_amount;
                $updateUserwallectamt = ['user_id' => $user_id, 'wallet_amount' => $wallet_amount];
                $this->updateWallactAmount($updateUserwallectamt);
            }

            //Reffral user amount update //
            $apiUrl2 = $this->apiUrl() . "/user/walletamount?user_id=" . $referralBy;
            $val = $this->get($apiUrl2);
            $JsonData = $val->getBody();
            $refferaluserwallectdata = Json::decode($JsonData, true);
            if (!empty($refferaluserwallectdata)) {
                $referral_wallet_amount = $refferaluserwallectdata['responsedata']['wallet_amount'];
                $referral_wallet_amount = $referral_wallet_amount + $referral_user_amount;
                $updateUserwallectamt = ['user_id' => $user_id, 'wallet_amount' => $referral_wallet_amount];
                $this->updateWallactAmount($updateUserwallectamt);
            }
            // End //

            /* END */
        }
        /* END */

        /* Send Registration Mail */
        $verifyLinkParam = ['username' => $username, 'user_type_id' => $user_type_id, 'user_id' => $user_id];
        $emailVerifyLink = $this->verifyLink($verifyLinkParam);

        $sendMailParam = [
            'user_id' => $user_id,
            'user_name' => $first_name,
            'user_email' => $email,
            'user_type_id' => $user_type_id,
            'template_name' => 'registration',
            'subject' => 'Registration',
            'email_verify_link' => $emailVerifyLink,
            'referralCode' => $referralCode,
            'refer_amount' => $referral_amount[0]['installation_amount_user'],
            'username' => $username,
            'password' => $password
        ];

        //$this->sendMail($sendMailParam);
        /* END Mail */

        return true;
    }

    /** @CreatedDate : 24-Oct-2018
     * @CreatedBy : Mohit Verma
     * @Descritpion  : Vendor insert company information */
    public function companyInfoAction() {
        $sessionUser = new Container('userlogin');
        $user_id = $sessionUser->userData['user_id'];
        if ($user_id != "") {
            //$this->redirect()->toRoute('home');
        }
        $msg = "";
        $sessionContainer = new Container('userlogin');
        $usertype = $sessionContainer->usertype;
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        if ($user_id == '') {
            //$this->redirect()->toRoute('home');
        }
        $request = $this->getRequest();
        $companyInfoForm = new CompanyRegistrationForm();
//        $sessionContainer = new Container('registration_state');
//        $user_id = $sessionContainer->user_id;

        if ($request->isPost()) {

            $postData = $this->getRequest()->getPost()->toArray();
            //echo '<pre>';print_r($postData);die();
            $companyInfoForm->setData($postData);

            /* if ($_FILES['office_proof']['name'] != '') {
              $arrData = array('file_name' => 'office_proof', 'user_id' => $user_id);
              $this->uploadFile($arrData);
              } */



            /** GET State id AND country id from city id */
            if (isset($postData['city_value']) && $postData['city_value'] != '') {
                $city_id = $postData['city_value'];
                $url = $this->apiUrl() . "/city/stateCountry?city_id=" . $city_id;
                $val = $this->get($url);
                $JsonData = $val->getBody();
                $JsonData = Json::decode($JsonData, true);
                if (!empty($JsonData['response'])) {
                    $statecountryData = $JsonData['response'][0];
                    $stateId = $statecountryData['state_id'];
                    $countryId = $statecountryData['country_id'];
                }
            }
            /* END */

            if ($companyInfoForm->isValid()) {

                //file start

                /* $fileNameGstProof = $postData['gst_proof']['name'];
                  $fileTmpNameGstProof = $postData['gst_proof']['tmp_name'];
                  $gstProofImageName = date("d-m-Y") . "-" . time() . $fileNameGstProof;
                  $targetPath = "public/upload/commonuser/gstproof/" . $gstProofImageName;
                  move_uploaded_file($fileTmpNameGstProof, $targetPath);

                  $fileNamePancardProof = $postData['pancard_proof']['name'];
                  $fileTmpNamePancardProof = $postData['pancard_proof']['tmp_name'];
                  $pancardProofImageName = date("d-m-Y") . "-" . time() . $fileNamePancardProof;
                  $targetPath = "public/upload/commonuser/pancardproof/" . $pancardProofImageName;
                  move_uploaded_file($fileTmpNamePancardProof, $targetPath);

                  $fileNameLogo = $postData['company_logo']['name'];
                  $fileTmpNameLogo = $postData['company_logo']['tmp_name'];
                  $logoImageName = date("d-m-Y") . "-" . time() . $fileNameLogo;
                  $targetPath = "public/upload/commonuser/logo/" . $logoImageName;
                  move_uploaded_file($fileTmpNameLogo, $targetPath); */


//                //file end


                $date = date('Y-m-d H:i:s');
                $finalData = [];
                $finalData = [
                    'user_id' => $user_id,
                    'company_name' => $postData['company_name'],
                    'company_address' => $postData['office_address'],
                    'city' => $postData['city_value'],
                    'state' => $stateId,
                    'country' => $countryId,
                    'pincode' => $postData['company_pincode'],
                    'service_tax_gst' => $postData['service_tax_gst'],
                    'pancard_no' => $postData['pancard_no'],
                    'contact_person_name' => $postData['contact_person'],
                    'landline_no' => $postData['company_phone_no'],
                    'mobile_no' => $postData['company_mobile_no'],
                    'email' => $postData['email'],
                    'website_url' => $postData['website_url'],
                    'added_by' => $user_id,
                    'created_date' => $date
                ];


                //echo '<pre>';print_r($finalData);die();
                //$url = $this->apiAdminUrl() . "users/addcompany";
                $url = $this->apiUrl() . "/company";
                $val = $this->post($url, $finalData);
                $JsonData = $val->getBody();
                //print_r($JsonData); exit;
                $JsonData = Json::decode($JsonData, true);
                //echo '<pre>';print_r($JsonData);die();
                if ((!empty($JsonData))) {
                    // $usertype=$this->$usertype;
                    $finalData2 = ['user_id' => $user_id, 'signup_status' => 4];
                    $this->registrationModel->updateSignupStatus($finalData2);
                    //echo $usertype; die;

                    switch ($usertype) {
                        case "driver":
                            $this->redirect()->toRoute($usertype, ['action' => 'vehicle-info']);
                            break;
                        case "vendor":
                            $this->redirect()->toRoute($usertype, ['action' => 'vehicle-info']);
                            break;
                        case "corporate-user":
                            $finalData2 = ['user_id' => $user_id, 'signup_status' => 10];
                            $this->registrationModel->updateSignupStatus($finalData2);

                            $userData = new Container('userdata');
                            $mobile = $userData->mobile_no;
                            $first_name = $userData->first_name;
                            $email = $userData->email;
                            $referralBy = $userData->referralBy;
                            $referralCode = $userData->referral_code;
                            $username = $userData->username;
                            $password = $userData->password;

                            $commondata = ['user_id' => $user_id,
                                'user_type_id' => $userTypeId,
                                'mobile' => $mobile,
                                'email' => $email,
                                'user_name' => $first_name,
                                'referralBy' => $referralBy,
                                'referral_code' => $referralCode,
                                'template_name' => 'acc_verify_code',
                                'username' => $username,
                                'password' => $password
                            ];
                            $this->commonRedirect($commondata);

                            $this->redirect()->toRoute($usertype, ['action' => 'thanks']);
                            break;
                        case "travel-agent":

                            $finalData2 = ['user_id' => $user_id, 'signup_status' => 10];
                            $this->registrationModel->updateSignupStatus($finalData2);

                            $userData = new Container('userdata');
                            if (empty($userData->username)) {
                                $userData = new Container('userlogin');
                            }
                            $mobile = $userData->mobile_no;
                            $first_name = $userData->first_name;
                            $email = $userData->email;
                            $referralBy = $userData->referralBy;
                            $referralCode = $userData->referral_code;
                            $username = $userData->username;
                            $password = $userData->password;

                            $commondata = ['user_id' => $user_id,
                                'user_type_id' => $userTypeId,
                                'mobile' => $mobile,
                                'email' => $email,
                                'user_name' => $first_name,
                                'referralBy' => $referralBy,
                                'referral_code' => $referralCode,
                                'template_name' => 'acc_verify_code',
                                'username' => $username,
                                'password' => $password
                            ];
                            $this->commonRedirect($commondata);

                            $this->redirect()->toRoute($usertype, ['action' => 'thanks']);
                            break;
                        case "guide":
                            $this->redirect()->toRoute($usertype, ['action' => 'duty-info']);
                            break;
                        case "hotel":

                            $finalData2 = ['user_id' => $user_id, 'signup_status' => 10];
                            $this->registrationModel->updateSignupStatus($finalData2);

                            $userData = new Container('userdata');
                            if (empty($userData->username)) {
                                $userData = new Container('userlogin');
                            }
                            $mobile = $userData->mobile_no;
                            $first_name = $userData->first_name;
                            $email = $userData->email;
                            $referralBy = $userData->referralBy;
                            $referralCode = $userData->referral_code;
                            $username = $userData->username;
                            $password = $userData->password;

                            $commondata = ['user_id' => $user_id,
                                'user_type_id' => $userTypeId,
                                'mobile' => $mobile,
                                'email' => $email,
                                'user_name' => $first_name,
                                'referralBy' => $referralBy,
                                'referral_code' => $referralCode,
                                'template_name' => 'acc_verify_code',
                                'username' => $username,
                                'password' => $password
                            ];
                            $this->commonRedirect($commondata);
                            $this->redirect()->toRoute($usertype, ['action' => 'thanks']);
                            break;

                        default:
                            echo "something went wrong";
                    }
                } else {

                    return new JsonModel(['error' => $JsonData['error']]);
                    exit();
                }

                //  \Zend\Debug\Debug::dump($jsonData); die();
                //$this->redirect()->toRoute('driver', ['action' => 'driver-company-info']);
            } else {

                //$msg = $companyInfoForm->getMessages();
                //\Zend\Debug\Debug::dump($msg);die;
            }
        }

        $viewModel = new ViewModel(['form' => $companyInfoForm, 'valid_email' => $msg, 'usertypename' => $usertype, 'userTypeId' => $userTypeId]);
        return $viewModel;
    }

    public function vehicleInfoAction() {
        $sessionContainer = new Container('userlogin');
        $usertype = $sessionContainer->usertype;
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        if ($user_id == '') {
            $this->redirect()->toRoute('home');
        }

        /* $sessionUser = new Container('userlogin');
          $userId = $sessionUser->userData['user_id'];
          if ($userId != "") {
          $this->redirect()->toRoute('home');
          }

          $sessionContainer = new Container('userdata');
          $usertype = $sessionContainer->usertype;
          $userTypeId = $sessionContainer->userTypeId;
          $user_id = $sessionContainer->user_id;
          if($user_id==''){
          $this->redirect()->toRoute('home');
          } */
        $request = $this->getRequest();
        $vehicleInfoForm = new VehicleRegistrationForm();


        if ($request->isPost()) {

            $postData = $this->getRequest()->getPost()->toArray();
            // echo '<pre>';print_r($postData);die();
            /* if ($_FILES['rc_proof']['name'] != '') {
              $fileNameOfficeAdd = $_FILES['rc_proof']['name'];
              $fileTmpNameOfficeAdd = $_FILES['rc_proof']['tmp_name'];
              $officeAddImageName = date("d-m-Y") . "-" . time() . $fileNameOfficeAdd;
              $folderpath = $user_id;
              $uploaddir = $_SERVER['DOCUMENT_ROOT'];

              $file = '/upload/';
              $filepath = $uploaddir . $file . $folderpath;
              $fileCreate = mkdir($filepath, 0777, true);
              chmod($filepath, 0777);
              $targetPath = $filepath . "/" . $officeAddImageName;
              move_uploaded_file($fileTmpNameOfficeAdd, $targetPath);
              $postData['rc_proof'] = $officeAddImageName;
              } */


            $vehicleInfoForm->setData($postData);

            if ($vehicleInfoForm->isValid()) {

                /* $fileNameRcProof = $postData['rc_proof']['name'];
                  $fileTmpNameRcProof = $postData['rc_proof']['tmp_name'];
                  $rcProofImageName = date("d-m-Y") . "-" . time() . $fileNameRcProof;
                  $targetPath = "public/upload/commonuser/rcproof/" . $rcProofImageName;
                  move_uploaded_file($fileTmpNameRcProof, $targetPath);

                  $fileNameInsuranceProof = $postData['insurance_proof']['name'];
                  $fileTmpNameInsuranceProof = $postData['insurance_proof']['tmp_name'];
                  $insuranceProofImageName = date("d-m-Y") . "-" . time() . $fileNameInsuranceProof;
                  $targetPath = "public/upload/commonuser/insuranceproof/" . $insuranceProofImageName;
                  move_uploaded_file($fileTmpNameInsuranceProof, $targetPath);

                  $fileNameFitnessProof = $postData['fitness_proof']['name'];
                  $fileTmpNameFitnessProof = $postData['fitness_proof']['tmp_name'];
                  $fitnessProofImageName = date("d-m-Y") . "-" . time() . $fileNameFitnessProof;
                  $targetPath = "public/upload/commonuser/fitnessproof/" . $fitnessProofImageName;
                  move_uploaded_file($fileTmpNameFitnessProof, $targetPath); */
                //file end
                /* if (isset($_FILES['rc_proof']['name']) && $_FILES['rc_proof']['name'] != '') {
                  $arrData = array('file_name' => 'rc_proof', 'user_id' => $user_id);
                  $this->uploadFile($arrData);
                  }
                  if (isset($_FILES['insurance_proof']['name']) && $_FILES['insurance_proof']['name'] != '') {
                  $arrData = array('file_name' => 'insurance_proof', 'user_id' => $user_id);
                  $this->uploadFile($arrData);
                  }
                  if (isset($_FILES['fitness_proof']['name']) && $_FILES['fitness_proof']['name'] != '') {
                  $arrData = array('file_name' => 'fitness_proof', 'user_id' => $user_id);
                  $this->uploadFile($arrData);
                  } */
                $vehicle_no = $postData['vehicle_code'] . "-" . $postData['vehicle_number'];

                $date = date('Y-m-d H:i:s');
                $finalData = [
                    'vehicle_exist_id' => $postData['vehicle_exist_status'],
                    'vehicle_value' => $postData['vehicle_value'],
                    'total_fleet_no' => $postData['total_fleet_no'],
                    'name' => $postData['name'],
                    // 'vehicle_type_id;'=>$postData['vehicle_value'],
                    'ignition_type_id' => $postData['ignition_type_id'],
                    'vehicle_no' => $vehicle_no,
                    'color' => $postData['color'],
                    'vehicle_owner_type' => $postData['vehicle_owner_type'],
                    'vehicle_owner_name' => $postData['vehicle_owner_name'],
                    'vehicle_owner_mobile' => $postData['vehicle_owner_cnt_no'],
                    'permit_exp_date' => date('Y-m-d', strtotime($postData['permit_exp_date'])),
                    'user_id' => $user_id,
                    'created_date' => $date,
                    'created_by' => $user_id
                ];
                //echo'<pre>';print_r($finalData);die();
                $finalData = array_filter($finalData);


                $url = $this->apiUrl() . "/vehicle-master/addvehicle";
                $val = $this->post($url, $finalData);
                $JsonData = $val->getBody();
                $JsonData = Json::decode($JsonData, true);


                if ((!empty($JsonData)) && $JsonData['response']['status'] == "success") {

                    $finalData2 = ['user_id' => $user_id, 'signup_status' => 4];
                    $this->registrationModel->updateSignupStatus($finalData2);

                    switch ($usertype) {
                        case "driver":
                            $this->redirect()->toRoute($usertype, ['action' => 'duty-info']);
                            break;
                        case "vendor":
                            $this->redirect()->toRoute($usertype, ['action' => 'duty-info']);
                            break;

                        default:
                            echo "something went wrong";
                    }
                } else {

                    return new JsonModel(['error' => $JsonData['error']]);
                    exit();
                }
            }

//            else{
//                $msg = $drivervehicleInfoForm->getMessages();
//               \Zend\Debug\Debug::dump($msg);die;
//            }
        }

        $viewModel = new ViewModel(['form' => $vehicleInfoForm]);
        return $viewModel;
    }

    public function dutyInfoAction() {
        $sessionContainer = new Container('userlogin');
        $usertype = $sessionContainer->usertype;
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        if ($user_id == '') {
            $this->redirect()->toRoute('home');
        }
//        $sessionUser = new Container('userlogin');
//        $userId = $sessionUser->userData['user_id'];
//        if ($userId != "") {
//            $this->redirect()->toRoute('home');
//        }
//        $msg="";
//        $sessionContainer = new Container('userdata');
//        $usertype = $sessionContainer->usertype;
//        $userTypeId = $sessionContainer->userTypeId;
//        $user_id = $sessionContainer->user_id;
//        if($user_id==''){
//            $this->redirect()->toRoute('home');
//        }
        $msg = "";
        $userData = new Container('userdata');
        $mobile = $userData->mobile_no;
        $first_name = $userData->first_name;
        $email = $userData->email;
        $referralBy = $userData->referralBy;
        $referralCode = $userData->referral_code;
        $username = $userData->username;
        $password = $userData->password;
        $user_id = $userData->user_id;

        DutyRegistrationForm:: $dutytype = $this->userModel->getPackageTypeList();
        DutyRegistrationForm:: $paymenttype = $this->userModel->getPaymentTypeList();
        DutyRegistrationForm:: $langspeak = $this->userModel->getLanguageList();
        DutyRegistrationForm:: $langwrite = $this->userModel->getLanguageList();
        DutyRegistrationForm:: $shiftlogin = $this->userModel->getShiftLoginList();
        $dutyInfoForm = new DutyRegistrationForm();
        $request = $this->getRequest();

        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();
            //echo '<pre>';print_r($postData);//die();
            $dutyInfoForm->setData($postData);
            if ($dutyInfoForm->isValid()) {

                //$drive_multiple = $postData['drive_multiple'];
                //$booking_type_size = sizeof($drive_multiple);
                //$cash = $postData['cash'];
                //$cash_type_size = sizeof($cash);
                //if ($booking_type_size >= 1 && $cash_type_size >= 1) {
                //$prefCity = implode(",", $postData['preferred_city']);
                $city_ids = str_replace(';', ',', $postData['city_search_id']);
                $speak = implode(",", $postData['language_speak']);
                $write = implode(",", $postData['language_write']);
                $shift = implode(",", $postData['shift_of_login']);
                $payment_cash = implode(",", $postData['payment_type']);
                $booking_type = implode(",", $postData['duty_type']);
                $date = date('Y-m-d');

                $finalData = [];
                $finalData = [
                    'pref_city' => rtrim($city_ids, ","),
                    'speak' => $speak,
                    'write' => $write,
                    'shift' => $shift,
                    'payment_cash' => $payment_cash,
                    'booking_type' => $booking_type,
                    'user_id' => $user_id,
                    'created_date' => $date
                ];

                //echo '<pre>';print_r($finalData);die();
                //$url = $this->apiAdminUrl()."users/prefdrivecity";
                $url = $this->apiUrl() . "/user/addDutyDetail";
                $val = $this->post($url, $finalData);
                $JsonData = $val->getBody();
                $JsonData = Json::decode($JsonData, true);


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

                    $finalData2 = ['user_id' => $user_id, 'signup_status' => 5];
                    $this->registrationModel->updateSignupStatus($finalData2);

                    $commondata = ['user_id' => $user_id,
                        'user_type_id' => $userTypeId,
                        'mobile' => $mobile,
                        'email' => $email,
                        'user_name' => $first_name,
                        'referralBy' => $referralBy,
                        'referral_code' => $referralCode,
                        'template_name' => 'acc_verify_code',
                        'username' => $username,
                        'password' => $password
                    ];

                    $this->commonRedirect($commondata);


                    switch ($usertype) {
                        case "driver":
                            $this->redirect()->toRoute($usertype, ['action' => 'thanks']);
                            //$this->redirect()->toRoute('user', array('controller' => 'index', 'action' => 'thanks'));
                            break;
                        case "vendor":
                            $this->redirect()->toRoute($usertype, ['action' => 'thanks']);
                            //$this->redirect()->toRoute('user', array('controller' => 'index', 'action' => 'thanks'));
                            break;
                        case "guide":
                            $this->redirect()->toRoute($usertype, ['action' => 'thanks']);
                            //$this->redirect()->toRoute('user', array('controller' => 'index', 'action' => 'thanks'));
                            break;
                        default:
                            echo "something went wrong";
                    }
                } else {

                    return new JsonModel(['error' => $JsonData['error']]);
                    exit();
                }
            }
//                            else {
//                 $msg = $dutyInfoForm->getMessages();
//               \Zend\Debug\Debug::dump($msg);die;
//                }
        }

        $viewModel = new ViewModel(
                [
            'form' => $dutyInfoForm,
            'error_msg' => $msg
        ]);
        return $viewModel;
    }

    /** @CreatedBy   :
     *  @CreatedDate :
     *  @Description : User Redirect when user sign up account.
     * */
    public function redirectUser($arrData) {
        if (!empty($arrData)) {
            $userdata = $arrData['data'][0];
            $user_id = $userdata["user_id"];
            $userTypeId = $userdata["user_type_id"];
            $is_active = $userdata["is_active"];


            if (isset($user_id) && $user_id != '') {
                $sessionContainer = new Container('userlogin');
                $sessionContainer->user_id = $user_id;
            }
            //$data = ['status' => true, 'user_id' => $user_id];

            $signup_status = $userdata['signup_status'];

            if ($signup_status == 0) {
                $this->redirect()->toRoute('signup', ['action' => 'personal-info']);
            } else if ($signup_status > 0 && $signup_status != 10) {
                $this->redirect()->toRoute('signup', ['action' => 'company-info']);
            } else if ($signup_status > 0 && $signup_status == 10 && $is_active == 0) {
                $data = ['status' => false, 'message' => 'Account is not active,Contact with admin'];
                echo '<pre>';
                print_r($data);
                die();
                return $data;
            }
        }
        //Debug::dump($data); die;
    }

    public function verifyemailAction() {
        $is_email_varified = '';
        $user_id = $this->getRequest()->getQuery('id');
        $username = $this->getRequest()->getQuery('username');
        //$password = $this->getRequest()->getQuery('password');
        $user_type = $this->getRequest()->getQuery('type');
        $secretkey = $this->getRequest()->getQuery('secretkey');
        $saltKey = 'hello@42cab';
        $val = [];
        $verifyParameter = md5($user_id . $username . $user_type . $saltKey);

        if (!empty($user_id)) {
            $url = $this->apiUrl() . "/user/userpersonalinfo?user_id=" . $user_id;
            $resp = $this->get($url);
            $cityJsonData = Json::decode($resp->getBody(), true);

            if ($cityJsonData['responsedata']['status'] == 'success') {
                $is_email_varified = $cityJsonData['responsedata']['data']['email_verified'];

                if ($is_email_varified == 1) {
                    $is_email_varified = 'Your email id is already Verified !';
                } elseif ($secretkey == $verifyParameter) {
                    // update email verify and update //
                    $url2 = $this->apiUrl() . "/user/emailVerifyStatus";
                    $finalData2 = ['id' => $user_id, 'emailverifystatus' => 1];
                    $val = $this->put($url2, $finalData2);
                    $is_email_varified = 'Your email id verification completed successfully.';
                }
            }
        }


        $viewModel = new ViewModel(['is_email_varified' => $is_email_varified]);
        return $viewModel;
    }

    /**
     * @type   function()
     * @return ViewModel
     */
    public function checkAlreadyExistUserAction() {
        $request = $this->getRequest();
        if ($request->isPost()) {
            $fieldName = $request->getPost("id");
            $value = $request->getPost("value");
            $userTypeId = $request->getPost("userTypeId");
            //$url = $this->apiUrl() . "/user/verifyregister?username=" . $value . "&user_type_id=" . $userTypeId;
            $url = $this->apiUrl() . "/user/verifyregister?username=" . $value;
            $val = $this->get($url);
            $JsonData = $val->getBody();
            $responseData = Json::decode($JsonData, true);

            if (isset($responseData['responsedata']['status']) && $responseData['responsedata']['status'] == 'failed') {
                return new JsonModel(["id" => $fieldName, "message" => "<p style='color:green;'>Available</p>", 'status' => false, 'signup_status' => 0]);
            } else {
                $signup_status = $responseData['responsedata']['data']['signup_status'];
                $is_active = $responseData['responsedata']['data']['is_active'];
                if ($signup_status != 10 && $is_active == 4) {
                    return new JsonModel(["id" => $fieldName, "message" => "<p style='color:red;'>($value) Already Exists, Registration not completed.</p>", 'status' => true, 'signup_status' => $signup_status]);
                } else if ($signup_status == 10 && $is_active == 4) {
                    return new JsonModel(["id" => $fieldName, "message" => "<p style='color:red;'>Account is not active. Please contact administrator.</p>", 'status' => true, 'signup_status' => $signup_status]);
                } else {
                    return new JsonModel(["id" => $fieldName, "message" => "<p style='color:red;'>($value) Already Exists</p>", 'status' => true, 'signup_status' => $signup_status]);
                }
            }
        }

        exit();
    }

    /** @comment: Get Company List */
    public function companyListAction() {

        $request = $this->getRequest();
        $postdata = $request->getPost();
        $term = $postdata['term'];
        //echo $url = $this->apiUrl() . "/users/searchcompany?company_name=" . $term;die;
        //$resp = $this->get($url);

        $val = '{"where": {"company_name": {"like": "' . $term . '%"}},"limit":10}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/company?&filter=" . $val;
        $resp = $this->get($url);

        $companylistJsonData = Json::decode($resp->getBody(), true);
        //Debug::dump($companylistJsonData); exit;

        if (!empty($companylistJsonData)) {
            foreach ($companylistJsonData as $value) {

                $data[] = array(
                    "label" => $value['company_name'], //company_name is the column name in the table
                    "value" => $value['id'],
                    "company_address" => $value['company_address'],
                    "city_name" => $value['city_name'],
                    "pincode" => $value['pincode'],
                    "service_tax_gst" => $value['service_tax_gst'],
                    "pancard_no" => $value['pancard_no'],
                    "contact_person_name" => $value['contact_person_name'],
                    "mobile_no" => $value['mobile_no'],
                    "email" => $value['email'],
                    "website_url" => $value['website_url'],
                    "is_exist" => true,
                );
            }
        } else {
            $data[] = array(
                "is_exist" => false,
            );
        }


        $view = new JsonModel($data);
        return $view;
    }

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

        $request = $this->getRequest();
        $postdata = $request->getPost();
        $term = $postdata['term'];

        //$val = '{"where":{"and": [{"city_id": "'.$city.'"},{"area": {"like": "' . $term . '%"}}]},"limit":10}';
        $val = '{"where": {"name": {"like": "%' . $term . '%"}},"limit":10}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/city?&filter=" . $val;
        $resp = $this->get($url);

        //echo $resp->isSuccess();exit;
        $cityJsonData = Json::decode($resp->getBody(), true);
        if (!empty($cityJsonData)) {
            foreach ($cityJsonData as $value) {
                $data[] = ["label" => $value['name'], "value" => $value['id']];
            }
        } else {
            $data[] = ["label" => 'No Record Found'];
        }

        $view = new JsonModel($data);
        return $view;
    }

    /** @  Search vehicle name */
    public function vehicleListAction() {
        $request = $this->getRequest();
        $postdata = $request->getPost();
        $term = $postdata['term'];

        $val = '{"where": {"name": {"like": "' . $term . '%"}},"limit":10}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/vehicle-model?&filter=" . $val;
        //echo $url;die;

        $resp = $this->get($url);
        $vehiclelistJsonData = Json::decode($resp->getBody(), true);

        if (!empty($vehiclelistJsonData)) {
            foreach ($vehiclelistJsonData as $value) {
                $data[] = array(
                    "label" => $value['name'],
                    "value" => $value['id']
                );
            }
        } else {
            $data = $vehiclelistJsonData;
        }

        $view = new JsonModel($data);
        return $view;
    }

    public function uploadFile($arrVal = array()) {

        $fileName = $arrVal['file_name'];
        $userId = $arrVal['user_id'];

        if ($_FILES['file']['name'] != '') {
            $fileNameOfficeAdd = $_FILES['file']['name'];
            $fileTmpNameOfficeAdd = $_FILES['file']['tmp_name'];

            /* Get Upload document type Id By Name */
            $apiResp = $this->getDocumentTypeByName($fileName);
            $docTypeId = 0;
            if (!empty($apiResp)) {
                $docTypeId = $apiResp[0]['doc_type_id'];
                $documentName = $apiResp[0]['doc_level_name'];
            }
            /* END */

            $folderpath = $userId;
            $uploaddir = $_SERVER['DOCUMENT_ROOT'];

            $allowed = array('png', 'jpg', 'gif', 'zip', 'pdf', 'docx', 'doc', 'jpeg', '');
            $extension = pathinfo($_FILES[$fileName]['name'], PATHINFO_EXTENSION);

            if (!in_array(strtolower($extension), $allowed)) {
                return array("status" => "error", 'message' => 'Please upload (png,jpg,gif,zip,pdf,docx,doc,jpeg) file only.');
                exit;
            }

            $file = '/upload/';

            $filepath = $uploaddir . $file . $folderpath;
            /* $fileCreate = mkdir($filepath, 0777, true);
              chmod($filepath, 0777); */
            $fileUploadName = $documentName . '.' . $extension;
            $targetPath = $filepath . "/" . $fileUploadName;

            $kycFile = file_get_contents($fileTmpNameOfficeAdd);
            $base64string = base64_encode($kycFile);

            $finalData['base64image'] = $base64string;
            $finalData['filepath'] = $targetPath;

            $this->uploadimageapi($finalData);
            //move_uploaded_file($fileTmpNameOfficeAdd, $targetPath);
            //$fileUploadName = $base64string; ///// For convert file in Base64 ///
            $url2 = $this->apiUrl() . "/user/uploadDocument";
            $finalData2 = ['user_id' => $userId, 'doc_type_id' => $docTypeId, 'doc_file_upload' => $fileUploadName];
            $this->post($url2, $finalData2);


            return array("status" => "success", "fileUploadName" => $base64string);
        }
        return array("status" => "error");
    }

    /** @Description : Create Verify link for send in mail.  */
    public function verifyLink($arrVal = array()) {
        $user_id = $arrVal['user_id'];
        $username = $arrVal['username'];
        //$password = $arrVal['password'];
        $user_type_id = $arrVal['user_type_id'];
        $sercreatKey = 'hello@42cab';
        return $redirectLink = md5($user_id . $username . $user_type_id . $sercreatKey);
    }

    /** @type: function
     * @Description  : Generate Referal Code. */
    public function generateReferralCode($arrval = array()) {
        $unique_id = $arrval['user_id'];
        $firstname = $arrval['first_name'];
        return $referKey = substr($firstname, 0, 3) . $unique_id;
    }

    /* @type : text */

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

    /** @Description : Referral code check */
    public function referralcodeAction() {
        $request = $this->getRequest();
        $postdata = $request->getPost();

        $referralCode = $postdata['referral_code'];

        if ($referralCode != '') {
            $val = '{"where": {"referral_key":"' . $referralCode . '"}}';
            $val = rawurlencode($val);
            $url = $this->apiUrl() . "/user?&filter=" . $val;
            $resp = $this->get($url);

            $userData = Json::decode($resp->getBody(), true);
        }

        if (!empty($userData)) {
            foreach ($userData as $value) {
                $data = ["user_id" => $value['id']];
            }
        } else {
            $data = ["error" => 'Invalid Referral Code'];
        }

        $view = new JsonModel($data);
        return $view;
    }

    /** @CreatedBy    : Mohit Verma
      /** @CreatedDate  : 2-Nov-2018
     *  @Description  : After completed signup redirect on thanks page.
     * */
    public function thanksAction() {
        $sessionContainer = new Container('userlogin');
        $user_id = $sessionContainer->user_id;
        $data = ['user_id'=>$user_id];
        $this->registrationModel->registrationThanks($data);
        $viewModel = new ViewModel();
        return $viewModel;
    }

    /** @CreatedBy    : Mohit Jain
      /*@CreatedDate  : 13-Nov-2018
     *  @Description  : After completed signup redirect on Confirm Page.
     * @modified_date : 15-oct-2019
     * @Modified_by : Mohit verma
     * */
    public function confirmotpAction() {
        $sessionUser = new Container('userlogin');
        $user_id = ($sessionUser->userData['user_id'] != '') ? $sessionUser->userData['user_id'] : $sessionUser->user_id;
        $password = ($sessionUser->userData['password'] != '') ? $sessionUser->userData['password'] : $sessionUser->password;
        if ($user_id == "") {
            $this->redirect()->toRoute('home');
        }
        $msg = "";
        $viewModel = new ViewModel();
        /* $sessionContainer = new Container('userdata');
          $usertype = $sessionContainer->usertype;
          $userTypeId = $sessionContainer->userTypeId;
          $user_id = ($sessionContainer->user_id)?$sessionContainer->user_id:$userId;
          if ($user_id == '') {
          $this->redirect()->toRoute('home');
          } */

        $form = new ConfirmOtpForm();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();
            //echo '<pre>';print_r($postData);die();
            $form->setData($postData);
            if ($form->isValid()) {
                $data = [
                    'user_id' => $user_id,
                    'confirm_otp' => $postData['confirm_otp']
                ];

                $rep = $this->fetchOtp($data);
                if ($rep['status'] == "success") {
                    $data = ['id' => $rep['data']['id'], 'UID' => $rep['data']['UID'], 'Verification_code' => $rep['data']['Verification_code'], 'isUsed' => 1];
                    $this->updateOtp($data);
                    $vefiryData = ['id' => $user_id, 'mobileverifystatus' => 1, 'user_type_id' => $userTypeId, 'password'=>$password];
                    $this->updateMobileVerifyStatus($vefiryData);

                    $finalData2 = ['user_id' => $user_id, 'signup_status' => 2];
                    $this->registrationModel->updateSignupStatus($finalData2);

                    //Debug::dump($aa);
                    if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                        $viewModel = new JsonModel();
                        $result = ['result' => true, 'currentUrlRedirect' => 'Y'];
                        $viewModel->setVariables(['data' => $result]);
                        return $viewModel;
                    } else {
                        unset($sessionContainer->user_id);
                        $this->redirect()->toRoute($usertype, ['action' => 'personal-info']);
                    }
                } 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;
                    }
                    /* END */
                }
            }
            /* Code must be Uncomment when login is required */
            /* else {
              $result = ['result' => false, 'message' => $form->getMessages()];
              if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
              $viewModel = new JsonModel();
              }
              $viewModel->setVariables(['data' => $result]);
              return $viewModel;
              } */
        }

        $viewModel = new ViewModel([
            'form' => $form,
            'msg' => $msg
        ]);
        return $viewModel;
    }

    /**
     * @CreatedDate : 12-Oct-2018
     * @createdBy   : Mohit Verma
     * @description : Home page User Signup
     * @
     */
    public function popupSignupAction() {

        $sessionuserData = new Container('userlogin');
        //$loginData = $sessionContainer->loginData;
        $username = $sessionuserData->username;
        $password = $sessionuserData->password;
        $userTypeId = 1;
        $usertype = $sessionuserData->usertype;

        $docTypeNameObj = $this->config()->getConfig()->document_file_upload_name;
        $docTypeNameArr = $docTypeNameObj->toArray();

        $request = $this->getRequest();
        $personalInfoForm = new PopupRegistrationForm();

        $personalInfoForm->get('email')->setAttribute('readonly', '');
        $personalInfoForm->get('contact_no')->setAttribute('readonly', '');
        if (ctype_digit($username)) {
            $personalInfoForm->get('contact_no')->setValue($username);
            $personalInfoForm->get('contact_no')->setAttribute('readonly', 'true');
        } else {
            $personalInfoForm->get('email')->setValue($username);
            $personalInfoForm->get('email')->setAttribute('readonly', 'true');
        }

        if ($request->isPost()) {
            $postData = $this->getRequest()->getPost()->toArray();
            $postData = array_filter($postData);
            //echo '<pre>';print_r($postData);die();
            $personalInfoForm->setData($postData);

            $password = trim($postData['password']);
            $confirmPassword = trim($postData['confirm_password']);
            $msg = '';
            if ($password != $confirmPassword) {
                $msg = "Password did n't match";
            }

            if ($personalInfoForm->isValid() && $msg == '') {

                $finalData = [];
                $finalData = [
                    'firstName' => $postData['first_name'],
                    'lastName' => $postData['last_name'],
                    'email' => $postData['email'],
                    'mobile' => $postData['contact_no'],
                    'user_type_id' => $userTypeId,
                    'password' => md5($postData['password'])
                ];

                /* Add registration user */
                $finalData = array_filter($finalData);
                $url = $this->apiUrl() . "/user/signup";
                $val = $this->post($url, $finalData);
                $JsonData = $val->getBody();
                $JsonData = Json::decode($JsonData, true);
                /* END */

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

                    $data = $JsonData['responsedata']['status'];
                    $user_id = $JsonData['responsedata']['user_id'];
                    if ($user_id != '') {
                        $loginuserdata = $this->userSignupLogin($user_id);
                        $sessionuserData->user_id = $user_id;
                        $sessionuserData->userData = $loginuserdata['responsedata'];
                    }


                    /* Update Referral Key */
                    $referralParams = array('user_id' => $user_id, 'first_name' => $postData['first_name']);
                    $referralCode = $this->generateReferralCode($referralParams);
                    $update_referal_key = $this->apiUrl() . "/user/updateReferralCode";
                    $referral_key_param = ['id' => $user_id, 'referral_code' => $referralCode];
                    $this->put($update_referal_key, $referral_key_param);
                    /* END */



                    /* Send Welcome Mail Starts Here */

                    $sendMailParam = [
                        'user_id' => $user_id,
                        'user_name' => $postData['first_name'],
                        'user_email' => $postData['email'],
                        'username' => $username,
                        'user_password' => $password,
                        'user_type_id' => $userTypeId,
                        'template_name' => 'welcome',
                        'subject' => 'Welcome to hello42cab'
                    ];

                    $this->sendMail($sendMailParam);
                    /* END Mail */
                    if ($data == 1) {
                        /* Update Signup Status */
                        $url2 = $this->apiUrl() . "/user/updatesignupstatus";
                        $finalData2 = ['user_id' => $user_id, 'signup_status' => 10];
                        $this->put($url2, $finalData2);
                        /* End */

                        $commondata = ['user_id' => $user_id,
                            'user_type_id' => $userTypeId,
                            'mobile' => $postData['contact_no'],
                            'email' => $postData['email'],
                            'user_name' => $postData['first_name'],
                            'referralBy' => $referralBy,
                            'template_name' => 'acc_verify_code',
                            'username' => $username,
                            'password' => $password
                        ];
                        $this->commonRedirect($commondata);
                    }
                    $result = ['result' => true, 'popup' => 1];
                } else {

                    return new JsonModel(['error' => $JsonData['error']]);
                    exit();
                }
            } else {
                $result = ['result' => false, 'message' => $personalInfoForm->getMessages(), 'popup' => 1];
            }

            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }
        $viewModel = new ViewModel(['form' => $personalInfoForm, 'usertype' => $usertype]);
        $viewModel->setTerminal(true);
        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;
    }

    /* Update Mobile verify status */

    public function updateMobileVerifyStatus($arrData) {
        $url2 = $this->apiUrl() . "/user/updateMobileVerify";
        $resp = $this->post($url2, $arrData);
        $response = Json::decode($resp->getBody(), true);
        return $response;
    }

    /* END */

    /** Get Signup referral Amount */
    public function getReferralAmount($arrval = array()) {
        $userTypeId = $arrval['user_type_id'];
        $val = '{"where": {"user_type":"' . $userTypeId . '"}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/referral-discount-amount?&filter=" . $val;
        $resp = $this->get($url);
        $response = Json::decode($resp->getBody(), true);
        return $response;
    }

    /* End */

    /** Add Signup referral Amount */
    public function addReferralAmount($arrval = array()) {
        $url = $this->apiUrl() . "/referral-signup-history";
        $resp = $this->post($url, $arrval);
        $response = Json::decode($resp->getBody(), true);
        return $response;
    }

    /* End */

    /** Add user wallect transaction Amount */
    public function addUserWalletTransaction($arrval = array()) {
        $url = $this->apiUrl() . "/user-wallet-transaction";
        $resp = $this->post($url, $arrval);
        $response = Json::decode($resp->getBody(), true);
        return $response;
    }

    /* End */

    /** Update wallat amount */
    public function updateWallactAmount($arrval = array()) {
        $url = $this->apiUrl() . "/user/updateWalletAmount";
        $resp = $this->put($url, $arrval);
        $response = Json::decode($resp->getBody(), true);
        return $response;
    }

    /* END */

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

    public function userSignupLogin($user_id) {
        $url = $this->apiUrl() . "/user/userpersonalinfo?user_id=" . $user_id;
        $resp = $this->get($url);
        return $response = Json::decode($resp->getBody(), true);
    }

    public function refreshAction() {
        $form = new PersonalRegistrationForm();
        $postData = $this->getRequest()->getPost();
        $catpcha_file = $postData['captcha'] . '.png';
        @unlink(CAPTCHA_PATH . $catpcha_file);
        $captcha = $form->get('captcha')->getCaptcha();
        $data = array();
        $data['id'] = $captcha->generate();
        $data['src'] = $captcha->getImgUrl() .
                $captcha->getId() .
                $captcha->getSuffix();
        $view = new JsonModel($data);
        return $view;
    }

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

        $request = $this->getRequest();
        $postdata = $request->getPost();
        $term = $postdata['term'];

        //$val = '{"where":{"and": [{"city_id": "'.$city.'"},{"area": {"like": "' . $term . '%"}}]},"limit":10}';
        $val = '{"where": {"nationality": {"like": "' . $term . '%"}},"limit":10}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/country?&filter=" . $val;
        $resp = $this->get($url);

        //echo $resp->isSuccess();exit;
        $cityJsonData = Json::decode($resp->getBody(), true);
        if (!empty($cityJsonData)) {
            foreach ($cityJsonData as $value) {
                $data[] = ["label" => $value['nationality'], "value" => $value['id']];
            }
        } else {
            $data[] = ["label" => 'No Record Found'];
        }

        $view = new JsonModel($data);
        return $view;
    }

    /** @Description - Get Document Type Id From Document Name
     *  @Param : document level Name
     *  @CreatedDate : 5-April-2019
     *  @CreatedBy : Mohit Verma
     *  @Type : API function
     *  */
    public function getDocumentTypeByName($documentName) {
        $response = [];
        if (isset($documentName) && $documentName != '') {
            $val = '{"where": {"doc_level_name":"' . $documentName . '"}}';
            $val = rawurlencode($val);
            $url = $this->apiUrl() . "/document-type?&filter=" . $val;
            $resp = $this->get($url);
            return $response = Json::decode($resp->getBody(), true);
        } else {
            return $response;
        }
    }

    /**
     * @type   function()
     * @return ViewModel
     */
    public function checkAlreadyExistPasswordUserAction() {
        $request = $this->getRequest();
        if ($request->isPost()) {
            $fieldName = $request->getPost("id");
            $value = $request->getPost("value");
            $username = $request->getPost("username");
            $data = [];
            $data = [
                'username' => $username,
                'password' => md5($value)
            ];

            $url = $this->apiUrl() . "/user/checkPassword";
            $resp = $this->post($url, $data);
            $responseData = Json::decode($resp->getBody(), true);
            //echo '<pre>';print_r($responseData);die();
            if (isset($responseData['responsedata']['status']) && $responseData['responsedata']['status'] == 'false') {
                return new JsonModel(["id" => $fieldName, "message" => "<p style='color:green;'>Available</p>", 'status' => false]);
            } else {
                return new JsonModel(["id" => $fieldName, "message" => "<p style='color:red;'>($value) Already Exists</p>", 'status' => true]);
            }
        }

        exit();
    }

    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 == true) {
            $val = ["status" => true, "data" => Json::decode($resp->getBody(), true)];
        } else {
            $val = ["status" => false, "data" => ''];
        }
        return $val;
        //Debug::dump($response);
        //exit;
    }

    /** Add Signup referral Amount */
    public function uploadimageapi($arrval = array()) {
        $url = $this->apiUrl() . "/user/uploadImg";
        $val = $this->post($url, $arrval);
        $JsonData = $val->getBody();
        $JsonData = Json::decode($JsonData, true);
    }

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

        $request = $this->getRequest();
        $postdata = $request->getPost();
        $term = $postdata['term'];

        //$val = '{"where":{"and": [{"city_id": "'.$city.'"},{"area": {"like": "' . $term . '%"}}]},"limit":10}';
        $val = '{"where": {"name": {"like": "' . $term . '%"}},"limit":10}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/state?&filter=" . $val;
        $resp = $this->get($url);

        //echo $resp->isSuccess();exit;
        $cityJsonData = Json::decode($resp->getBody(), true);
        if (!empty($cityJsonData)) {
            foreach ($cityJsonData as $value) {
                $data[] = ["label" => $value['name'], "value" => $value['id']];
            }
        } else {
            $data[] = ["label" => 'No Record Found'];
        }

        $view = new JsonModel($data);
        return $view;
    }

    public function getCityDataAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $term = $postData['term'];
        $url = $this->apiUrl() . "/city/stateCountryByCityName?city_name=" . $term;
        $resp = $this->get($url);
        $cityJsonData = Json::decode($resp->getBody(), true);
        $cityData = $cityJsonData['response']['data'];
        if ($cityJsonData['response']['status'] == "success") {
            foreach ($cityData as $value) {
                $data[] = ["country_id" => $value['country_id'], "state_id" => $value['state_id'], "city_id" => $value['city_id'], "label" => $value['citystatecountry']];
            }
        } else {
            $data[] = ["label" => 'Not Exist'];
        }
        $view = new JsonModel($data);
        return $view;
    }

    /**
     * @Description : Comman File upload using ajax function
     * @return JsonModel
     */
    public function uploadfileAction() {
        $sessionuserData = new Container('userlogin');
        $user_id = $sessionuserData->user_id;

        $postData = $this->getRequest()->getPost()->toArray();
        $fileName = $postData['fileuploadname'];

        $userId = $user_id;

        if ($_FILES['file']['name'] != '') {
            $fileNameOfficeAdd = $_FILES['file']['name'];
            $fileTmpNameOfficeAdd = $_FILES['file']['tmp_name'];


            /* Get Upload document type Id By Name */
            $apiResp = $this->getDocumentTypeByName($fileName);
            $docTypeId = 0;
            if (!empty($apiResp)) {
                $docTypeId = $apiResp[0]['doc_type_id'];
                $documentName = $apiResp[0]['doc_level_name'];
                $documentName = $documentName . "_" . time();
            }
            /* END */

            $folderpath = $userId;
            $uploaddir = $this->config()->getConfig()->base_url->file_path;
            //$uploaddir = $_SERVER['DOCUMENT_ROOT'];

            $allowed = array('png', 'jpg', 'gif', 'zip', 'pdf', 'docx', 'doc', 'jpeg', '');
            $extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);

            if (!in_array(strtolower($extension), $allowed)) {
                $data = array("status" => "error", 'message' => 'Please upload (png,jpg,gif,zip,pdf,docx,doc,jpeg) file only.');
                $view = new JsonModel($data);
                return $view;
            }

            //$file = '/upload/';

            $filepath = $uploaddir . $folderpath;
            /* $fileCreate = mkdir($filepath, 0777, true);
              chmod($filepath, 0777); */
            $fileUploadName = $documentName . '.' . $extension;
            $targetPath = $filepath . "/" . $fileUploadName;

            $kycFile = file_get_contents($fileTmpNameOfficeAdd);
            $base64string = base64_encode($kycFile);

            $finalData['base64image'] = $base64string;
            $finalData['filepath'] = $targetPath;

            $uploadresp = $this->uploadimageapi($finalData);
            if ($uploadresp['status'] == 'failed') {
                $data = array("status" => "error", "message" => $uploadresp['message']);
                return $view = new JsonModel($data);
            }
            //move_uploaded_file($fileTmpNameOfficeAdd, $targetPath);
            //$fileUploadName = $base64string; ///// For convert file in Base64 ///
            $url2 = $this->apiUrl() . "/user/uploadDocument";
            $finalData2 = ['user_id' => $userId, 'doc_type_id' => $docTypeId, 'doc_file_upload' => $fileUploadName];
            $this->post($url2, $finalData2);


            $data = array("status" => "success", 'message' => "File uploaded successfully", "fileUploadName" => $base64string);
        }
        // $data= array("status" => "error");
        $view = new JsonModel($data);
        return $view;
    }

    public function userdataAction() {
        $sessionUser = new Container('userlogin');
        $userData = $sessionUser->userData;
        $data = [
            'first_name' => $userData['first_name'],
            'last_name' => $userData['last_name'],
            'mobile' => $userData['mobile'],
            'alt_mobile_number' => $userData['alternate_mobile'],
            'email' => $userData['email']
        ];
        $view = new JsonModel($data);
        return $view;
    }

    public function newslettersubscriptionAction() {
        $is_newsletter_verified = '';
        $user_id = $this->getRequest()->getQuery('id');
        $newsletter_status = $this->getRequest()->getQuery('newsletter_status');
        $secretkey = $this->getRequest()->getQuery('secretkey');
        $saltKey = 'hello@42cab';
        $val = [];
        $verifyParameter = md5($user_id . $newsletter_status . $saltKey);
        if (!empty($user_id)) {
            if ($secretkey == $verifyParameter) {
                $url = $this->apiUrl() . "/user/userpersonalinfo?user_id=" . $user_id;
                $resp = $this->get($url);
                $cityJsonData = Json::decode($resp->getBody(), true);
                if ($cityJsonData['responsedata']['status'] == 'success') {
                    $is_newsletter_verified = $cityJsonData['responsedata']['data']['newsletter_subscription'];
                    if ($is_newsletter_verified == 1 && $newsletter_status == 1) {
                        $is_newsletter_verified = 'Your Newsletter Subscription as Already Subscribed';
                    } else if ($is_newsletter_verified == 0 && $newsletter_status == 0) {
                        $is_newsletter_verified = 'Your Newsletter Subscription as Already Un-Subscribed';
                    } else {
                        $url2 = $this->apiUrl() . "/user/newsletterVerifyStatus";
                        $finalData2 = ['id' => $user_id, 'newsletter_subscription' => $newsletter_status];
                        $val = $this->put($url2, $finalData2);
                        if ($newsletter_status == 1) {
                            $is_newsletter_verified = 'Your Newsletter Subscription Subscribed Successfully.';
                        } else {
                            $is_newsletter_verified = 'Your Newsletter Subscription Un-Subscribed Successfully.';
                        }
                    }
                } else {
                    $is_newsletter_verified = 'Invalid User!';
                }
            }
        }
        $viewModel = new ViewModel(['is_newsletter_verified' => $is_newsletter_verified]);
        return $viewModel;
    }

    public function subscribeNewsletterAction() {
        $sessionuserData = new Container('userlogin');
        $user_id = $sessionuserData->user_id;
        $request = $this->getRequest();
        /////////////////
        if ($request->isPost()) {
            $result = [];
            if ($request->isXmlHttpRequest()) {
                $post = $request->getPost()->toArray();
                //echo '<pre>';print_r($post);
                $first_name = (trim($post['first_name']));
                $last_name = (trim($post['last_name']));
                $email = trim($post['email']);
                $contact_no = trim($post['contact_no']);
                $email_subscription = trim($post['email_subscription']);
                $mobile_subscription = trim($post['mobile_subscription']);
                $both_subscription = trim($post['both_subscription']);

                $newsletter_subscription = $email_subscription;
                $mobile_promotion = $mobile_subscription;
                if (isset($both_subscription) && $both_subscription == 1) {
                    $newsletter_subscription = 1;
                    $mobile_promotion = 1;
                }

                $JsonData = $this->registrationModel->verifyRegisterUser($email);
                //echo '<pre>';print_r($JsonData);die();
                if ((!empty($JsonData)) && ($JsonData['responsedata']['status']) == "success") {
                    $user_id = $JsonData['responsedata']['data']['user_id'];
                    $url = $this->apiUrl() . "/user/userpersonalinfo?user_id=" . $user_id;
                    $resp = $this->get($url);
                    $userData = Json::decode($resp->getBody(), true);
                    //echo '<pre>';print_r($userData);die();
                    $is_newsletter_verified = $userData['responsedata']['data']['newsletter_subscription'];
                    $is_mobile_subscribed = $userData['responsedata']['data']['mobile_promotion'];
                    if (($is_newsletter_verified == $newsletter_subscription) && ($is_mobile_subscribed == $mobile_promotion)) {
                        $status = "success";
                        $msg = 'Your Newsletter Subscription Already Subscribed';
                    } else {
                        $url2 = $this->apiUrl() . "/user/newsletterVerifyStatus";
                        $finalData2 = [
                            'id' => $user_id,
                            'newsletter_subscription' => $newsletter_subscription,
                            'mobile_promotion' => $mobile_promotion
                        ];
                        $val = $this->put($url2, $finalData2);
                        $user_id = $JsonData['responsedata']['data']['user_id'];
                        $url = $this->apiUrl() . "/user/userpersonalinfo?user_id=" . $user_id;
                        $resp = $this->get($url);
                        $userData = Json::decode($resp->getBody(), true);
                        //echo '<pre>';print_r($userData);die();
                        $is_newsletter_verified = $userData['responsedata']['data']['newsletter_subscription'];
                        $is_mobile_subscribed = $userData['responsedata']['data']['mobile_promotion'];
                        $status = "success";
                        if (($is_newsletter_verified == 1 && $is_mobile_subscribed == 1) || ($is_newsletter_verified == 1 && $is_mobile_subscribed == 0) || ($is_newsletter_verified == 0 && $is_mobile_subscribed == 1)) {
                            $msg = "Your Newsletter Subscription Subscribed Successfully";
                        } else {
                            $msg = "Your Newsletter Subscription Un-Subscribed Successfully";
                        }
                    }
                } 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,
                        'user_type_id' => 0,
                        '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);
                    if ($JsonData['responsedata']['status'] == 'success') {
                        $user_id = $JsonData['responsedata']['data']['user_id'];
                        $url2 = $this->apiUrl() . "/user/newsletterVerifyStatus";
                        $finalData2 = [
                            'id' => $user_id,
                            'newsletter_subscription' => $newsletter_subscription,
                            'mobile_promotion' => $mobile_promotion
                        ];
                        $val = $this->put($url2, $finalData2);
                        $status = "success";
                        $msg = "Your Newsletter Subscription Subscribed Successfully";
                    }
                }
            }
        }

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

}

//End class


