<?php

namespace Dashboard\Controller;

use Application\Controller\RestAPIClientController;
use Dashboard\Form\{
    UserManagementSearchForm,
    UserManagementLoginForm,
    UserPersonalManagementFormFilter,
    ProfilePersonalForm,
    ProfileCompanyDetailForm,
    ProfileChangePasswordForm,
    ProfileBankDetailForm,
    ProfileCreditRequestForm,
    ProfileDutyDetailForm,
    ProfileLicenseDetailForm,
    ProfileOtherDetailForm,
    ProfileVehicleDetailForm,
    DataSearchForm
};
use Zend\View\Model\{
    ViewModel,
    JsonModel
};
use Zend\Validator\File\Size;
use Zend\Json\Json;
use Zend\Debug\Debug;
use Zend\Session\Container;
use Dashboard\Model\User;
use Dashboard\Model\CommonModel;
use Dashboard\Model\Vehicle;

class UserManagementController extends RestAPIClientController {

    public function __construct() {
        $this->userModel = new User();
        $this->commonModel = new CommonModel();
        $this->vehicleModel = new Vehicle();
    }

    private $owned = 1;
    private $attached = 2;

    /**
     * User Management Home
     * @return ViewModel
     */
    public function indexAction() {

        $relationManagerData = [];
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];
        $roleTypeName = $this->config()->getConfig()->userRoleType->staff;
        $roleTypeData = $this->userModel->getUserRoleType($roleTypeName);
        $roleTypeData = $this->userModel->getAllUserRoleType($roleTypeData);
        $user_type_id = $roleTypeData;
        if ($user_id != '') {
            $data = array('user_id' => $user_id, 'user_type_id' => $user_type_id);
            $resposne = $this->userModel->getUserStaff($data);

            if ($resposne['responsedata']['status']=="success") {
                $relationManagerData = $resposne['responsedata']['data'];
            }
        }

        $data = [];
        $userTypedata = [];
        $user_type = 'User';
        $roleType = $this->config()->getConfig()->userRoleType->user;
        UserManagementSearchForm::$country = $this->userModel->getCountryList();
        $userTypedata = $this->userModel->getUserTypeList($roleType);

        $userTypeDatares = array_diff($userTypedata, ['Driver', 'Vendor']);
        $userTypeDatares[2] = 'Un-register User (Client)';
        $userTypeDatares[7] = 'Travel Agent';
        $userStatus = $this->driverStatus();

