<?php

namespace User\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\JsonModel;
use Zend\Debug\Debug;
use Zend\View\Model\ViewModel;
use User\Form\{
    AddLoginForm,
    LoginForm,
    PopupRegistrationForm,
    ConfirmOtpForm,
    ConfirmLoginOtpForm,
    AddNewUserForm,
    AddNewUserHotelForm
};

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

class IndexController extends RestAPIClientController {

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

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

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

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

    /**
     *
     * @return ViewModel
     */
    /* public function loginActionOld() {
      $loginForm = new LoginForm();
      $request = $this->getRequest();
      //echo "niharika";die;

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

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

      if ($loginForm->isValid()) {

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

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


      if ($valide_mobile || $validate_email) {


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

      if ($valid) {

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

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

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

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

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

      return $viewModel;
      } */

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

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


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

      if ($request->isXmlHttpRequest()) {


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

      if ($loginForm->isValid()) {

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

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

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





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

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

      return $viewModel;
      } */

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


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

            if ($request->isXmlHttpRequest()) {


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

                if ($loginForm->isValid()) {

                    $post['password'] = ($post['password']);
                    $post['sms_send_status'] = "true";
                    $data = $this->userLogin($post);
                    //echo '<pre>';print_r($data);die();
                    if (isset($data['error']) && $data['error']) {
                        $errorMsg = $data['error'];
                        $result = ['status' => 'error1', 'msg' => $errorMsg];
                        $view = new JsonModel($result);
                        return $view;
                    } elseif ($data['status'] == 000) {
                        $result = ['status' => 'error1', 'msg' => $data['error']];
                        $view = new JsonModel($result);
                        return $view;
                    } else {
                        $userTypeArr = $this->config()->getConfig()->loginUserType;
                        $userTypeArr = $userTypeArr->toArray();
                        $user_type_id = $data['data']['user_type_id'];
                        if (in_array($user_type_id, $userTypeArr)) {
                            $sessionUser = new Container('confirmuserlogin');
                            $sessionUser->user_id = $data['data']['user_id'];
                            $user_id = $data['data']['user_id'];
                            $mobile = $data['data']['mobile'];
                            $first_name = $data['data']['first_name'];
                            $sessionUser->user_token = $data['data']['token'];

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

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

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


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

                            $result = ['status' => 'success'];
                        } else {
                            $result = ['status' => 'error1', 'msg' => 'Unauthorized-Access'];
                        }
                        $view = new JsonModel($result);
                        return $view;
                    }
                } else {

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

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

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

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

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

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

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

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

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

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

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

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


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

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

      if ($loginForm->isValid()) {

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

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

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

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

      return $viewModel;
      } */

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

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

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

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

    public function logoutAction() {
        $sessionUser = new Container('userlogin');
        $user_tokendata = $this->userToken();
        //echo'<pre>';print_r($user_tokendata);die();

        unset($sessionUser->userData);
        return $this->redirect()->toRoute('home');
    }

    public function userLogin($data) {
        //echo '<pre>';print_r($data);die();
        $val = [];

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

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

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

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

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


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

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

    /* @type : text */

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

    public function sendTxtMsg($paramData = array()) {
        $smsparam = ['template_name' => $paramData['template_name'], 'mobile' => $paramData['mobile'], 'user_name' => $paramData['user_name'], 'otp' => $paramData['otp']];
        //Debug::dump($smsparam); exit;
        $this->sendSMS($smsparam);
    }

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

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

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

                if (isset($data['error']) && $data['error']) {
                    //$errorMsg = $data['error'];
                    $errorMsg = "Invalid Username,Email,Mobile or password";
                } elseif ($data['status'] == 'false') {
                    //$errorMsg = $data['error'];
                    $errorMsg = "Invalid Username,Email,Mobile or password";
                } else {
                    $userTypeArr = $this->config()->getConfig()->loginUserType;
                    $alluserArr = $this->config()->getConfig()->userTypeId;
                    $userTypeArr = $userTypeArr->toArray();
                    $alluserArr = $alluserArr->toArray();
                    $user_type_id = $data['data']['user_type_id'];
                    $usertype = array_search($user_type_id, $alluserArr);
                    if (!in_array($user_type_id, $userTypeArr)) {
                        $sessionUser = new Container('userlogin');
                        $sessionUser->user_id = $data['data']['user_id'];
                        $sessionUser->user_token = $data['data']['token'];
                        $sessionUser->password = $post['password'];
                        $sessionUser->usertype = $usertype;
                        $sessionUser->mobile = $data['data']['mobile'];
                        $sessionUser->mobile_prefix = $data['data']['mobile_prefix'];
                        $sessionUser->first_name = $data['data']['first_name'];
                        $sessionUser->last_name = $data['data']['last_name'];
                        $sessionUser->email = $data['data']['email'];

                        $signup_status = $data['data']['signup_status'];
                        $is_active = $data['data']['is_active'];
                        $user_type_id = $data['data']['user_type_id'];
                        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) {
                            if ($user_type_id == 5) {
                                $this->redirect()->toRoute($usertype, ['action' => 'duty-info']);
                            } else {
                                $this->redirect()->toRoute($usertype, ['action' => 'vehicle-info']);
                            }
                        } else if ($signup_status == 5) {
                            $this->redirect()->toRoute($usertype, ['action' => 'duty-info']);
                        } else if ($signup_status > 0 && $signup_status == 10 && $is_active == 0) {
                            $errorMsg = 'Account is not active,Contact with admin';
                        } else if ($signup_status > 0 && $signup_status == 10 && $is_active == 1) {
                            $user_id = $data['data']['user_id'];
                            $url = $this->apiUrl() . "/user/userpersonalinfo?user_id=" . $user_id;
                            $resp = $this->get($url);
                            $response = Json::decode($resp->getBody(), true);
                            $sessionUser->userData = $response['responsedata']['data'];
                            $this->redirect()->toRoute('dashboard');
                        }
                    } else {
                        $errorMsg = 'Unauthorized-Access';
                    }
                }
            } else {
                //$msg=$form->getMessages();
                //echo '<pre>';print_r($msg);die();
            }
        }

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

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

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

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

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

            $bookingInfo['wallet_updated_amount'] = $walletAmt;
            //echo $walletAmt.'<br/>';
            //echo $paymentStatus.'<br/>';
            //echo $walletStatus.'<br/>';
            //echo $post['booking_amt_paid'];
            //Debug::dump($post);
            $finalData = [];
            $finalData = array_merge($bookingInfo, $post);
            //Debug::dump($finalData);
            //exit;
            //$finalBooking = $this->finalBookingSubmission($finalData);
            //$lastInsertId = $finalBooking['data']['response']['insertId'];
            $companyInitial = $this->config()->getConfig()->company->companyInitial;
            //$finalData['booking_id'] = $lastInsertId;
            //Debug::dump($finalData);
            //exit;

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

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



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

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

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

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

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

    public function userBookingUpdate($data) {
        $url = $this->apiUrl() . "/booking/getBookingAmtBalance?booking_id=" . $data['booking_id'];
        $resp = $this->get($url);
        $response = Json::decode($resp->getBody(), true);
        if ($response['responsedata']['status'] == "success") {
            if ($data['booking_amt_percentage'] != '100') {
                $booking_amt_percentage = $response['responsedata']['data']['booking_amt_percentage'] + $data['booking_amt_percentage'];
                $booking_amt_paid = $response['responsedata']['data']['booking_amt_paid'] + $data['booking_amt_paid'];
                $booking_amt_balance = $response['responsedata']['data']['booking_amt_balance'] - $data['booking_amt_paid'];
            } else {
                $booking_amt_percentage = $data['booking_amt_percentage'];
                $booking_amt_paid = $data['estimated_final_price'];
                $booking_amt_balance = 0;
            }
            $data1 = [
                'booking_id' => $data['booking_id'],
                'booking_amt_percentage' => $booking_amt_percentage,
                'booking_amt_paid' => $booking_amt_paid,
                'booking_amt_balance' => $booking_amt_balance
            ];

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

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

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

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

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

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

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

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

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

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

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

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

    /** @Description  : API User Login
     *  @createdDate  : 25-Sep-2020
     *  @createdBY    : Mohit Verma
     *  */
    public function apiUserLoginAction() {
        $sessionUser = new Container('userlogin');
        $user_id = $sessionUser->userData['user_id'];
        if ($user_id != "") {
            $this->redirect()->toRoute('dashboard');
        }
        $errorMsg = "";
        $captchaerror = '';
        $form = new LoginForm();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $form->setData($request->getPost());
            if ($post['g-recaptcha-response'] == '') {
                $captchaerror = 'Please check the captcha';
            }
            //$form->getInputFilter()->get('user_type_id')->setRequired(false);
            if ($form->isValid() && $captchaerror == '') {
                $post['password'] = ($post['password']);
                $post['ip'] = $_SERVER['REMOTE_ADDR'];
                $post['sms_send_status'] = "false";
                $data = $this->userLogin($post);
                //echo '<pre>';print_r($data);die();

                if (isset($data['error']) && $data['error']) {
                    //$errorMsg = $data['error'];
                    $errorMsg = "Invalid Username,Email,Mobile or password";
                } elseif ($data['status'] == 'false') {
                    //$errorMsg = $data['error'];
                    $errorMsg = "Invalid Username,Email,Mobile or password";
                } else {
                    $userTypeArr = $this->config()->getConfig()->loginUserType;
                    $alluserArr = $this->config()->getConfig()->userTypeId;
                    $userTypeArr = $userTypeArr->toArray();
                    $alluserArr = $alluserArr->toArray();
                    $user_type_id = $data['data']['user_type_id'];
                    $usertype = array_search($user_type_id, $alluserArr);
                    if (!in_array($user_type_id, $userTypeArr)) {
                        $sessionUser = new Container('userlogin');
                        $sessionUser->user_id = $data['data']['user_id'];
                        $sessionUser->user_token = $data['data']['token'];
                        $sessionUser->password = $post['password'];
                        $sessionUser->usertype = $usertype;
                        $sessionUser->mobile = $data['data']['mobile'];
                        $sessionUser->mobile_prefix = $data['data']['mobile_prefix'];
                        $sessionUser->first_name = $data['data']['first_name'];
                        $sessionUser->last_name = $data['data']['last_name'];
                        $sessionUser->email = $data['data']['email'];

                        $signup_status = $data['data']['signup_status'];
                        $is_active = $data['data']['is_active'];
                        $user_type_id = $data['data']['user_type_id'];
                        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) {
                            if ($user_type_id == 5) {
                                $this->redirect()->toRoute($usertype, ['action' => 'duty-info']);
                            } else {
                                $this->redirect()->toRoute($usertype, ['action' => 'vehicle-info']);
                            }
                        } else if ($signup_status == 5) {
                            $this->redirect()->toRoute($usertype, ['action' => 'duty-info']);
                        } else if ($signup_status > 0 && $signup_status == 10 && $is_active == 0) {
                            $errorMsg = 'Account is not active,Contact with admin';
                        } else if ($signup_status > 0 && $signup_status == 10 && $is_active == 1) {
                            $user_id = $data['data']['user_id'];
                            $url = $this->apiUrl() . "/user/userpersonalinfo?user_id=" . $user_id;
                            $resp = $this->get($url);
                            $response = Json::decode($resp->getBody(), true);
                            $sessionUser->userData = $response['responsedata']['data'];
                            if ($user_type_id == 9) {
                                $this->redirect()->toRoute('api');
                            } else {
                                $this->redirect()->toRoute('dashboard');
                            }
                        }
                    } else {
                        $errorMsg = 'Unauthorized-Access';
                    }
                }
            } else {
                //$msg=$form->getMessages();
                //echo '<pre>';print_r($msg);die();
            }
        }

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

    public function loginUserAction() {
        $request = $this->getRequest();
        /////////////////
        if ($request->isPost()) {
            $result = [];
            if ($request->isXmlHttpRequest()) {
                $post = $request->getPost()->toArray();
                $user_id = $post['user_id'];
                $username = $post['username'];
                $mobile = $post['mobile'];
                $email = $post['email'];
                if (!empty($user_id)) {
                    $sessionAddUserContainer = new Container('addUserData');
                    $sessionAddUserContainer->user_id = $user_id;
                    $sessionAddUserContainer->user_name = $username;
                    $sessionAddUserContainer->mobile = $mobile;
                    $sessionAddUserContainer->email = $email;                        
                    $result = ['status' => 'success'];
                    $view = new JsonModel($result);
                    return $view;
                } else {
                    $result = ['status' => 'error'];
                    $view = new JsonModel($result);
                    return $view;
                }
            }
        }

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

    public function removeUserAction() {
        $request = $this->getRequest();
        /////////////////
        if ($request->isPost()) {
            $result = [];
            if ($request->isXmlHttpRequest()) {
                $post = $request->getPost()->toArray();
                $sessionAddUserContainer = new Container('addUserData');
                unset($sessionAddUserContainer->user_id);
                unset($sessionAddUserContainer->user_name);
                unset($sessionAddUserContainer->mobile);
                unset($sessionAddUserContainer->email);
                $result = ['status' => 'success'];
                $view = new JsonModel($result);
                return $view;
            }
        }

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

    public function getUserListAction() {
        $request = $this->getRequest();
        $postdata = $request->getPost();
        $term = trim($postdata['term']);
        if ( preg_match('/\s/',$term) ){
        $term = explode(' ',$term);
        $val = '{"where":{ "and" :[{"first_name":{"like": "' . $term[0] . '%"}},{"last_name": {"like": "' . $term[1] . '%"}}]},"limit":15}';
        }else{
        $val = '{"where":{ "and" :[{"first_name":{"like": "' . $term. '%"}}]},"limit":15}';
        }        
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/user?filter=" . $val;
        $resp = $this->get($url);
        $driverJsonData = Json::decode($resp->getBody(), true);
        if (!empty($driverJsonData)) {
            foreach ($driverJsonData as $value) {
                $data[] = [
                    "label" => $value['first_name'].' '.$value['last_name'].' '.$value['mobile'].', '.$value['email'],
                    "value" => $value['id'],
                    "mobile" => $value['mobile'],
                    "email" => $value['email'],
                    "name" => $value['first_name'].' '.$value['last_name']
                ];
            }
        } else {
            $data[] = ["label" => 'Not Exist'];
        }
        $view = new JsonModel($data);
        return $view;
    }
    
    public function addNewUserAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];
        AddNewUserForm::$usertype = $this->userModel->getUserTypeList();
        AddNewUserForm::$countryprefix = $this->userModel->getCountryCodePrefix();
        $form = new AddNewUserForm();       
        $viewModel = new ViewModel(['form' => $form]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }
    
    public function addNewHotelUserAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];
        $data = ['role_type_id'=>14];
        AddNewUserHotelForm::$usertype = $this->userModel->getUserTypeList();
        AddNewUserHotelForm::$countryprefix = $this->userModel->getCountryCodePrefix();
        AddNewUserHotelForm::$dutytype = $this->userModel->getRoleServicesList($data);
        $form = new AddNewUserHotelForm();       
        $viewModel = new ViewModel(['form' => $form]);
        $viewModel->setTerminal(true);
        return $viewModel;
    }
    
    public function addUserAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];
        $viewModel = new ViewModel();
        $request = $this->getRequest();
        $form = new AddNewUserForm();
        $msg = '';
        if ($request->isXmlHttpRequest()) {
            $postdata = $request->getPost()->toArray();
            $form->setData($postdata);
            if ($form->isValid()) {               
                $data = [
                    'user_type_id' => $postdata['user_type'],
                    'company_id' => $this->config()->getConfig()->company->companyId,
                    'firstName' => trim($postdata['first_name']),
                    'lastName' => trim($postdata['last_name']),
                    'email' => trim($postdata['email']),
                    'prefix_contact_no' => trim($postdata['prefix_contact_no']),
                    'mobile' => trim($postdata['contact_no']),
                    'password' => md5($postdata['contact_no']),                    
                    'parent_id' => $user_id,
                    'gender' => trim($postdata['gender']),
                    'created_by' => $user_id,
                    'nationality' => trim($postdata['nationality_value']),
                    'signup_status' => 10,
                    'user_grade' => $this->config()->getConfig()->userGrade->defaultGrade,
                    'created_date' => date('Y-m-d h:i:s')
                ];
                $resp = $this->userModel->addNewUser($data);
                //var_dump($resp); die
                
                if($resp['responsedata']['status'] == true) {     
                    
                    $finalData1 = [
                        'user_id' => $resp['responsedata']['user_id'],
                        'company_name' => $postData['company_name'],
                        'added_by' => $user_id,
                        'created_date' => date('Y-m-d H:i:s'),
                    ];
                    
                    $url1 = $this->apiUrl() . "/company";
                    $val1 = $this->post($url1, $finalData1);
                    $JsonData1 = $val1->getBody();               
                    $JsonData1 = Json::decode($JsonData1, true); 
                    
                    $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']);
                    
                    
                    $finalData2 = [
                        '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('Y-m-d'),
                        'created_by' => $user_id
                    ];

                    $url2 = $this->apiUrl() . "/user/addDutyDetail";
                    $val2 = $this->post($url2, $finalData2);
                    $JsonData2 = $val2->getBody();
                    $JsonData2 = Json::decode($JsonData2, true);
                    
                    $url = $this->apiUrl() . "/user/userpersonalinfo?user_id=" . $resp['responsedata']['user_id'];
                    $val = $this->get($url);
                    $JsonData = $val->getBody();
                    $JsonData = Json::decode($JsonData, true);
                    $userData = $JsonData['responsedata']['data'];
                    $sessionAddUserContainer = new Container('addUserData');
                    $sessionAddUserContainer->user_id = $resp['responsedata']['user_id'];
                    $sessionAddUserContainer->user_name = $userData['first_name'].' '.$userData['last_name'];
                    $sessionAddUserContainer->mobile = $userData['mobile'];
                    $sessionAddUserContainer->email = $userData['email'];            
                    $status = true;
                    $msg = $resp['responsedata']['message'];
                }else{
                    $status = false;
                    $msg = $resp['responsedata']['message'];
                }
                $result = ['result' => $status, 'currentUrlRedirect'=>'Z', 'message' => $msg];
            } else {
                $result = ['result' => false, 'message' => $form->getMessages()];
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }
    }
    
