<?php

namespace Dashboard\Controller;

use Application\Controller\RestAPIClientController;
use Dashboard\Form\{
    AddStaffForm
};
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;

class StaffController extends RestAPIClientController {

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

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

    /**
     * User Management Home
     * @return ViewModel
     */
    public function indexAction() {
        $result = [];
        $userstatus = [];
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];
        $user_type_id = 11;
        if ($user_id != '') {
            $data = array('user_id' => $user_id, 'user_type_id' => $user_type_id);
            $resposne = $this->userModel->getUserStaff($data);
            //echo '<pre>';print_r($resposne);die();

            if ($resposne['responsedata']['status']=="success") {
                $result = $resposne['responsedata']['data'];
            }
        }
        //echo'<pre>';print_r($result);die();
        $userstatus=$this->userStatus();
        $viewModel = new ViewModel(['result' => $result,'userstatus'=>$userstatus]);
        return $viewModel;
    }

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

        $url = $this->apiUrl() . "/role-assign-module/getAllRoleModules?user_id=" . $user_id;
        $val = $this->get($url);
        $JsonData = $val->getBody();
        $JsonData = Json::decode($JsonData, true);

        if ((!empty($JsonData))) {

            foreach ($JsonData as $key => $value) {
                foreach ($value as $key2 => $value2) {
                    $roletype [$value2['role_id']] = $value2['role_name'];
                }
            }
        }

        $request = $this->getRequest();
        $roleType = $this->config()->getConfig()->userRoleType->staff;
        AddStaffForm::$usertype = $this->userModel->getUserTypeList($roleType);
        AddStaffForm::$department = $this->CommonModel->getDepartmentByuserId($user_id);
        AddStaffForm::$countryprefix = $this->userModel->getCountryCodePrefix();
        $form = new AddStaffForm();

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

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

            if ($form->isValid()) {
                $rand = substr(rand(), 0, 4);
                $password = '123456';
                $data = [
                    'user_type_id' => 11,
                    'company_id' => $companyId,
                    'role_id' => $postData['user_role'],
                    'department_id' => $postData['department'],
                    'firstName' => trim($postData['first_name']),
                    'lastName' => trim($postData['last_name']),
                    'email' => trim($postData['email']),
                    'prefix_contact_no' => trim($postData['prefix_contact_no']),
                    'nationality' => trim($postData['nationality_value']),
                    'mobile' => trim($postData['contact_no']),
                    'gender' => trim($postData['gender']),
                    'password' => $password,
                    'parent_id' => $user_id,
                    'signup_status' => 10,
                    'created_date' => date('Y-m-d h:i:s'),
                    'created_by' => $user_id,
                    'user_grade' => $this->config()->getConfig()->userGrade->defaultGrade,
                ];

                $resp = $this->userModel->addstaff($data);
                //echo'<pre>';print_r($resp);//die();
                if ($resp['responsedata']['status'] == 1) {

                    $assigne_role_id = $resp['responsedata']['assigne_role_id'];
                    $finalData = [];
                    $finalData = [
                        'assign_role_id' => $assigne_role_id,
                        'moduleids' => implode(',', $postData['modulenameid']),
                        'created_by' => $user_id,
                        'created_date' => date('Y-m-d h:i:s')
                    ];
                    //echo '<pre>';print_r($finalData);die();
                    $url = $this->apiUrl() . "/role-assign-module/userassignmodule";

                    $val = $this->post($url, $finalData);
                    $JsonData = $val->getBody();
                    $JsonData = Json::decode($JsonData, true);


                    if ((!empty($JsonData)) && !isset($JsonData['error'])) {
                        $msg = "Added Successfully..";

                        $this->redirect()->toRoute('staff', ['action' => 'index']);
                        $this->flashMessenger()->addMessage(array('success' => $msg));
                    } else {
                        $msg = "Could Not Added!..";
                        $this->redirect()->toRoute('staff', ['action' => 'index']);
                        $this->flashMessenger()->addMessage(array('danger' => $msg));
                    }

                    //Pt End
                }
            }
        }

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

    public function editStaffAction() {
        $sessionUser = new Container('userlogin');
        $loginData = $sessionUser->userData;
        $user_id = $loginData['user_id'];

        $roletype = [];
        $id = $this->params()->fromQuery('id');

        $url = $this->apiUrl() . "/role-assign-module/getAllRoleModules?user_id=" . $user_id;
        $val = $this->get($url);
        $JsonData = $val->getBody();
        $JsonData = Json::decode($JsonData, true);

        if ((!empty($JsonData))) {

            foreach ($JsonData as $key => $value) {
                foreach ($value as $key2 => $value2) {
                    $roletype [$value2['role_id']] = $value2['role_name'];
                }
            }
        }

        $request = $this->getRequest();

        AddStaffForm::$usertype = $roletype;
        AddStaffForm::$department = $this->CommonModel->getDepartmentByuserId($user_id);
        $form = new AddStaffForm();
        if (!empty($id)) {
            $url = $this->apiUrl() . "/user/getuserstaff?user_id=$id";
            $resp = $this->get($url);
            $result = Json::decode($resp->getBody(), true);
            $response = $result['responsedata']['data'][0];
            $form->setData($response);
        }

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

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

            if ($form->isValid()) {
                $data = [
                    'user_id' => $postData['user_id'],
                    'role_id' => $postData['user_role'],
                    'department_id' => $postData['department'],
                    'first_name' => trim($postData['first_name']),
                    'last_name' => trim($postData['last_name']),
                    'email' => trim($postData['email']),
                    'mobile' => trim($postData['contact_no']),
                    'gender' => trim($postData['gender']),
                    'assign_role_id' => $postData['assign_role_id'],
                    'moduleids' => implode(',', $postData['modulenameid']),
                    'modified_by' => $user_id,
                    'created_by' => $user_id,
                    'created_date' => date('Y-m-d h:i:s')
                ];

                $resp = $this->userModel->updatestaff($data);
               //echo'<pre>';print_r($resp);die();
                if (!empty($resp) && $resp['response']['status'] == 'success') {

                    if ((!empty($JsonData)) && !isset($JsonData['error'])) {
                        $msg = "Added Successfully..";

                        $this->redirect()->toRoute('staff', ['action' => 'index']);
                        $this->flashMessenger()->addMessage(array('success' => $msg));
                    } else {
                        $msg = "Could Not Added!..";
                        $this->redirect()->toRoute('staff', ['action' => 'index']);
                        $this->flashMessenger()->addMessage(array('danger' => $msg));
                    }

                }
            }
        }

        $viewModel = new ViewModel(['form' => $form, 'response' => $response, 'user_type_id'=>$loginData['user_type_id']]);
        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() {
        $data = [];
        UserManagementSearchForm::$country = $this->userModel->getCountryList();
        UserManagementSearchForm::$usertype = $this->userModel->getUserTypeList();
        $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['status'],
                ];
                $data = array_filter($data);
                //echo '<pre>';print_r($data);die();
            }
        }

        $data['user_type_id'] = '3';
        $data['company_id'] = $this->config()->getConfig()->company->companyId;
        //echo '<pre>';print_r($data);die();
        $userListing = $this->userModel->getDriverList($data);
        //echo '<pre>';print_r($userListing);die();
        $viewModel = new ViewModel(['form' => $form, 'userListing' => $userListing['data']['responsedata'], 'action' => 'driver']);
        return $viewModel;
    }

    /**
     * Vendor Listing
     * @return ViewModel
     */
    public function vendorAction() {
        $data = [];
        UserManagementSearchForm::$country = $this->userModel->getCountryList();
        UserManagementSearchForm::$usertype = $this->userModel->getUserTypeList();
        $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['status'],
                ];
                $data = array_filter($data);
                //echo '<pre>';print_r($data);die();
            }
        }

        $data['user_type_id'] = '4,7';
        $data['company_id'] = $this->config()->getConfig()->company->companyId;
        $userListing = $this->userModel->getUserList($data);
        //echo '<pre>';print_r($userListing);die();
        $viewModel = new ViewModel(['form' => $form, 'userListing' => $userListing['data']['responsedata'], 'action' => 'vendor']);
        return $viewModel;
    }

    /**
     * Personal Detail
     * @return ViewModel
     */
    public function personalDetailAction() {
        $msg = "";
        $msg_class = "";
        $refer_by = "";
        $referral_key = "";
        $email_verified = "";
        $phone_verified = "";
        $id = "";

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

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


            if ($JsonData['responsedata']['status'] == 'success') {
                $userDetails = $JsonData['responsedata']['data'];
                $dob = date('d/m/Y', strtotime($userDetails['dob']));
                $userDetails['dob'] = $dob;

                $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');
                } else if ($userDetails['mobile'] != "") {
                    $form->get('mobile')->setAttribute('readonly', 'true');
                }
            }
        }
        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');
            } else 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'],
                ];


                $url = $this->apiUrl() . "/user/updatepersonalinfo";
                $val = $this->post($url, $finalData);
                $JsonData = $val->getBody();
                $JsonData = Json::decode($JsonData, true);
                //echo '<pre>';print_r($JsonData);die();
                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]);

        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'));
        }
        //die;
        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();
            }
        }
        $viewModel = new ViewModel(['form' => $form, 'tab' => 'company-detail', 'id' => $id, 'msg' => $msg, 'msg_class' => $msg_class]);
        return $viewModel;
    }

    /**
     * Vehicle Detail
     * @return ViewModel
     */
    public function vehicleDetailAction() {
        ProfileVehicleDetailForm::$cabType = $this->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);
            //echo '<pre>';print_r($vehicleData[0]);//die();
            //echo $vehicleData[0]['vehicle_owner_type']; //die;
            if ($vehicleData[0]['vehicle_owner_type'] == "Owned") {
                $form->get('vehicle_attach_selected')->setValue(1);
            }
            if ($vehicleData[0]['vehicle_owner_type'] == "Attached") {
                $form->get('vehicle_owned_selected')->setValue(0);
            }
        }

        $viewModel = new ViewModel(['form' => $form, 'tab' => 'vehicle-detail', 'id' => $id, 'vehicleData' => $vehicleData[0]]);
        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->setData($postData);
            $id = intval($postData['user_id']);
            if ($form->isValid()) {
                $finalData = [];
                $finalData = [
                    'password' => md5($postData['new_password']),
                    'id' => $postData['user_id']
                ];
                $url = $this->apiUrl() . "/user/changePassword";
                $val = $this->put($url, $finalData);
                $JsonData = $val->getBody();
                $JsonData = Json::decode($JsonData, true);

                if ($JsonData['response']['affectedRows'] == true) {
                    $msg = "Passowrd changed Successfully";
                    $msg_class = "success";
                } else {
                    $msg = "Passowrd not changed";
                    $msg_class = "danger";
                }
            }
        }
        $viewModel = new ViewModel(['form' => $form, 'tab' => 'change-password', 'id' => $id, 'msg' => $msg, 'msg_class' => $msg_class]);
        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];
                $form->setData($userDetails);
            }
        }

        if ($request->isPost()) {
            $postData = $this->getRequest()->getPost()->toArray();
            $id = intval($postData['user_id']);
            $form->setData($postData);
            if ($form->isValid()) {
                $finalData = [];
                $finalData = [
                    'bank_id' => $postData['bank_id'],
                    'user_id' => $postData['user_id'],
                    'name' => $postData['name'],
                    'address' => $postData['address'],
                    'ifsc_code' => $postData['ifsc_code'],
                    'ac_no' => $postData['ac_no'],
                    'ac_holder_name' => $postData['ac_holder_name'],
                    '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');
                }


                $url = $this->apiUrl() . "/bank-details";
                $val = $this->put($url, $finalData);
                $JsonData = $val->getBody();
                $JsonData = Json::decode($JsonData, true);
                //echo '<pre>';print_r($JsonData);die();
                if (!empty($JsonData)) {
                    $msg = "Bank Details Updated Successfully";
                    $msg_class = "success";
                } else {
                    $msg = "Bank Details Not Updated";
                    $msg_class = "danger";
                }
            }
        }
        $viewModel = new ViewModel(['form' => $form, 'tab' => 'bank-detail', 'id' => $id, 'msg' => $msg, 'msg_class' => $msg_class]);
        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'));
        }
        $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 = [];
                $finalData = [
                    'driver_id' => $postData['user_id'],
                    'deposit_date' => $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'],
                    'payment_ref_no' => $this->generatePaymentRefNo(),
                ];
                $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)) && (!$JsonData['error'])) {
                    $msg = "Credit Request Insert Successfully";
                    $msg_class = "success";
                } else {
                    $msg = "Credit Request Not Insert";
                    $msg_class = "danger";
                }
            }
        }
        $viewModel = new ViewModel(['form' => $form, 'tab' => 'credit-request', 'msg' => $msg, 'msg_class' => $msg_class, 'id' => $id]);
        return $viewModel;
    }

    /**
     * Duty Payment Detail...
     * @return ViewModel
     */
    public function dutyDetailAction() {
        $msg = "";
        $msg_class = "";
        $id = "";
        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 = [];
                $finalData = [
                    'booking_type' => implode(",", $postData['duty_type']),
                    'payment_cash' => implode(",", $postData['payment_type']),
                    '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')
                ];
                //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)) && (!$JsonData['error'])) {
                    $msg = "Duty Details Updated Successfully";
                    $msg_class = "success";
                } else {
                    $msg = "Duty Details Not Updated";
                    $msg_class = "danger";
                }
            } else {
                //echo "Jain";
                //$msg = $form->getMessages();
                //Debug::dump($msg); exit;
            }
        }

        $userPrefDriveCityList = $this->userModel->getUserprefDriveCityList($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);

        $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
        ]);
        return $viewModel;
    }

    /**
     * Licence Detail...
     * @return ViewModel
     */
    public function licenseDetailAction() {
        $msg = "";
        $msg_class = "";
        $id = "";
        $form = new ProfileLicenseDetailForm();
        if (intval($this->params('id'))) {
            $id = intval($this->params('id'));
        }
        $form->get('user_id')->setValue($id);
        $request = $this->getRequest();

        if (!empty($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);
                $state_name = $this->userModel->getStateId($userDetails['license_state']);
                $form->get('license_state')->setValue($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'] . '"}';
                $val = rawurlencode($val);
                $url = $this->apiUrl() . "/driver/update?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";
                }
            }
        }

        $viewModel = new ViewModel(['form' => $form, 'tab' => 'license-detail', 'msg' => $msg, 'msg_class' => $msg_class, 'id' => $id]);
        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']
                ];
                $val = '{"id": "' . $postData['id'] . '"}';
                $val = rawurlencode($val);
                $url = $this->apiUrl() . "/driver/update?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";
                }
            }
        }

        $viewModel = new ViewModel([
            'form' => $form,
            'tab' => 'other-detail',
            'id' => $id,
            'msg' => $msg,
            'msg_class' => $msg_class,
        ]);
        return $viewModel;
    }

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

     public function userStatus() {
        $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;
    }



}