        UserManagementSearchForm::$usertype = $userTypeDatares;
        UserManagementSearchForm::$usertype_status = $userStatus['data'];

        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];
        $user_type_id = $loginData['user_type_id'];

        $request = $this->getRequest();
        $form = new UserManagementSearchForm();


        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $form->setData($request->getPost());
            if (!empty($post['search_user'])) {
                $data = [
                    'user_id' => $post['user_id'],
                    'first_name' => $post['name'],
                    'mobile' => $post['mobile_number'],
                    'email' => $post['email'],
                    'country_id' => $post['country_id'],
                    'state_id' => $post['state_id'],
                    'city_id' => $post['city_id'],
                    'user_type_id' => $post['user_type'],
                    'status' => $post['user_type_status']
                ];
                $data = array_filter($data);
            }
        } else {
            $data['user_type_id'] = '1,2,5,6,7,8';
        }
        $data['parent_id'] = ($user_type_id != 10) ? $user_id : 0;
        $data['company_id'] = $this->config()->getConfig()->company->companyId;
        //echo '<pre>';print_r($data);die();
        $userListing = $this->userModel->getUserList($data);
        $userStatus_keys = [1, 6, 7];
        $user_type_status = $this->userModel->getUserTypeList($userStatus_keys);
        $user_type_status[2] = 'Un-register User';

        $viewModel = new ViewModel(['form' => $form, 'userListing' => $userListing['data']['responsedata'], 'action' => 'index', 'userstatus' => $userStatus, 'user_type' => $user_type, 'relatinaldata' => $relationManagerData, 'user_type_status' => $user_type_status, 'userTypeKeyId' => $userStatus_keys]);
        return $viewModel;
    }

   /**
     * Add User Login Page
     * @return ViewModel
     */
    public function addAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];

        $request = $this->getRequest();
        $roleType = $this->config()->getConfig()->userRoleType->user;
        UserManagementLoginForm::$usertype = $this->userModel->getUserTypeList($roleType);
        UserManagementLoginForm::$countryprefix = $this->userModel->getCountryCodePrefix();
        $form = new UserManagementLoginForm();

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

            $sessionContainer = new Container('userlogindetail');
            $loginData = $this->getRequest()->getPost();
            $sessionContainer->loginData = $loginData;
            //echo '<pre>';print_r($loginData);die();

            if ($form->isValid()) {
                /*if (ctype_digit($loginData['login_id'])) {
                    $mobile = $loginData['login_id'];
                    $email = "";
                } else {
                    $email = $loginData['login_id'];
                    $mobile = "";
                }

                if ($loginData['password'] != "") {
                    $password = md5($loginData['password']);
                } else {
                    $rand = substr(rand(), 0, 6);
                    $password = md5($rand);
                }*/
                $data = [
                    'user_type_id' => $loginData['user_type'],
                    'company_id' => $this->config()->getConfig()->company->companyId,
                    'firstName' => trim($loginData['first_name']),
                    'lastName' => trim($loginData['last_name']),
                    'email' => trim($loginData['email']),
                    'prefix_contact_no' => trim($loginData['prefix_contact_no']),
                    'mobile' => trim($loginData['contact_no']),
                    'password' => $loginData['password'],
                    'parent_id' => $user_id,
                    'gender' => trim($loginData['gender']),
                    'created_by' => $user_id,
                    'nationality' => trim($loginData['nationality_value']),
                    'signup_status' => 10,
                    'user_grade' => $this->config()->getConfig()->userGrade->defaultGrade,
                    'created_date' => date('Y-m-d h:i:s')
                ];
                //echo '<pre>';print_r($data);die();
                $userType = $loginData['user_type'];
                $resp = $this->userModel->addNewUser($data);
                //echo '<pre>';print_r($resp);die();
                if ($resp['responsedata'] == true) {
                    $action = 'index';
                    if ($userType == 1 || $userType == 5 || $userType == 6) {
                        $action = 'index';
                    }
                    if ($userType == 2 || $userType == 4) {
                        $action = 'vendor';
                    }
                    if ($userType == 3) {
                        $action = 'driver';
                    }

                    $this->redirect()->toRoute('usermanagement', ['action' => $action]);
                }
            }
        }

        $viewModel = new ViewModel(['form' => $form]);
        return $viewModel;
    }
    
     /**
     * Add User Login Page
     * @return ViewModel
     */
    public function addVendorAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];

        $request = $this->getRequest();
        $roleType = $this->config()->getConfig()->userRoleType->vendor;
        UserManagementLoginForm::$usertype = $this->userModel->getUserTypeList($roleType);
        UserManagementLoginForm::$countryprefix = $this->userModel->getCountryCodePrefix();
        $form = new UserManagementLoginForm();

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

            $sessionContainer = new Container('userlogindetail');
            $loginData = $this->getRequest()->getPost();
            $sessionContainer->loginData = $loginData;
            //echo '<pre>';print_r($loginData);die();

            if ($form->isValid()) {
                /*if (ctype_digit($loginData['login_id'])) {
                    $mobile = $loginData['login_id'];
                    $email = "";
                } else {
                    $email = $loginData['login_id'];
                    $mobile = "";
                }

                if ($loginData['password'] != "") {
                    $password = md5($loginData['password']);
                } else {
                    $rand = substr(rand(), 0, 6);
                    $password = md5($rand);
                }*/
                $data = [
                    'user_type_id' => $loginData['user_type'],
                    'company_id' => $this->config()->getConfig()->company->companyId,
                    'firstName' => trim($loginData['first_name']),
                    'lastName' => trim($loginData['last_name']),
                    'email' => trim($loginData['email']),
                    'prefix_contact_no' => trim($loginData['prefix_contact_no']),
                    'mobile' => trim($loginData['contact_no']),
                    'password' => $loginData['password'],
                    'parent_id' => $user_id,
                    'gender' => trim($loginData['gender']),
                    'created_by' => $user_id,
                    'nationality' => trim($loginData['nationality_value']),
                    'signup_status' => 10,
                    'user_grade' => $this->config()->getConfig()->userGrade->defaultGrade,
                    'created_date' => date('Y-m-d h:i:s')
                ];
                //echo '<pre>';print_r($data);die();
                $userType = $loginData['user_type'];
                $resp = $this->userModel->addNewUser($data);
                //echo '<pre>';print_r($resp);die();
                if ($resp['responsedata'] == true) {
                    $action = 'index';
                    if ($userType == 1 || $userType == 5 || $userType == 6) {
                        $action = 'index';
                    }
                    if ($userType == 2 || $userType == 4) {
                        $action = 'vendor';
                    }
                    if ($userType == 3) {
                        $action = 'driver';
                    }

                    $this->redirect()->toRoute('usermanagement', ['action' => $action]);
                }
            }
        }

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

    /**
     * Add User Detail...
     * @return ViewModel
     */
    public function addUserDetailAction() {
        //echo 'raza';die;
        $sessionuserData = new Container('userlogindetail');
        $loginData = $sessionuserData->loginData;
        $username = $loginData['login_id'];
        $request = $this->getRequest();
        ProfilePersonalForm:: $kyctype = $this->getKycTypeList();
        $form = new ProfilePersonalForm();
        $form->get('email')->setAttribute('readonly', '');
        $form->get('mobile')->setAttribute('readonly', '');
        $form->get('first_name')->setValue($loginData['first_name']);
        $form->get('last_name')->setValue($loginData['last_name']);
        if (ctype_digit($username)) {
            $form->get('mobile')->setValue($username);
            $form->get('mobile')->setAttribute('readonly', 'true');
        } else {
            $form->get('email')->setValue($username);
            $form->get('email')->setAttribute('readonly', 'true');
        }

        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $mergeData = array_merge_recursive(
                    $this->getRequest()->getPost()->toArray(), $this->getRequest()->getFiles()->toArray()
            );



            $form->setData($mergeData);
            $userPersonalFilter = new UserPersonalManagementFormFilter();
            $form->setInputFilter($userPersonalFilter);

            if ($form->isValid()) {
                $postData = $mergeData;
                //file start
                $fileNameKycProof = $postData['kyc_upload']['name'];
                $fileTmpNameKycProof = $postData['kyc_upload']['tmp_name'];
                $kycProofImageName = date("d-m-Y") . "-" . time() . $fileNameKycProof;
                //$targetpath = EMAIL_IMAGE_PATH.$filename;
                $targetPath = "public/upload/profile/kyc/" . $kycProofImageName;
                move_uploaded_file($fileTmpNameKycProof, $targetPath);
                //file end

                $finalData = [];
                $finalData = [
                    'first_name' => $postData['first_name'],
                    'last_name' => $postData['last_name'],
                    'father_name' => $postData['father_name'],
                    'email' => $postData['email'],
                    'email_verified' => $postData['email_verified'],
                    'mobile_number' => $postData['mobile_number'],
                    'phone_number' => $postData['phone_number'],
                    'phone_number_verified' => $postData['phone_number_verified'],
                    'external_reference' => $postData['external_reference'],
                    'dob' => $postData['dob'],
                    'gender' => $postData['gender'],
                    'address' => $postData['address'],
                    'state_id' => $postData['state_value'],
                    'city_id' => $postData['city_value'],
                    'kyc' => $postData['kyc'],
                    'kyc_upload' => $kycProofImageName,
                    'pincode' => $postData['pincode'],
                    'company_name' => $postData['company_name'],
                    'login_id' => $postData['login_id'],
                    'password' => $postData['password']
                ];
                $jsonData = json_encode($finalData);
                \Zend\Debug\Debug::dump($jsonData);
                die();
                //$this->redirect()->toRoute('usermanagement', ['action' => 'index']);
            }
        }

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

    /**
     * Edit User Detail...
     * @return ViewModel
     */
    public function editUserDetailAction() {
        //echo 'raza';die;
        $request = $this->getRequest();
        $form = new ProfilePersonalForm();
        $userId = $this->params()->fromRoute('id');
        //call api here...
        $userDetail = [
            'first_name' => 'amir',
            'last_name' => 'raza',
            'father_name' => 'n hoda',
            'email' => 'amirraza278@gmail.com',
            'email_verified' => '1',
            'mobile_number' => '9654148220',
            'phone_number' => '47474747',
            'phone_number_verified' => '1',
            'external_reference' => 'mohit jain',
            'dob' => '1994-06-28',
            'gender' => 'male',
            'address' => 'nizamuddin',
            'state_name' => 'Delhi',
            'state_value' => '1',
            'city_name' => 'New Delhi',
            'city_value' => '2',
            'kyc' => 'KJ65FV',
            'kyc_upload' => '',
            'pincode' => '100006',
            'company_name' => 'Hello42'
        ];
        $form->setData($userDetail);

        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $mergeData = array_merge_recursive(
                    $this->getRequest()->getPost()->toArray(), $this->getRequest()->getFiles()->toArray()
            );


            $form->setData($mergeData);
            $userPersonalFilter = new UserPersonalManagementFormFilter();
            $form->setInputFilter($userPersonalFilter);

            if ($form->isValid()) {
                $postData = $mergeData;
                //file start
                $fileNameKycProof = $postData['kyc_upload']['name'];
                $fileTmpNameKycProof = $postData['kyc_upload']['tmp_name'];
                $kycProofImageName = date("d-m-Y") . "-" . time() . $fileNameKycProof;
                //$targetpath = EMAIL_IMAGE_PATH.$filename;
                $targetPath = "public/upload/profile/kyc/" . $kycProofImageName;
                move_uploaded_file($fileTmpNameKycProof, $targetPath);
                //file end

                $finalData = [];
                $finalData = [
                    'first_name' => $postData['first_name'],
                    'last_name' => $postData['last_name'],
                    'father_name' => $postData['father_name'],
                    'email' => $postData['email'],
                    'email_verified' => $postData['email_verified'],
                    'mobile_number' => $postData['mobile_number'],
                    'phone_number' => $postData['phone_number'],
                    'phone_number_verified' => $postData['phone_number_verified'],
                    'external_reference' => $postData['external_reference'],
                    'dob' => $postData['dob'],
                    'gender' => $postData['gender'],
                    'address' => $postData['address'],
                    'state_id' => $postData['state_value'],
                    'city_id' => $postData['city_value'],
                    'kyc' => $postData['kyc'],
                    'kyc_upload' => $kycProofImageName,
                    'pincode' => $postData['pincode'],
                    'company_name' => $postData['company_name'],
                    'login_id' => $postData['login_id'],
                    'password' => $postData['password']
                ];
                $jsonData = json_encode($finalData);
                \Zend\Debug\Debug::dump($jsonData);
                die();
                //$this->redirect()->toRoute('usermanagement', ['action' => 'index']);
            }
        }

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

    /**
     * Driver Listing
     * @return ViewModel
     */
    public function driverAction() {
        $user_type = 'Driver';
        $relationManagerData = [];
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];
        $roleTypeName = $this->config()->getConfig()->userRoleType->staff;
        $roleTypeData = $this->userModel->getUserRoleType($roleTypeName);
        $roleTypeData = $this->userModel->getAllUserRoleType($roleTypeData);
        $user_type_id = $roleTypeData;
        if ($user_id != '') {
            $data = array('user_id' => $user_id, 'user_type_id' => $user_type_id);
            $resposne = $this->userModel->getUserStaff($data);

            if ($resposne['responsedata']['status']=="success") {
                $relationManagerData = $resposne['responsedata']['data'];
            }
        }

        $data = [];
        $driverStatus = $this->driverStatus();
        UserManagementSearchForm::$country = $this->userModel->getCountryList();
        UserManagementSearchForm::$usertype = $this->userModel->getUserTypeList();
        UserManagementSearchForm::$usertype_status = $driverStatus['data'];

        $request = $this->getRequest();
        $form = new UserManagementSearchForm();

        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $form->setData($request->getPost());
            if (!empty($post['search_user'])) {
                $data = [
                    'user_id' => $post['user_id'],
                    'first_name' => $post['name'],
                    'mobile' => $post['mobile_number'],
                    'email' => $post['email'],
                    'country_id' => $post['country_id'],
                    'state_id' => $post['state_id'],
                    'city_id' => $post['city_id'],
                    //'user_type_id' => $post['user_type'],
                    'status' => $post['user_type_status']
                ];
                $data = array_filter($data);
            }
        }
        $data['vendor_id'] = ($user_type_id != 10) ? $user_id : 0;
        $data['user_type_id'] = '3';
        $data['company_id'] = $this->config()->getConfig()->company->companyId;
        //echo '<pre>';print_r($data);die();
        $userListing = $this->userModel->getDriverList($data);
        $userStatus_keys = [3, 4];
        $user_type_status = $this->userModel->getUserTypeList($userStatus_keys);

        $viewModel = new ViewModel(['form' => $form, 'userListing' => $userListing['data']['responsedata'], 'action' => 'driver', 'driverStatus' => $driverStatus, 'user_type' => $user_type, 'relatinaldata' => $relationManagerData, 'user_type_status' => $user_type_status]);
        return $viewModel;
    }

    /**
     * Vendor Listing
     * @return ViewModel
     */
    public function vendorAction() {
        $user_type = 'Vendor';
        $relationManagerData = [];
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];
        $roleTypeName = $this->config()->getConfig()->userRoleType->staff;
        $roleTypeData = $this->userModel->getUserRoleType($roleTypeName);
        $roleTypeData = $this->userModel->getAllUserRoleType($roleTypeData);
        $user_type_id = $roleTypeData;
        if ($user_id != '') {
            $data = array('user_id' => $user_id, 'user_type_id' => $user_type_id);
            $resposne = $this->userModel->getUserStaff($data);

            if ($resposne['responsedata']['status']=="success") {
                $relationManagerData = $resposne['responsedata']['data'];
            }
        }

        $data = [];
        $vendorStatus = $this->driverStatus();
        UserManagementSearchForm::$country = $this->userModel->getCountryList();
        UserManagementSearchForm::$usertype = $this->userModel->getUserTypeList();
        UserManagementSearchForm::$usertype_status = $vendorStatus['data'];
        $request = $this->getRequest();
        $form = new UserManagementSearchForm();
        if ($request->isPost()) {
            $post = $request->getPost()->toArray();
            $form->setData($request->getPost());
            if (!empty($post['search_user'])) {
                //Debug::dump($post); exit;
                $data = [
                    'user_id' => $post['user_id'],
                    'first_name' => $post['name'],
                    'mobile' => $post['mobile_number'],
                    'email' => $post['email'],
                    'country_id' => $post['country_id'],
                    'state_id' => $post['state_id'],
                    'city_id' => $post['city_id'],
                    //'user_type_id' => $post['user_type']
                    'status' => $post['user_type_status']
                ];
                $data = array_filter($data);
            }
        }
        $data['parent_id'] = ($user_type_id != 10) ? $user_id : 0;
        $data['user_type_id'] = '4';
        $data['company_id'] = $this->config()->getConfig()->company->companyId;
        $userListing = $this->userModel->getUserList($data);
        $userStatus_keys = [3, 4];
        $user_type_status = $this->userModel->getUserTypeList($userStatus_keys);
        //echo'<pre>';print_r($userListing);die();
        $viewModel = new ViewModel(['form' => $form, 'userListing' => $userListing['data']['responsedata'], 'action' => 'vendor', 'vendorStatus' => $vendorStatus, 'user_type' => $user_type, 'relatinaldata' => $relationManagerData, 'user_type_status' => $user_type_status]);
        return $viewModel;
    }

    /**
     * Personal Detail
     * @return ViewModel
     */
    public function personalDetailAction() {
        $msg = "";
        $msg_class = "";
        $refer_by = "";
        $referral_key = "";
        $email_verified = "";
        $phone_verified = "";
        $id = "";
        $userTypeId = '';
        $usertypelist = $this->userModel->getUserTypeList();

        $request = $this->getRequest();
        ProfilePersonalForm:: $kyctype = $this->userModel->getKycTypeList();


        if (intval($this->params('id'))) {
            $id = intval($this->params('id'));

            $userTypeId = $this->userModel->getUserType($id);
            $userTypedata = $this->userModel->getUserTypeList();

            $user_Type_keys = [3, 4];
            if (in_array($userTypeId, $user_Type_keys)) {
                $userTypedata = array_intersect_key($userTypedata, array_flip($user_Type_keys));
            } else {
                $userTypedata = array_diff($userTypedata, ['Driver', 'Vendor']);
                $userTypedata[2] = 'Un-register User (Client)';
                $userTypedata[7] = 'Travel Agent';
            }
            ProfilePersonalForm:: $usertype = $userTypedata;
        }


        $form = new ProfilePersonalForm();
        $form->get('kyc_upload')->setAttribute('data-id',$id);

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

            //echo'<pre>';print_r($JsonData);die();
            if ($JsonData['responsedata']['status'] == 'success') {
                $userDetails = $JsonData['responsedata']['data'];
                $dob = date('d/m/Y', strtotime($userDetails['dob']));
                $userDetails['dob'] = $dob;
                $userDetails['mobile'] = $userDetails['mobile_prefix'] . ' - ' . $userDetails['mobile'];

                $referral_key = $userDetails['referral_key'];
                $refer_by = $userDetails['refer_by'];

                $email_verified = ($userDetails['email_verified'] == 0) ? 'Un-Verified' : 'Verified';
                $phone_verified = ($userDetails['phone_verified'] == 0) ? 'Un-Verified' : 'Verified';

                $form->setData($userDetails);
                $form->get('state_value')->setValue($userDetails['state_id']);
                $form->get('city_value')->setValue($userDetails['city_id']);
                if ($userDetails['email'] != "") {
                    $form->get('email')->setAttribute('readonly', 'true');
                }if ($userDetails['mobile'] != "") {
                    $form->get('mobile')->setAttribute('readonly', 'true');
                }
                $form->get('user_type')->setValue($userDetails['user_type_id']);
            }
        }
        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();
            //echo '<pre>';print_r($postData);die();
            $email_verified = (isset($userDetails['email_verified']) == 0) ? 'Un-Verified' : 'Verified';
            $phone_verified = (isset($userDetails['phone_verified']) == 0) ? 'Un-Verified' : 'Verified';
            if ($postData['email'] != "") {
                $form->get('email')->setAttribute('readonly', 'true');
            } if ($postData['mobile'] != "") {
                $form->get('mobile')->setAttribute('readonly', 'true');
            }
            $form->setData($postData);

            $referral_key = $postData['referral_key'];
            $refer_by = $postData['refer_by'];

            $id = intval($postData['user_id']);
            if ($form->isValid()) {
                $url = $this->apiUrl() . "/city/stateCountry?city_id=" . $postData['city_value'];
                $val = $this->get($url);
                $JsonData = $val->getBody();
                $JsonData = Json::decode($JsonData, true);
                $countryId = $JsonData['response'][0]['country_id'];
                $finalData = [];
                $finalData = [
                    'first_name' => $postData['first_name'],
                    'last_name' => $postData['last_name'],
                    'father_name' => $postData['father_name'],
                    'email' => $postData['email'],
                    //'mobile' => $postData['mobile'],
                    'landline_number' => $postData['landline_number'],
                    'alternate_mobile' => $postData['alternate_mobile'],
                    'dob' => date('Y-m-d', strtotime($postData['dob'])),
                    'gender' => $postData['gender'],
                    'address' => $postData['address'],
                    'country_id' => $countryId,
                    'state' => $postData['state_value'],
                    'city' => $postData['city_value'],
                    'kyc_type' => $postData['kyc_type'],
                    'kyc' => $postData['kyc'],
                    'pincode' => $postData['pincode'],
                    'user_id' => $postData['user_id'],
                    'user_type_id' => $postData['user_type']
                ];
                //echo '<pre>';print_r($finalData);die();

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

                if ((!empty($JsonData)) && !isset($JsonData['error'])) {
                    $msg = "Personal Details Updated Successfully";
                    $msg_class = "success";
                } else {
                    $msg = "Personal Details Not Updated";
                    $msg_class = "danger";
                }
            } else {
                $msg = $form->getMessages();
                //echo '<pre>';print_r($msg);die();
            }
        }
        $viewModel = new ViewModel([
            'form' => $form,
            'tab' => 'personal-detail',
            'id' => $id,
            'email_verified' => $email_verified,
            'refer_by' => $refer_by,
            'referral_key' => $referral_key,
            'phone_verified' => $phone_verified,
            'msg' => $msg,
            'msg_class' => $msg_class,
            'userTypeId' => $userTypeId
        ]);
        return $viewModel;
    }

    /**
     * Company-Detail
     * @return ViewModel
     */
    public function companyDetailAction() {
        $msg = "";
        $msg_class = "";
        $request = $this->getRequest();
        $form = new ProfileCompanyDetailForm;

        if (intval($this->params('id'))) {
            $id = intval($this->params('id'));
        }
        $form->get('gst_proof')->setAttribute('data-id',$id);
        $form->get('office_proof')->setAttribute('data-id',$id);
        $form->get('company_pancard_proof')->setAttribute('data-id',$id);
        $form->get('logo')->setAttribute('data-id',$id);

        if (!empty($id)) {
            $form->get('user_id')->setValue($id);
            $url = $this->apiUrl() . "/company/companydetails?user_id=" . $id;
            $val = $this->get($url);
            $JsonData = $val->getBody();
            $JsonData = Json::decode($JsonData, true);
            if ($JsonData['responsedata']['status'] == true) {
                $userDetails = $JsonData['responsedata'];
                $form->get('state_value')->setValue($userDetails['state']);
                $form->get('city_value')->setValue($userDetails['city']);
                $form->setData($userDetails);
            }
        }
        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();
            $form->setData($postData);
            $id = intval($postData['user_id']);
            if ($form->isValid()) {

                $finalData = [];
                $finalData = [
                    'company_name' => $postData['company_name'],
                    'company_address' => $postData['company_address'],
                    'state' => $postData['state_value'],
                    'city' => $postData['city_value'],
                    'service_tax_gst' => $postData['service_tax_gst'],
                    'pancard_no' => $postData['pancard_no'],
                    'contact_person_name' => $postData['contact_person_name'],
                    'landline_no' => $postData['landline_no'],
                    'mobile_no' => $postData['mobile_no'],
                    'email' => $postData['email'],
                    'website_url' => $postData['website_url'],
                    //'logo' => $postData['logo'],
                    'user_id' => $postData['user_id'],
                    'country' => 101,
                    'pincode' => $postData['pincode']
                ];
                //print_r($finalData); exit;
                $url = $this->apiUrl() . "/company";
                if ($postData['id'] != "") {
                    $finalData['id'] = $postData['id'];
                    $val = $this->put($url, $finalData);
                } else {
                    $val = $this->post($url, $finalData);
                }
                $JsonData = $val->getBody();
                $JsonData = Json::decode($JsonData, true);
                //print_r($JsonData); exit;
                if (!empty($JsonData)) {
                    $msg = "Company Details Updated Successfully";
                    $msg_class = "success";
                } else {
                    $msg = "Company Details Not Updated";
                    $msg_class = "danger";
                }
            } else {
                $msg = $form->getMessages();
                //echo '<pre>';print_r($msg);die();
            }
        }
        $userTypeId = $this->userModel->getUserType($id);
        $viewModel = new ViewModel([
            'form' => $form,
            'tab' => 'company-detail',
            'id' => $id,
            'msg' => $msg,
            'msg_class' => $msg_class,
            'userTypeId' => $userTypeId
        ]);
        return $viewModel;
    }

    /**
     * Vehicle Detail
     * @return ViewModel
     */
    public function vehicleDetailAction() {
        $vehicleData = [];
        ProfileVehicleDetailForm::$cabType = $this->vehicleModel->getVehicleTypeList();
        ProfileVehicleDetailForm::$ignitionType = $this->getFuelTypeList();
        ProfileVehicleDetailForm::$amenities = $this->getVehicleAmenitiesList();
        ProfileVehicleDetailForm::$modelYear = $this->getModelYearList();
        $request = $this->getRequest();
        $form = new ProfileVehicleDetailForm();
        if (intval($this->params('id'))) {
            $id = intval($this->params('id'));
        }

        if (!empty($id)) {
            $data['user_id'] = $id;
            $vehicleData = $this->getAllMappingVehicleList($data);
            if (isset($vehicleData[0])) {

                $vehicleData = $vehicleData[0];


                if ($vehicleData['vehicle_owner_type'] == "Owned") {
                    $form->get('vehicle_attach_selected')->setValue(1);
                }
                if ($vehicleData['vehicle_owner_type'] == "Attached") {
                    $form->get('vehicle_owned_selected')->setValue(0);
                }
            }
        }
        $userTypeId = $this->userModel->getUserType($id);
        $viewModel = new ViewModel(['form' => $form, 'tab' => 'vehicle-detail', 'id' => $id, 'vehicleData' => $vehicleData, 'userTypeId' => $userTypeId]);
        return $viewModel;
    }

    /**
     * Change Password...
     * @return ViewModel
     */
    public function changePasswordAction() {
        $msg = "";
        $msg_class = "";
        $id = "";
        $form = new ProfileChangePasswordForm();
        if (intval($this->params('id'))) {
            $id = intval($this->params('id'));
        }
        $form->get('user_id')->setValue($id);
        $request = $this->getRequest();
        if ($request->isPost()) {
            $postData = $this->getRequest()->getPost()->toArray();
            $form->getInputFilter()->get('old_password')->setRequired(false);
            $form->setData($postData);
            $id = intval($postData['user_id']);
            if ($form->isValid()) {
                $finalData = [];
                $finalData = [
                    'password' => $postData['new_password'],
                    'id' => $postData['user_id']
                ];
                $response = $this->userModel->userChangePassword($finalData);
                if ($response['status'] == "success") {
                    $msg = $response['message'];
                    $msg_class = "success";
                } else {
                    $msg = $response['message'];
                    $msg_class = "danger";
                }
            }
        }
        $userTypeId = $this->userModel->getUserType($id);
        $viewModel = new ViewModel([
            'form' => $form,
            'tab' => 'change-password',
            'id' => $id,
            'msg' => $msg,
            'msg_class' => $msg_class,
            'userTypeId' => $userTypeId
        ]);
        return $viewModel;
    }

    /**
     * Bank Detail...
     * @return ViewModel
     */
    public function bankDetailAction() {
        $msg = "";
        $msg_class = "";
        $id = "";
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $userId = $loginData['user_id'];
        $form = new ProfileBankDetailForm();
        $request = $this->getRequest();

        if (intval($this->params('id'))) {
            $id = intval($this->params('id'));
        }
        $form->get('user_id')->setValue($id);

        if (!empty($id)) {
            $val = '{"where": {"user_id": "' . $id . '"}}';
            $val = rawurlencode($val);
            $url = $this->apiUrl() . "/bank-details?&filter=" . $val;
            $resp = $this->get($url);
            $JsonData = $resp->getBody();
            $JsonData = Json::decode($JsonData, true);
            if (!empty($JsonData[0])) {
                $userDetails = $JsonData[0];
                $bankproof = $userDetails['bank_proof'];
                $form->setData($userDetails);
            }
        }

        if ($request->isPost()) {
            $postData = $this->getRequest()->getPost()->toArray();
            $id = intval($postData['user_id']);
            $form->setData($postData);
            if ($form->isValid()) {

                $fileNameBankProof = $_FILES['bank_proof']['name'];
                if ($fileNameBankProof != '') {
                    $fileTmpNamebankProof = $_FILES['bank_proof']['tmp_name'];
                    $extension = pathinfo($_FILES['bank_proof']['name'], PATHINFO_EXTENSION);
                    $bankProofImageName = "bank_proof_" . time() .'.'. $extension;

                    $allowed = array('png', 'jpg', 'gif', 'zip', 'pdf', 'docx', 'doc', 'jpeg', '');
                    if (!in_array(strtolower($extension), $allowed)) {

                        $msg = "Please upload (png,jpg,gif,zip,pdf,docx,doc,jpeg) file only.";
                        $this->redirect()->toRoute('usermanagement', ['action' => 'bank-detail', 'id' => $id]);
                        $this->flashMessenger()->addMessage(array('error' => $msg));
                    }
                    $filepath = $this->config()->getConfig()->base_url->file_path;
                    $targetPath = $filepath."public/upload/" . $id . "/" . $bankProofImageName;
                    move_uploaded_file($fileTmpNamebankProof, $targetPath);
                }

                $finalData = [];
                $finalData = [
                    'bank_id' => $postData['bank_id'],
                    'user_id' => $postData['user_id'],
                    'name' => $postData['name'],
                    'branch' => $postData['branch'],
                    'address' => $postData['address'],
                    'ifsc_code' => $postData['ifsc_code'],
                    'ac_no' => $postData['ac_no'],
                    'ac_holder_name' => $postData['ac_holder_name'],
                    'bank_proof' => isset($bankProofImageName)?$bankProofImageName:'',
                    'status' => '1',
                    'ip' => $_SERVER['SERVER_ADDR']
                ];
                if ($postData['bank_id'] > 0) {
                    $finalData['modified_by'] = $userId;
                } else {
                    $finalData['created_by'] = $userId;
                    $finalData['created_date'] = date('Y-m-d h:i:s');
                }

                $finalData = array_filter($finalData);
                $val = '{"user_id":"'.$id.'"}';
                $val = rawurlencode($val);
                $url = $this->apiUrl() ."/bank-details/upsertWithWhere?where=".$val;
                $respdata = $this->post($url, $finalData);
                $JsonData = $respdata->getBody();
                $JsonData = Json::decode($JsonData, true);
                if (!empty($JsonData)) {
                    $msg = "Bank Details Updated Successfully";
                    $msg_class = "success";
                } else {
                    $msg = "Bank Details Not Updated";
                    $msg_class = "danger";
                }

                $this->redirect()->toRoute('usermanagement', ['action' => 'bank-detail', 'id' => $id]);
                $this->flashMessenger()->addMessage(array('success' => $msg));
            }
        }
        $userTypeId = $this->userModel->getUserType($id);
        $viewModel = new ViewModel([
            'form' => $form,
            'tab' => 'bank-detail',
            'id' => $id,
            'msg' => $msg,
            'msg_class' => $msg_class,
            'userTypeId' => $userTypeId,
            'bankproof'=>$bankproof
        ]);
        return $viewModel;
    }

    /**
     * Credit Request...
     * @return ViewModel
     */
    public function creditRequestAction() {
        $msg = "";
        $msg_class = "";
        $id = "";
        $form = new ProfileCreditRequestForm();
        if (intval($this->params('id'))) {
            $id = intval($this->params('id'));

            $val = '{"where": {"user_id": "'. $id.'"}}';
            $val = rawurlencode($val);
            $url = $this->apiUrl() . "/driver-payment?&filter=" . $val;
            $resp = $this->get($url);
            $JsonData = $resp->getBody();
            $JsonData = Json::decode($JsonData, true);
            if (!empty($JsonData[0])) {
                $userDetails = $JsonData[0];
                $paymentproof = $userDetails['fileupload'];
                $form->setData($userDetails);
                $form->get('payment_mode')->setValue($userDetails['transaction_mode']);
            }
        }

        $form->get('user_id')->setValue($id);
        $request = $this->getRequest();
        if ($request->isPost()) {
            $postData = $this->getRequest()->getPost()->toArray();
            $id = $postData['user_id'];
            $form->setData($postData);
            if ($form->isValid()) {
                $finalData = [];

                if (!empty($_FILES['fileupload'])) {
                    $paymentFile = $_FILES['fileupload']['name'];
                    $ext = pathinfo($paymentFile, PATHINFO_EXTENSION);
                    $paymentFile = file_get_contents($_FILES['fileupload']['tmp_name']);
                    $paymentFileName = date("d-m-Y") . "-" . time() . "-" . "payment_proof." . $ext;
                    $paymentFile = base64_encode($paymentFile);
                    $filePath = PUBLIC_PATH . '/upload/' . $postData['user_id'] . '/' . $paymentFileName;
                    $fileData['base64image'] = $paymentFile;
                    $fileData['filepath'] = $filePath;

                    $this->commonModel->uploadimageapi($fileData);
                }

                $finalData = [
                    'user_id' => $postData['user_id'],
                    'deposit_date' => $this->userModel->changeDateFormat($postData['deposit_date']),
                    'transaction_mode' => $postData['payment_mode'],
                    'partner_bank' => $postData['partner_bank_accounts'],
                    'amount' => $postData['amount'],
                    'deposit_bank' => $postData['deposit_bank'],
                    'deposit_branch' => $postData['deposit_branch'],
                    'remark' => $postData['remark_request'],
                    'fileupload' => $paymentFileName,
                    'payment_ref_no' => $this->generatePaymentRefNo(),
                ];
                //echo '<pre>';print_r($finalData);die();
                $url = $this->apiUrl() . "/driver-payment";
                $val = $this->post($url, $finalData);
                $JsonData = $val->getBody();
                $JsonData = Json::decode($JsonData, true);
                //print_r($JsonData); exit;

                if ((!empty($JsonData))) {
                    $msg = "Credit Request Insert Successfully";
                    $msg_class = "success";
                } else {
                    $msg = "Credit Request Not Insert";
                    $msg_class = "danger";
                }
                $this->redirect()->toRoute('usermanagement', ['action' => 'credit-request', 'id' => $id]);
                $this->flashMessenger()->addMessage(array('success' => $msg));
            }
        }
        $userTypeId = $this->userModel->getUserType($id);
        $viewModel = new ViewModel([
            'form' => $form,
            'tab' => 'credit-request',
            'msg' => $msg,
            'msg_class' => $msg_class,
            'id' => $id,
            'userTypeId' => $userTypeId,
            'paymentproof'=>$paymentproof
        ]);
        return $viewModel;
    }

    /**
     * Duty Payment Detail...
     * @return ViewModel
     */
    public function dutyDetailAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $login_userId = $loginData['user_id'];

        $msg = "";
        $msg_class = "";
        $id = "";
        //ProfileDutyDetailForm:: $prefcity = $this->userModel->getPrefCityList();
        ProfileDutyDetailForm:: $dutytype = $this->userModel->getPackageTypeList();
        ProfileDutyDetailForm:: $paymenttype = $this->userModel->getPaymentTypeList();
        ProfileDutyDetailForm:: $langspeak = $this->userModel->getLanguageList();
        ProfileDutyDetailForm:: $langwrite = $this->userModel->getLanguageList();
        ProfileDutyDetailForm:: $shiftlogin = $this->userModel->getShiftLoginList();
        ProfileDutyDetailForm:: $weekdays = $this->userModel->getWeekDaysList();
        $form = new ProfileDutyDetailForm();
        if (intval($this->params('id'))) {
            $id = intval($this->params('id'));
        }
        $form->get('user_id')->setValue($id);

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

        $request = $this->getRequest();
        if ($request->isPost()) {
            $postData = $this->getRequest()->getPost()->toArray();
            $id = $postData['user_id'];
            $form->setData($postData);
            if ($form->isValid()) {
                $finalData = [];
                $city_ids = str_replace(';', ',', $postData['pref_city_search_id']);
                $finalData = [
                    'booking_type' => implode(",", $postData['duty_type']),
                    'payment_cash' => implode(",", $postData['payment_type']),
                    'pref_city' => rtrim($city_ids, ","),
                    //'pref_city' => implode(",", $postData['preferred_city']),
                    'shift' => implode(",", $postData['shift_of_login']),
                    'speak' => implode(",", $postData['language_speak']),
                    'write' => implode(",", $postData['language_write']),
                    'week_off' => implode(",", $postData['week_days']),
                    'user_id' => $postData['user_id'],
                    'created_date' => date('Y-m-d'),
                    'created_by' => $login_userId,
                ];
                //Debug::dump($finalData);
                //exit;
                $url = $this->apiUrl() . "/user/addDutyDetail";
                $val = $this->post($url, $finalData);
                $JsonData = $val->getBody();
                $JsonData = Json::decode($JsonData, true);

                if ((!empty($JsonData['response'])) && (!isset($JsonData['error']))) {
                    $msg = "Duty Details Updated Successfully";
                    $this->redirect()->toRoute('usermanagement', ['action' => 'duty-detail', 'id' => $id]);
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                } else {
                    $msg = "Duty Details Not Updated";
                    $this->redirect()->toRoute('usermanagement', ['action' => 'duty-detail', 'id' => $id]);
                    $this->flashMessenger()->addMessage(array('success' => $msg));
                }
            } else {
                //echo "Jain";
                //$msg = $form->getMessages();
                //Debug::dump($msg); exit;
            }
        }

        $userPrefDriveCityList = $this->userModel->getUserprefDriveCity($id);
        $userDutyTypeList = $this->userModel->getUserdutyTypeList($id);
        $userPaymentTypeList = $this->userModel->getUserpaymentTypeList($id);
        $userSpeakLangList = $this->userModel->getUserSpeakLanguageList($id);
        $userWriteLangList = $this->userModel->getUserWriteLanguageList($id);
        $userShiftLoginList = $this->userModel->getUserShiftLoginList($id);
        $userWeekDaysList = $this->userModel->getUserWeekDaysList($id);
        $userTypeId = $this->userModel->getUserType($id);
        //echo '<pre>';print_r($userPrefDriveCityList); die();
        if (!empty($userPrefDriveCityList)) {
            $city_name = array_column($userPrefDriveCityList, 'name', 'city_id');
            $city_name_string = implode('; ', array_values($city_name)) . '; ';
            $city_ids = implode(';', array_keys($city_name)) . ';';
        }
        $viewModel = new ViewModel([
            'form' => $form,
            'userPrefDriveCityList' => $userPrefDriveCityList,
            'userDutyTypeList' => $userDutyTypeList,
            'userPaymentTypeList' => $userPaymentTypeList,
            'userSpeakLangList' => $userSpeakLangList,
            'userWriteLangList' => $userWriteLangList,
            'userShiftLoginList' => $userShiftLoginList,
            'userWeekDaysList' => $userWeekDaysList,
            'tab' => 'duty-detail',
            'id' => $id,
            'msg' => $msg,
            'msg_class' => $msg_class,
            'userTypeId' => $userTypeId,
            'city_name_string' => isset($city_name_string) ? $city_name_string : '',
            'city_ids' => isset($city_ids) ? $city_ids : '',
        ]);
        return $viewModel;
    }

    /**
     * Licence Detail...
     * @return ViewModel
     */
    public function licenseDetailAction() {
        $getDocument = [];
        $msg = "";
        $msg_class = "";
        $id = "";
        $form = new ProfileLicenseDetailForm();

        if (intval($this->params('id'))) {
            $id = intval($this->params('id'));
        }
        $form->get('user_id')->setValue($id);
        $form->get('police_proof')->setAttribute('data-id',$id);
        $form->get('audit_proof')->setAttribute('data-id',$id);
        $form->get('pancard_proof')->setAttribute('data-id',$id);
        $form->get('license_proof')->setAttribute('data-id',$id);
        $request = $this->getRequest();

        if (!empty($id)) {

            $documentDetail = $this->userModel->getUserDocument($id,'');
            if (isset($documentDetail['responsedata']) && $documentDetail['responsedata']['status'] == 'success') {
                $getDocument = $documentDetail['responsedata']['data'];
            }

            $val = '{"where": {"user_id": "' . $id . '"}}';
            $val = rawurlencode($val);
            $url = $this->apiUrl() . "/driver?&filter=" . $val;
            $resp = $this->get($url);
            $JsonData = $resp->getBody();
            $JsonData = Json::decode($JsonData, true);
            //print_r($JsonData); exit;

            if (!empty($JsonData[0])) {
                $userDetails = $JsonData[0];
                $form->setData($userDetails);
                $state_name = $this->userModel->getStateId($userDetails['license_state']);
                $form->get('license_state')->setValue(isset($state_name['name']) ? $state_name['name'] : '');
                $form->get('license_state_value')->setValue($userDetails['license_state']);
            }
        }

        if ($request->isPost()) {
            $postData = $this->getRequest()->getPost()->toArray();
            $id = $postData['user_id'];
            $form->setData($postData);

            if ($form->isValid()) {
                $finalData = [];
                $finalData = [
                    'license_state' => $postData['license_state_value'],
                    'driving_license_no' => $postData['driving_license_no'],
                    'license_validity' => $postData['license_validity'],
                    'gps' => $postData['gps'],
                    'pancard_no' => $postData['pancard_no'],
                    'user_id' => $postData['user_id'],
                    'id' => $postData['id']
                ];
                //$val = '{"id": "' . $postData['id'] . '"}';
                $finalData = array_filter($finalData);
                $val = '{"user_id": "' . $postData['user_id'] . '"}';
                $val = rawurlencode($val);
                $url = $this->apiUrl() . "/driver/upsertWithWhere?where=" . $val;
                $val = $this->post($url, $finalData);
                $JsonData = $val->getBody();
                $JsonData = Json::decode($JsonData, true);
                if (!empty($JsonData)) {
                    $msg = "License Details Updated Successfully";
                    $msg_class = "success";
                } else {
                    $msg = "License Details Not Updated";
                    $msg_class = "danger";
                }
            }
        }
        $userTypeId = $this->userModel->getUserType($id);
        $viewModel = new ViewModel([
            'form' => $form,
            'tab' => 'license-detail',
            'msg' => $msg,
            'msg_class' => $msg_class,
            'id' => $id,
            'userTypeId' => $userTypeId,
            'getdoc' => $getDocument
        ]);
        return $viewModel;
    }

    /**
     * Other Detail...
     * @return ViewModel
     */
    public function otherDetailAction() {
        $msg = "";
        $msg_class = "";
        $id = "";
        $form = new ProfileOtherDetailForm();
        $request = $this->getRequest();
        if (intval($this->params('id'))) {
            $id = intval($this->params('id'));
        }
        $form->get('user_id')->setValue($id);
        $val = '{"where": {"user_id": "' . $id . '"}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/driver?&filter=" . $val;
        $resp = $this->get($url);
        $JsonData = $resp->getBody();
        $JsonData = Json::decode($JsonData, true);
        //print_r($JsonData); exit;
        if (!empty($JsonData[0])) {
            $userDetails = $JsonData[0];
            $form->setData($userDetails);
        }

        if ($request->isPost()) {
            $postData = $this->getRequest()->getPost()->toArray();
            $id = $postData['user_id'];
            $form->setData($postData);
            if ($form->isValid()) {
                $finalData = [];
                $finalData = [
                    'route_know' => $postData['route_know'],
                    'zone' => $postData['zone'],
                    'user_id' => $postData['user_id'],
                    'id' => $postData['id']
                ];
                $finalData = array_filter($finalData);
                $val = '{"user_id": "' . $postData['user_id'] . '"}';
                $val = rawurlencode($val);
                $url = $this->apiUrl() . "/driver/upsertWithWhere?where=" . $val;
                $val = $this->post($url, $finalData);
                $JsonData = $val->getBody();
                $JsonData = Json::decode($JsonData, true);
                if (!empty($JsonData)) {
                    $msg = "Other Details Updated Successfully";
                    $msg_class = "success";
                } else {
                    $msg = "Other Details Not Updated";
                    $msg_class = "danger";
                }
            }
        }
        $userTypeId = $this->userModel->getUserType($id);
        $viewModel = new ViewModel([
            'form' => $form,
            'tab' => 'other-detail',
            'id' => $id,
            'msg' => $msg,
            'msg_class' => $msg_class,
            'userTypeId' => $userTypeId
        ]);
        return $viewModel;
    }

    /**
     * SMS Detail...
     * @return ViewModel
     */
    public function smsDetailAction() {
        if (intval($this->params('id'))) {
            $id = intval($this->params('id'));
        }
        $smsListing = $this->userModel->getSmsHistory($id);
        $userTypeId = $this->userModel->getUserType($id);
        $viewModel = new ViewModel([
            'tab' => 'sms-detail',
            'id' => $id,
            'smsListing' => $smsListing,
            'userTypeId' => $userTypeId
        ]);
        return $viewModel;
    }

    /**
     * Email Detail...
     * @return ViewModel
     */
    public function emailDetailAction() {
        if (intval($this->params('id'))) {
            $id = intval($this->params('id'));
        }
        $emailListing = $this->userModel->getEmailHistory($id);
        $userTypeId = $this->userModel->getUserType($id);
        $viewModel = new ViewModel([
            'tab' => 'email-detail',
            'id' => $id,
            'emailListing' => $emailListing,
            'userTypeId' => $userTypeId
        ]);
        return $viewModel;
    }

    /**
     * Status History Detail...
     * @return ViewModel
     */
    public function statusHistoryAction() {
        if (intval($this->params('id'))) {
            $id = intval($this->params('id'));
        }
        $form = new DataSearchForm();
        $request = $this->getRequest();

        $from_date = "";
        $to_date = "";
        if (intval($this->params('id'))) {
            $id = intval($this->params('id'));
        }
        $form->get('user_id')->setValue(isset($id) ? $id : 0);
        if ($request->isPost()) {
            $postData = $this->getRequest()->getPost()->toArray();
            $form->setData($postData);
            $id = intval($postData['user_id']);
            $from_date = $postData['from_date'];
            $to_date = $postData['to_date'];
        }
        $statusHistory = $this->userModel->getStatusHistory($id, $from_date, $to_date);
        $userTypeId = $this->userModel->getUserType($id);
        $viewModel = new ViewModel([
            'form' => $form,
            'tab' => 'status-history',
            'statusHistory' => $statusHistory['responsedata']['data'],
            'id' => $id,
            'userTypeId' => $userTypeId
        ]);
        return $viewModel;
    }

    /**
     * Allocation History Detail...
     * @return ViewModel
     */
    public function allocationHistoryAction() {
        $form = new DataSearchForm();
        $request = $this->getRequest();

        $from_date = "";
        $to_date = "";
        if (intval($this->params('id'))) {
            $id = intval($this->params('id'));
        }
        $form->get('user_id')->setValue(isset($id) ? $id : 0);
        if ($request->isPost()) {
            $postData = $this->getRequest()->getPost()->toArray();
            $form->setData($postData);
            $id = intval($postData['user_id']);
            $from_date = $postData['from_date'];
            $to_date = $postData['to_date'];
        }
        $allocationHistory = $this->userModel->getAllocationHistory($id, $from_date, $to_date);
        $userTypeId = $this->userModel->getUserType($id);
        $viewModel = new ViewModel([
            'form' => $form,
            'tab' => 'allocation-history',
            'allocationHistory' => $allocationHistory['responsedata'],
            'id' => $id,
            'userTypeId' => $userTypeId
        ]);
        return $viewModel;
    }

    /**
     * Booking History Detail...
     * @return ViewModel
     */
    public function bookingHistoryAction() {
        $form = new DataSearchForm();
        $request = $this->getRequest();
        $data = "";
        $from_date = "";
        $to_date = "";
        if (intval($this->params('id'))) {
            $id = intval($this->params('id'));
        }
        $form->get('user_id')->setValue(isset($id) ? $id : 0);
        $data = [
            'user_id' => isset($id) ? $id : 0
        ];
        if ($request->isPost()) {
            $postData = $this->getRequest()->getPost()->toArray();
            $form->setData($postData);
            $id = intval($postData['user_id']);
            $data = [
                'user_id' => intval($postData['user_id']),
                'from_date' => $postData['from_date'],
                'to_date' => $postData['to_date']
            ];
        }
        //echo '<pre>';print_r($data);die();
        $bookingHistory = $this->userModel->getBookingHistory($data);
        $userTypeId = $this->userModel->getUserType($id);
        $viewModel = new ViewModel([
            'form' => $form,
            'tab' => 'booking-history',
            'bookingHistory' => $bookingHistory,
            'id' => $id,
            'userTypeId' => $userTypeId
        ]);
        return $viewModel;
    }

    /**
     * Driver Ledger Detail...
     * @return ViewModel
     */
    public function driverLedgerAction() {
        $form = new DataSearchForm();
        $request = $this->getRequest();

        $from_date = "";
        $to_date = "";
        if (intval($this->params('id'))) {
            $id = intval($this->params('id'));
        }
        $form->get('user_id')->setValue(isset($id) ? $id : 0);
        if ($request->isPost()) {
            $postData = $this->getRequest()->getPost()->toArray();
            $form->setData($postData);
            $id = intval($postData['user_id']);
            $from_date = $postData['from_date'];
            $to_date = $postData['to_date'];
        }
        $driverLedger = $this->userModel->getDriverLedger($id, $from_date, $to_date);
        $userTypeId = $this->userModel->getUserType($id);
        $viewModel = new ViewModel([
            'form' => $form,
            'tab' => 'driver-ledger',
            'driverLedger' => $driverLedger['responsedata'],
            'id' => $id,
            'userTypeId' => $userTypeId
        ]);
        return $viewModel;
    }

    /**
     * Payment History...
     * @return ViewModel
     */
    public function paymentHistoryAction() {
        if (intval($this->params('id'))) {
            $id = intval($this->params('id'));
        }
        $paymentHistory = $this->userModel->getPaymentHistory($id);
        //echo '<pre>';print_r($paymentHistory);die();
        $userTypeId = $this->userModel->getUserType($id);
        $viewModel = new ViewModel([
            'tab' => 'payment-history',
            'paymentHistory' => $paymentHistory['responsedata'],
            'id' => $id,
            'userTypeId' => $userTypeId
        ]);
        return $viewModel;
    }

    /**
     * View By Id
     * @return ViewModel
     */
    public function viewByIdAction() {
        //echo 'raza';die;

        $id = $this->params()->fromRoute('id');

        //call api here...
        $info = [
            'login_id' => 'amir@gmail.com',
            'name' => 'amir',
            'email' => 'amirraza278@gmail.com',
            'country_name' => 'India',
            'city_name' => 'New Delhi',
            'user_type' => '1',
            'is_active' => '1'
        ];

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

    /**
     * Delete...
     * @return type
     */
    public function deleteAction() {
        //echo 'raza';die;
        $id = $this->params()->fromRoute('id');

        //call api here...
        $res = 1;

        return $this->redirect()->toRoute('usermanagement', ['action' => 'index']);
    }

    /**
     * Check Already Exist LoginId...
     * @return JSON
     */
    public function checkAlreadyExistLoginIdAction() {
        $request = $this->getRequest();
        if ($request->isPost()) {
            $fieldName = $request->getPost("id");
            $value = $request->getPost("value");
            $userTypeId = $request->getPost("userTypeId");
            //$url = $this->apiUrl() . "/user/verifyregister?username=" . $value . "&user_type_id=" . $userTypeId;
            $url = $this->apiUrl() . "/user/verifyregister?username=" . $value;
            $val = $this->get($url);
            $JsonData = $val->getBody();
            $responseData = Json::decode($JsonData, true);
            //echo '<pre>';print_r($responseData);die();
            if ($responseData['responsedata']['status'] == 'failed') {
                return new JsonModel(["id" => $fieldName, "message" => "<p style='color:green;'>Available</p>", 'status' => false]);
            } else {
                $signup_status = $responseData['responsedata']['data']['signup_status'];
                $is_active = $responseData['responsedata']['data']['is_active'];
                if ($signup_status != 10 && $is_active == 0) {
                    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 == 0) {
                    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();
    }

    /**
     * Get State List
     * @return JSON
     */
    public function getStateListAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $country_id = $postData['country_id'];
        $val = '{"where": {"country_id": "' . $country_id . '%"}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/state?&filter=" . $val;
        $resp = $this->get($url);
        $stateJsonData = Json::decode($resp->getBody(), true);
        if (!empty($stateJsonData)) {
            foreach ($stateJsonData as $value) {
                $data[] = ["id" => $value['id'], "name" => $value['name']];
            }
            $response = ["status" => true, "data" => $data];
        } else {
            $response = ["status" => false];
        }
        $view = new JsonModel($response);
        return $view;
    }

    /**
     * State List...
     * @return ViewModel
     */
    public function getLicenseStateListAction() {
        $request = $this->getRequest();
        $postdata = $request->getPost();
        $term = $postdata['term'];
        $val = '{"where": {"name": {"like": "' . $term . '%"}},"limit":10}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/state?&filter=" . $val;
        $resp = $this->get($url);
        $cityJsonData = Json::decode($resp->getBody(), true);
        if (!empty($cityJsonData)) {
            foreach ($cityJsonData as $value) {
                $data[] = ["label" => $value['name'], "value" => $value['id']];
            }
        } else {
            $data[] = ["label" => 'Not Exist'];
        }
        $view = new JsonModel($data);
        return $view;
    }

    /**
     * Get City List
     * @return JSON
     */
    public function getCityListAction() {
        $data = [];
        $postData = $this->getRequest()->getPost();
        $state_id = $postData['state_id'];
        $val = '{"where": {"state_id": "' . $state_id . '%"}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/city?&filter=" . $val;
        $resp = $this->get($url);
        $cityJsonData = Json::decode($resp->getBody(), true);
        if (!empty($cityJsonData)) {
            foreach ($cityJsonData as $value) {
                $data[] = ["id" => $value['id'], "name" => $value['name']];
            }
            $response = ["status" => true, "data" => $data];
        } else {
            $response = ["status" => false];
        }
        $view = new JsonModel($response);
        return $view;
    }

    /** Function to change User STATUS */
    public function userStatusAction() {
        $data1 = [];
        $data1['user_type_id'] = '1,5,6';
        $data1['company_id'] = $this->config()->getConfig()->company->companyId;
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;
        $data = $this->getRequest()->getPost();
        //print_r($data); die;
        $id = implode(',', $data['selected']);
        $user_status = $data['status'];
        $data = ['user_id' => $user_id, 'id' => $id, 'user_status' => $user_status];
        $this->userModel->updateUserStatus($data);
        $userListing = $this->userModel->getUserList($data1);
        $viewModel = new ViewModel(['userListing' => $userListing['data']['responsedata']]);
        $viewModel->setTemplate('dashboard/user-management/user-listing.phtml');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    /**
     * Check Already Exist LoginId...
     * @return JSON
     */
    public function showAllocationDataAction() {
        $request = $this->getRequest();
        if ($request->isPost()) {
            $user_id = $request->getPost("user_id");
            $date = $request->getPost("date");
            $booking_status = $request->getPost("booking_status");
            $url = $this->apiUrl() . "/user/allocationHistoryDetails?user_id=" . $user_id . "&date=" . $date . "&booking_status=" . $booking_status;
            $resp = $this->get($url);
            $data = Json::decode($resp->getBody(), true);
            $viewModel = new ViewModel(['allocationData' => $data['responsedata']]);
            $viewModel->setTemplate('dashboard/user-management/show-allocation-data.phtml');
            $viewModel->setTerminal(true);
            return $viewModel;
        }
    }

    /**
     *
     * Vehicle Type List...
     * @return ViewModel
     */
    public function getVehicleTypeList($data = null) {
        $vehicleTypeJsonDataArray = [];
        $url = $this->apiUrl() . "/vehicle-type";
        $resp = $this->get($url);
        $vehicleTypeJsonData = Json::decode($resp->getBody(), true);
        if ($vehicleTypeJsonData['status'] == "success") {
            foreach ($vehicleTypeJsonData['data'] as $res) {
                $vehicleTypeJsonDataArray[$res['id']] = $res['vehicle_type'];
            }
        }
        return $vehicleTypeJsonDataArray;
    }

    /** Function to GET VEHICLE IGNITION TYPES */
    public function getFuelTypeList() {
        $fuelTypeJsonDataArray = [];
        $url = $this->apiUrl() . "/fuel-type";
        $resp = $this->get($url);
        $fuelTypeJsonData = Json::decode($resp->getBody(), true);
        if ($fuelTypeJsonData['status'] == "success") {
            foreach ($fuelTypeJsonData['data'] as $res) {
                $fuelTypeJsonDataArray[$res['id']] = $res['fuel_type'];
            }
        }
        return $fuelTypeJsonDataArray;
    }

    /** Function to Get VEHICLE AMENITIES */
    public function getVehicleAmenitiesList() {
        $amenitiesJsonDataArray = [];
        $url = $this->apiUrl() . "/vehicle-amenities";
        $resp = $this->get($url);
        $amenitiesJsonData = Json::decode($resp->getBody(), true);
        foreach ($amenitiesJsonData as $res) {
            $amenitiesJsonDataArray[$res['id']] = $res['amenities_name'];
        }
        return $amenitiesJsonDataArray;
    }

    /** Function to Get VEHICLE MODEL YEARS */
    public function getModelYearList() {
        $yearJsonDataArray = [];
        $date = date('Y');
        for ($i = $date; $i >= $date - 20; $i--) {
            $yearJsonDataArray[$i] = $i;
        }
        return $yearJsonDataArray;
    }

    /**
     *
     * Vehicle Mapping List...
     * @return ViewModel
     */
    public function getAllMappingVehicleList($data) {
        $vehicleList = [];
        $url = $this->apiUrl() . "/vehicle-master/listDriverVehicleMap";
        $resp = $this->post($url, $data);
        $vehiclelistJsonData = Json::decode($resp->getBody(), true);
        if (!isset($vehiclelistJsonData['error'])) {
            $vehicleList = $vehiclelistJsonData['responsedata'];
        }
        return $vehicleList;
    }

    public function getPaymentRefNo() {
        $url = $this->apiUrl() . "/driver-payment/driverPaymentRefno";
        $resp = $this->get($url);
        $data = Json::decode($resp->getBody(), true);
        $val = $data['responsedata'][0];
        if ($val['payment_ref_no'] != "") {
            $value = '00' . $val['payment_ref_no'];
        } else {
            $value = $this->config()->getConfig()->invoice->creditPaymentStart;
        }
        return $value;
    }

    public function generatePaymentRefNo() {
        $val = $this->getPaymentRefNo();
        $initial = $this->config()->getConfig()->company->companyInitial;
        //// Code for year Starts Here ///
        $dateYear = date('y');
        $dateYear = 64 + $dateYear;
        $dateYear = chr($dateYear);
        //// Code for year Ends Here ///
        //// Code for Month Starts Here ////////
        $dateMonth = date('m');
        $dateMonth = 64 + $dateMonth;
        $dateMonth = chr($dateMonth);
        //// Code for Month Ends Here///////
        $ref_no = $initial . '' . $dateYear . '' . $dateMonth . '' . $val;
        return $ref_no;
    }

    public function userTypeViewAction() {

        $status = [];
        $request = $this->getRequest();
        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();
            $finalData = [];
            $finalData = [
                'user_id' => $postData['usertid'],
                'user_type_id' => $postData['usertype']
            ];

            $url = $this->apiUrl() . "/user/updatepersonalinfo";
            $val = $this->post($url, $finalData);
            $JsonData = $val->getBody();
            $JsonData = Json::decode($JsonData, true);
            if ((!empty($JsonData['response'])) && ($JsonData['response']['status'] == 'success')) {

                $msg = " User type updated successfully !";
            } else {
                $msg = "User type could not updated !";
            }
            $status = ['msg' => $msg];
        }

        $viewModel = new JsonModel($status);
        return $viewModel;
    }

    public function driverStatus() {
        $data = [];
        $val = '{"where": {"type": "driverS"}}';
        $val = rawurlencode($val);
        $url = $this->apiUrl() . "/cab-status?filter=" . $val;
        $resp = $this->get($url);
        $driverstatusJson = Json::decode($resp->getBody(), true);
        if (!empty($driverstatusJson)) {
            foreach ($driverstatusJson as $value) {
                $data[$value['status_id']] = $value['status'];
            }
            $response = ["status" => true, "data" => $data];
        } else {
            $response = ["status" => false];
        }

        return $response;
    }

    public function statusAction() {
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $user_id = $sessionContainer->user_id;

        $id = (!empty(intval($this->params('id')))) ? intval($this->params('id')) : 0;

        $data['company_id'] = $this->config()->getConfig()->company->companyId;
        $data['user_id'] = $id;
        $userListing = $this->userModel->getDriverList($data);
        $curent_status = isset($userListing['data']['responsedata'][0]['driver_status_id']) ? $userListing['data']['responsedata'][0]['driver_status_id'] : 0;

        $form = new ProfilePersonalForm();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();
            $cur_user_id = $postData['user_id'];
            $user_status = isset($postData['status']) ? $postData['status'] : 1;
            $data = ['user_id' => $user_id, 'id' => $cur_user_id, 'user_status' => $user_status];
            $JsonData = $this->userModel->updateUserStatus($data);
            $result = $JsonData['response']['affectedRows'];

            if ($result == 1) {
                $msg = "Status Details Updated Successfully..";
                $this->redirect()->toRoute('usermanagement', ['action' => 'status', 'id' => $cur_user_id]);
                $this->flashMessenger()->addMessage(array('success' => $msg));
            } else {
                $msg = "Status Details Not Updated..";
                $this->redirect()->toRoute('usermanagement', ['action' => 'status', 'id' => $cur_user_id]);
                $this->flashMessenger()->addMessage(array('success' => $msg));
            }
        }
        $userTypeId = $this->userModel->getUserType($id);
        $driverStatus = $this->driverStatus();
        $viewModel = new ViewModel([
            'tab' => 'status',
            'id' => $id,
            'driverStatus' => $driverStatus,
            'curent_status' => $curent_status,
            'form' => $form,
            'userTypeId' => $userTypeId
        ]);
        return $viewModel;
    }

    public function updateUserSatusAction() {

        $request = $this->getRequest();
        if ($request->isPost()) {
            $result = 0;
            $sessionContainer = new Container('userlogin');
            $userTypeId = $sessionContainer->userTypeId;
            $user_id = $sessionContainer->user_id;
            $postData = $request->getPost()->toArray();
            $id = $postData['usertid'];
            $user_status = isset($postData['userstatus']) ? $postData['userstatus'] : 1;

            $data = ['user_id' => $user_id, 'id' => $id, 'user_status' => $user_status];
            $JsonData = $this->userModel->updateUserStatus($data);
            $result = $JsonData['response']['affectedRows'];

            if ($result == 1) {
                $msg = "Status updated successfully !";
            } else {
                $msg = "Status could Not Updated !";
            }
            $status = ['msg' => $msg];
        }


        $viewModel = new JsonModel($status);
        return $viewModel;
    }

    public function addRelationManagerAction() {
        $responseData = [];
        $status = [];
        $request = $this->getRequest();
        if ($request->isPost()) {
            $data = [];
            $sessionContainer = new Container('userlogin');
            $userTypeId = $sessionContainer->userTypeId;
            $user_id = $sessionContainer->user_id;
            $postData = $request->getPost()->toArray();

            $data = [
                'user_id' => $postData['user_id'],
                'staff_id' => $postData['staff_id'],
                'created_by' => $user_id,
                'ip' => $_SERVER['REMOTE_ADDR']
            ];

            $responseData = $this->userModel->relationManager($data);
            if ($responseData['responsedata']['status'] == 'success') {

                $msg = "Added successfully !";
                $status = ['msg' => $msg];
            } else {
                $msg = "could Not added !";
                $status = ['msg' => $msg];
            }
        }


        $viewModel = new JsonModel($status);
        return $viewModel;
    }

    public function documentApprovalAction() {
        $documentListing = [];
        if (intval($this->params('id'))) {
            $id = intval($this->params('id'));
        }
        if (!empty($id)) {
            $documentDetail = $this->userModel->getUserDocument($id,'');
            if (isset($documentDetail['responsedata']) && $documentDetail['responsedata']['status'] == 'success') {
                $documentListing = $documentDetail['responsedata']['data'];
            }
            $url = $this->apiUrl() . "/user/userpersonalinfo?user_id=" . $id;
            $val = $this->get($url);
            $JsonData = $val->getBody();
            $JsonData = Json::decode($JsonData, true);
            //echo'<pre>';print_r($JsonData);die();
            if ($JsonData['responsedata']['status'] == 'success') {
               $userDetails = $JsonData['responsedata']['data'];
            }
        }
        //echo '<pre>';print_r($documentListing);die();
        $viewModel = new ViewModel(['documentListing' => $documentListing, 'userId' => $id, 'userDetails'=>$userDetails]);
        return $viewModel;
    }

    public function updateDocStatusAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];
        $data = $this->getRequest()->getPost();
        //$id = implode(',', $data['selected']);
        $id = $data['selected'];
        $doc_status = $data['status'];
        $userId = $data['user_id'];
        $data = ['user_id' => $user_id, 'id' => $id, 'doc_status' => $doc_status];
        $docStatus = $this->userModel->updateDocStatus($data);
        $documentListing = [];

        $documentDetail = $this->userModel->getUserDocument($userId,'');
        if (isset($documentDetail['responsedata']) && $documentDetail['responsedata']['status'] == 'success') {
            $documentListing = $documentDetail['responsedata']['data'];
        }

        $viewModel = new ViewModel(['documentListing' => $documentListing, 'userId' => $userId]);
        $viewModel->setTemplate('/dashboard/user-management/doc-approval-listing');
        $viewModel->setTerminal(true);
        return $viewModel;
    }

    public function updateDocDefaultStatusAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];
        $data = $this->getRequest()->getPost();
        //$id = implode(',', $data['selected']);
        $id = $data['selected'];
        $doc_status = $data['status'];
        $userId = $data['user_id'];
        $data = ['user_id' => $userId, 'id' => $id, 'doc_default_status' => $doc_status];
        //echo '<pre>';print_r($data);die();
        $docStatus = $this->userModel->updateDocDefaultStatus($data);
        $documentListing = [];

        $documentDetail = $this->userModel->getUserDocument($userId,'');
        if (isset($documentDetail['responsedata']) && $documentDetail['responsedata']['status'] == 'success') {
            $documentListing = $documentDetail['responsedata']['data'];
        }

        $viewModel = new ViewModel(['documentListing' => $documentListing, 'userId' => $userId]);
        $viewModel->setTemplate('/dashboard/user-management/doc-approval-listing');
        $viewModel->setTerminal(true);
        return $viewModel;
    }
}
