<?php

namespace User\Controller;

use Application\Controller\RestAPIClientController;
use User\Form\{
    RegistrationForm,
    ApiUserForm,
    PersonalRegistrationForm,
    DutyRegistrationForm,
    ServiceRegistrationForm,
    CompanyRegistrationForm,
    VehicleRegistrationForm,
    ConfirmOtpForm,
    PopupRegistrationForm,
    LoginForm
};
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;
use Dashboard\Model\CommonModel;
use Dashboard\Model\UserLicenseModel;

class RegistrationController extends RestAPIClientController {

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


    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 = $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->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_prefix' => $mobile_prefix,
                                    'mobile' => $contact_no,
                                    '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;
                                $JsonData = $this->registrationModel->userNewSignup($finalData);
                                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;
        $referralCode = $sessionuserData->referral_code;
        $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 == '') {

                // File upload in personal info//
               // $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' : '';
               // $residential_proof = (isset($_FILES['residential_proof']['name']) != '') ? 'residential_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 */

                $finalData = [];
                $finalData = [
                    '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'] : '',
                    'user_id' => $user_id,
                    'signup_status' => 2     //Upadte signup status in API //
                ];
                /* Add registration user */

                $finalData = array_filter($finalData);
                $JsonData = $this->registrationModel->updatePersonalInfo($finalData);

                /* END */

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

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

                    /* User registration data */
                    $loginuserData = new Container('userdata');
                    $loginuserData->user_id = $user_id;
                    $loginuserData->mobile_no = $postData['contact_no'];
                    $loginuserData->first_name = $postData['first_name'];
                    $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 //

                    if (isset($license_proof) && $license_proof != '') {
                        $arrData1 = array('file_name' => $license_proof, 'user_id' => $user_id);
                        $uploadDataArr = $this->uploadFile($arrData1);
                    }

                    // Upload license proff //
                    if (isset($residential_proof) && $residential_proof != '') {
                        $arrData2 = array('file_name' => $residential_proof, 'user_id' => $user_id);
                        $uploadDataArr = $this->uploadFile($arrData2);
                    }
                    // END- License Proof //
                    // 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 */
                     $userData = $this->registrationModel->getUserPersonalInfo($user_id);
                     $userdata = $userData['responsedata']['data'];

                    $sendMailParam = [
                        'user_id' => $user_id,
                        'user_name' => $userdata['first_name'],
                        //'user_name' => $postData['first_name'],
                        //'user_email' => $postData['email'],
                        'user_email' => $email,
                        'username' => $userdata['username'],
                        'user_password' => $password,
                        'referral_code' => $userdata['referral_key'],
                        '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-user":
                                $this->redirect()->toRoute($usertype, ['action' => 'company-info']);
                                break;
                            case "dmc-user":
                                $this->redirect()->toRoute($usertype, ['action' => 'company-info']);
                                break;
                            case "cruise-user":
                                $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' => 5];
                                $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']);

                        }
                    }
                } else {

                    return new JsonModel(['error' => $JsonData['response']['message']]);
                    exit();
                }
            }