    public function addUsersAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];
        $viewModel = new ViewModel();
        $request = $this->getRequest();
        $form = new AddNewUserHotelForm();
        $msg = '';
        if ($request->isXmlHttpRequest()) {
            $postdata = $request->getPost()->toArray();
            $form->setData($postdata);
            if ($form->isValid()) {               
                $data = [
                    'user_type_id' => $postdata['user_type'],
                    'company_id' => $this->config()->getConfig()->company->companyId,
                    'firstName' => trim($postdata['first_name']),
                    'lastName' => trim($postdata['last_name']),
                    'email' => trim($postdata['email']),
                    'prefix_contact_no' => trim($postdata['prefix_contact_no']),
                    'mobile' => trim($postdata['contact_no']),
                    'password' => md5($postdata['contact_no']),                    
                    'parent_id' => $user_id,
                    'gender' => trim($postdata['gender']),
                    'created_by' => $user_id,
                    'nationality' => trim($postdata['nationality_value']),
                    'signup_status' => 10,
                    'user_grade' => $this->config()->getConfig()->userGrade->defaultGrade,
                    'created_date' => date('Y-m-d h:i:s')
                ];
                $resp = $this->userModel->addNewUser($data);
                
                if($resp['responsedata']['status'] == true) {                              
                    $status = true;
                    $msg = $resp['responsedata']['message'];
                }else{
                    $status = false;
                    $msg = $resp['responsedata']['message'];
                }
                $result = ['result' => $status, 'currentUrlRedirect'=>'Z', 'message' => $msg];
            } else {
                $result = ['result' => false, 'message' => $form->getMessages()];
            }
            if (!$viewModel instanceof JsonModel && $request->isXmlHttpRequest()) {
                $viewModel = new JsonModel();
            }
            $viewModel->setVariables(['data' => $result]);
            return $viewModel;
        }
    }
    
    
    /**
     * Get Services List
     * @return JSON
     */
    public function getUserServicesAction() {
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $data = [];
        $postData = $this->getRequest()->getPost();
        $user_type = $postData['user_type'];
        $data = [
            'role_type_id' => $user_type,
        ];
        $url = $this->apiUrl() . "/user-role-vendor/getCategoryServicesList";
        $resp = $this->post($url, $data);
        $userJsonData = Json::decode($resp->getBody(), true);
        //echo '<pre>';print_r($userJsonData['responsedata']);die();
        if ($userJsonData['responsedata']['status']=="success") {
            foreach ($userJsonData['responsedata']['data'] as $value) {
                $data1[] = ["id" => $value['id'], "name" => $value['service_name']];
            }
            $response = ["status" => true, "data" => $data1];
        } else {
            $response = ["status" => false];
        }
        //var_dump($response); die;
        $view = new JsonModel($response);
        return $view;
    }

}