//            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' => isset($referral_amount[0]['installation_amount_user'])?$referral_amount[0]['installation_amount_user']:'0',
            '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');
        }
        
        CompanyRegistrationForm::$countryprefix = $this->userModel->getCountryCodePrefix();
        $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);
            }
            if ($_FILES['gst_proof']['name'] != '') {
                $arrData = array('file_name' => 'gst_proof', 'user_id' => $user_id);
                $this->uploadFile($arrData);
            }
            if ($_FILES['company_logo']['name'] != '') {
                $arrData = array('file_name' => 'company_logo', 'user_id' => $user_id);
                $this->uploadFile($arrData);
            }
            if ($_FILES['pancard_proof']['name'] != '') {
                $arrData = array('file_name' => 'company_pancard_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'],
                    'country_prefix_land' => $postData['country_prefix_land'],
                    'country_prefix_mob' => $postData['country_prefix_mob'],
                    'added_by' => $user_id,
                    'created_date' => $date
                ];


               
                //$url = $this->apiAdminUrl() . "users/addcompany";
                $url = $this->apiUrl() . "/company";
                $val = $this->post($url, $finalData);
                $JsonData = $val->getBody();               
                $JsonData = Json::decode($JsonData, true);               
                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' => 4];
                            $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' => 'confirmotp']);
                            break;
                        case "travel-agent":
                            $finalData2 = ['user_id' => $user_id, 'signup_status' => 5];
                            $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' => 'confirmotp']);
                            break;
                        case "guide":
                            $this->redirect()->toRoute($usertype, ['action' => 'duty-info']);
                            break;                        
                        case "hotel-user":
                            $this->redirect()->toRoute($usertype, ['action' => 'service-info']);
                            break;
                        case "dmc-user":
                            $this->redirect()->toRoute($usertype, ['action' => 'service-info']);
                            break;
                        case "cruise-user":
                            $this->redirect()->toRoute($usertype, ['action' => 'service-info']);
                            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() {
        $sessionUser = new Container('userlogin');
        $user_id = $sessionUser->userData['user_id'];
        if ($user_id != "") {
           // $this->redirect()->toRoute('home');
        }
        $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');
          } */

        VehicleRegistrationForm::$colour = $this->registrationModel->getVehicleColour();
        VehicleRegistrationForm::$modelyear = $this->registrationModel->getVehileModelYear();
        $request = $this->getRequest();
        $vehicleInfoForm = new VehicleRegistrationForm();


        if ($request->isPost()) {

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

            $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'],
                    'model' => $postData['model'],
                    '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);
                //echo'<pre>';print_r($finalData);die();

                $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' => 5];
                    $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 = $vehicleInfoForm->getMessages();
//               \Zend\Debug\Debug::dump($msg);die;
//            }
        }

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

    public function dutyInfoAction() {
        $sessionUser = new Container('userlogin');
        $user_id = $sessionUser->userData['user_id'];
        if ($user_id != "") {
            $this->redirect()->toRoute('home');
        }
        $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');
        $userData = $this->registrationModel->getUserPersonalInfo($user_id);
        $userData = $userData['responsedata']['data'];
        //echo '<pre>';print_r($userData);//die();
        $mobile = $userData['mobile'];
        $first_name = $userData['first_name'];
        $email = $userData['email'];
        $referralBy = $userData['refer_by'];
        $referralCode = $userData['referral_key'];
        $username = $userData['username'];
        $password = $sessionContainer->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,
                    'created_by' => $user_id
                ];

                //echo '<pre>';print_r($finalData);die();
                //$url = $this->apiAdminUrl()."users/prefdrivecity";echo
                $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' => 10];
                    //$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']);
                            break;
                        case "vendor":
                            $this->redirect()->toRoute($usertype, ['action' => 'thanks']);
                            break;
                        case "guide":
                            $this->redirect()->toRoute($usertype, ['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;
    }
    
    
    public function serviceInfoAction() {
        $sessionUser = new Container('userlogin');
        $user_id = $sessionUser->userData['user_id'];
        if ($user_id != "") {
            $this->redirect()->toRoute('home');
        }
        $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');
        $userData = $this->registrationModel->getUserPersonalInfo($user_id);
        $userData = $userData['responsedata']['data'];
        //echo '<pre>';print_r($userData);//die();
        $mobile = $userData['mobile'];
        $first_name = $userData['first_name'];
        $email = $userData['email'];
        $referralBy = $userData['refer_by'];
        $referralCode = $userData['referral_key'];
        $username = $userData['username'];
        $password = $sessionContainer->password;
        $user_id = $userData['user_id'];
        $dataService = ['role_type_id'=>$userTypeId];
        //ServiceRegistrationForm:: $dutytype = $this->userModel->getPackageTypeList();
        ServiceRegistrationForm:: $dutytype = $this->userModel->getRoleServicesList($dataService);
        ServiceRegistrationForm:: $paymenttype = $this->userModel->getPaymentTypeList();
        ServiceRegistrationForm:: $langspeak = $this->userModel->getLanguageList();
        ServiceRegistrationForm:: $langwrite = $this->userModel->getLanguageList();
        ServiceRegistrationForm:: $shiftlogin = $this->userModel->getShiftLoginList();
        $dutyInfoForm = new ServiceRegistrationForm();
        $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,
                    'created_by' => $user_id
                ];

                //echo '<pre>';print_r($finalData);die();
                //$url = $this->apiAdminUrl()."users/prefdrivecity";echo
                $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' => 10];
                    //$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 "hotel-user":
                            $this->redirect()->toRoute($usertype, ['action' => 'thanks']);
                            break;
                        case "dmc-user":
                            $this->redirect()->toRoute($usertype, ['action' => 'thanks']);
                            break;
                        case "cruise-user":
                            $this->redirect()->toRoute($usertype, ['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   Ajax function
     * @return JsonModel
     * @message : For check user is exist or not in database.
     */
    public function checkAlreadyExistUserAction() {
        $request = $this->getRequest();
        if ($request->isPost()) {
            $fieldName = $request->getPost("id");
            $value = $request->getPost("value");
            $userTypeId = $request->getPost("userTypeId");
            if($fieldName=="username"){
            $url = $this->apiUrl() . "/user/verifyregister?username=" . $value;
            }else if($fieldName=="email"){
            $url = $this->apiUrl() . "/user/verifyregister?username=" . $value . "&user_type_id=" . $userTypeId;
            }else{
            $url = $this->apiUrl() . "/user/verifyregister?username=" . $value . "&user_type_id=" . $userTypeId;
            }

            $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[$fileName]['name'] != '') {
            $fileNameOfficeAdd = $_FILES[$fileName]['name'];
            $fileTmpNameOfficeAdd = $_FILES[$fileName]['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,'status'=>1];
            $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 $JsonData['responsedata'];
    }

    /**
     *
     * @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;
    }



    public function uploadfileAction() {
        $sessionuserData = new Container('userlogin');
        $userId = $sessionuserData->user_id;

        $postData = $this->getRequest()->getPost()->toArray();
        $fileName  = $postData['fileuploadname'];
        $edituserId    = isset($postData['userId'])?$postData['userId']:'';
        if($edituserId!=''){
          $userId = $edituserId;
        }

        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;//$_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,'status'=>1];
            $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 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;
    }
    
    
    /** @CreatedDate : 23-sep-20
     *  @CreatedBy   : Mohit Verma
     *  @Description : Api user registration for access api module.
     */
    public function apiUserAction(){
        $sessionUser = new Container('userlogin');
        $user_id = $sessionUser->userData['user_id'];
        if ($user_id != "") {
            $this->redirect()->toRoute('home');
        }
        $form = new LoginForm();
        $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];


        ApiUserForm::$countryprefix = $this->userModel->getCountryCodePrefix();
        ApiUserForm::$master_package = $this->commonModel->getPackageTypeList();
        ApiUserForm::$membershipackage = $this->licenseModel->getMembershipPackage();

        $loginDetailForm = new ApiUserForm();
        $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 = $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'];
                $company_name    =  $loginformData['company_name'];
                $company_address =  $loginformData['company_address'];
                $company_postal_code =  $loginformData['company_postal'];
                $company_website =  $loginformData['company_website'];

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

                                $finalData = [];
                                $finalData = [
                                    'company_id' => $this->config()->getConfig()->company->companyId,
                                    'first_name' => $first_name,
                                    'last_name' => $last_name,
                                    'email' => $email,
                                    'mobile_prefix' => $mobile_prefix,
                                    'mobile' => $contact_no,
                                    'user_type_id' => $userTypeId,
                                    'password' => $password,
                                    //'refer_by' => $refer_by,
                                    'nationality' => $nationality,
                                    'user_grade' => $this->config()->getConfig()->userGrade->defaultGrade,
                                    'signup_status' =>10, 
                                    'is_active' =>1 
                                ];
                                $finalData = array_filter($finalData);
                                $finalData['parent_id'] = 0;
                                $JsonData = $this->registrationModel->userNewSignup($finalData);
                                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;
                                        
                                        $companyData = [];
                                        $companyData = [
                                            'user_id' => $user_id,
                                            'company_name' => $company_name,
                                            'company_address' => $company_address,                                         
                                            'email' => $email,                                           
                                            'mobile_no' => $contact_no,                                          
                                            'country' => $nationality,
                                            'pincode' => $company_postal_code,                                           
                                            'added_by' => $user_id,                                            
                                            'website_url' => $company_website,                                            
                                            'created_date' => date('Y-m-d')                                            
                                        ];
                                                                            
                                        $url = $this->apiUrl() . "/company";
                                        $val = $this->post($url, $companyData);
                                        $JsonData = $val->getBody();               
                                        $JsonData = Json::decode($JsonData, true);  
                                        
                                        $adduserlicenseData = [
                                            'user_id'     => $user_id,
                                            'module'      =>  $loginformData['package_module'],
                                            'package'     =>  $loginformData['package'],
                                            'license_option' =>  $loginformData['license_option'],
                                            'created_by'  => $user_id,                                            
                                            'domain_name' => $company_website,
                                             'ip'         => $_SERVER['REMOTE_ADDR']
                                        ];
                                        
                                        $this->licenseModel->insertLicenseData($adduserlicenseData);
                                       
                                        $this->redirect()->toRoute($usertype, ['action' => 'thanks']);
                                    }
                                }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";
            }
        }
        
        $viewModel = new ViewModel(
                [
            'form' => $loginDetailForm,
            'loginform' => $form,
            'error_msg' => $msg
        ]);
        
        return $viewModel;
    }

}

//End class
