<?php

namespace Dashboard\Controller;

use Application\Controller\RestAPIClientController;
use Dashboard\Form\{
    ProfilePersonalForm,
    ProfileCompanyDetailForm,
    ProfileVehicleDetailForm,
    ProfileChangePasswordForm,
    ProfileBankDetailForm,
    ProfileCreditRequestForm,
    ProfileDutyDetailForm,
    ProfileLicenseDetailForm,
    ProfileOtherDetailForm,
    SecurityForm
};
use Zend\View\Model\{
    ViewModel,
    JsonModel
};
use Zend\Session\Container;
use Zend\Json\Json;
use Zend\Debug\Debug;
use Dashboard\Model\User;
use Dashboard\Model\CommonModel;

class ProfileController extends RestAPIClientController {

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

    /**
     * Index...
     * @return ViewModel
     */
    public function indexAction() {
        $msg = "";
        $msg_color = "";
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;

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

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



        if ($JsonData['responsedata']['status'] == 'success') {
            $userDetails = $JsonData['responsedata']['data'];
            $userDetails['mobile'] = $userDetails['mobile_prefix'].' - '.$userDetails['mobile'];
            $form->setData($userDetails);
            $form->get('dob')->setValue(date('d-m-Y', strtotime($userDetails['dob'])));
            $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');
            }
        }
        if ($request->isPost()) {
            $postData = $request->getPost()->toArray();
            $form->getInputFilter()->get('email_verified')->setRequired(false);
            $form->getInputFilter()->get('phone_verified')->setRequired(false);
            $form->getInputFilter()->get('newsletter_subscription')->setRequired(false);

            if (isset($_FILES['profile_image']['name']) && $_FILES['profile_image']['name'] != '') {
                $arrData = array('file_name' => 'profile_image', 'user_id' => $userId);
                $this->uploadFile($arrData);
            }

            if (isset($_FILES['kyc_upload']['name']) && $_FILES['kyc_upload']['name'] != '') {
                $arrData = array('file_name' => 'kyc_upload', 'user_id' => $userId);
                $this->uploadFile($arrData);
            }

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

                $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'],
                    'refer_by' => $postData['refer_by'],
                    'dob' => date('Y-m-d', strtotime($postData['dob'])),
                    'gender' => $postData['gender'],
                    'address' => $postData['address'],
                    'state' => $postData['state_value'],
                    'city' => $postData['city_value'],
                    'kyc_type' => $postData['kyc_type'],
                    'kyc' => $postData['kyc'],
                    'pincode' => $postData['pincode'],
                    'newsletter_subscription' => $postData['newsletter_subscription'],
                    'user_id' => $userId
                ];
                //$jsonData = Json::encode($finalData);
                // Debug::dump($jsonData);
                // exit;
                //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_color = "green";
                } else {
                    $msg = "Personal Details Not Updated";
                    $msg_color = "red";
                }
            } else {
                $msg = $form->getMessages();
                Debug::dump($msg); die;
            }
        }

        $viewModel = new ViewModel(['form' => $form, 'tab' => 'personal-details', 'msg' => $msg, 'msg_color' => $msg_color, 'personalinfodetail' => $userDetails]);
        return $viewModel;
    }

    /**
     * Company Detail...
     * @return ViewModel
     */
    public function companyDetailAction() {
        $msg = "";
        $msg_color = "";
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;

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

        $url = $this->apiUrl() . "/company/companydetails?user_id=" . $userId;
        $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 = $this->getRequest()->getPost()->toArray();
            $form->setData($postData);
            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' => $userId,
                    'country' => 101,
                    'pincode' => $postData['pincode'],
                    'id' => $userDetails['id']
                ];
                //print_r($finalData); exit;

                $url = $this->apiUrl() . "/company";
                $val = $this->put($url, $finalData);
                $JsonData = $val->getBody();
                $JsonData = Json::decode($JsonData, true);
                //print_r($JsonData); exit;

                if ((!empty($JsonData))) {
                    $msg = "Company Details Updated Successfully";
                    $msg_color = "green";
                } else {
                    $msg = "Company Details Not Updated";
                    $msg_color = "red";
                }
            }
        }

        $viewModel = new ViewModel(['form' => $form, 'tab' => 'company-details', 'msg' => $msg, 'msg_color' => $msg_color]);
        return $viewModel;
    }

    /**
     * Vehicle Detail
     * @return ViewModel
     */
    public function vehicleDetailAction() {
        $msg = "";
        $msg_color = "";
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        $vehicleData = [];
        ProfileVehicleDetailForm::$cabType = $this->getVehicleTypeList();
        ProfileVehicleDetailForm::$ignitionType = $this->getFuelTypeList();
        ProfileVehicleDetailForm::$amenities = $this->getVehicleAmenitiesList();
        ProfileVehicleDetailForm::$modelYear = $this->getModelYearList();
        $request = $this->getRequest();
        $form = new ProfileVehicleDetailForm();

        if (!empty($userId)) {
            $data['user_id'] = $userId;
            $vehicleData = $this->getAllMappingVehicleList($data);
            //echo '<pre>';print_r($vehicleData);die();
            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);
                }
                $form->setData($vehicleData);
            }
        }
        $userTypeId = $this->userModel->getUserType($userId);
        $viewModel = new ViewModel(['form' => $form, 'tab' => 'vehicle-detail', 'vehicleData' => $vehicleData, 'userTypeId' => $userTypeId]);
        return $viewModel;
    }

    /**
     * Change Password...
     * @return ViewModel
     */
    public function changePasswordAction() {
        $success = "";
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;

        //$userId = 10;

        $form = new ProfileChangePasswordForm();
        $request = $this->getRequest();
        if ($request->isPost()) {
            $postData = $this->getRequest()->getPost()->toArray();
            $form->setData($postData);
            if ($form->isValid()) {
                $finalData = [];
                $finalData = [
                    'oldpass' => $postData['old_password'],
                    'newpass' => $postData['new_password'],
                    'cpass' => $postData['confirm_password'],
                    'id' => $userId
                ];
                $response   =   $this->userModel->changePassword($finalData);
                $success = $response['message'];
            }
        }
        $viewModel = new ViewModel(['form' => $form, 'msg_value' => $success, 'tab' => 'change-password']);
        return $viewModel;
    }

    /**
     * Bank Detail...
     * @return ViewModel
     */
    public function bankDetailAction() {
        $msg = "";
        $msg_color = "";
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        //$userId = 3;

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

        $val = '{"where": {"user_id": "' . $userId . '"}}';
        $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();
            $form->setData($postData);

            if ($form->isValid()) {

                $finalData = [];
                $finalData = [
                    'bank_id' => $userDetails['bank_id'],
                    'user_id' => $userId,
                    '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'],
                    'created_date' => date('Y-m-d H:i:s'),
                    'status' => 1,
                    'created_by' => $userId,
                    'modified_by' => $userId,
                    'ip' => $_SERVER['SERVER_ADDR'],
                ];

                $finalData = array_filter($finalData);
                $val = '{"user_id": "' . $userId . '"}';
                $val = rawurlencode($val);
                $url = $this->apiUrl() . "/bank-details/upsertWithWhere?where=" . $val;
                $val = $this->post($url, $finalData);
                $JsonData = $val->getBody();
                $JsonData = Json::decode($JsonData, true);
                //print_r($JsonData); exit;

                if ((!empty($JsonData))) {
                    $msg = "Bank Details Updated Successfully";
                    $msg_color = "green";
                } else {
                    $msg = "Bank Details Not Updated";
                    $msg_color = "red";
                }
            }
        }
        $viewModel = new ViewModel(['form' => $form, 'tab' => 'bank-detail', 'msg' => $msg, 'msg_color' => $msg_color,'bankproof'=>$bankproof, 'id' => $userId,]);
        return $viewModel;
    }

    /**
     * Credit Request...
     * @return ViewModel
     */
    public function creditRequestAction() {
        $msg = "";
        $msg_color = "";
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        $form = new ProfileCreditRequestForm();
        $request = $this->getRequest();

        if ($request->isPost()) {
            $postData = $this->getRequest()->getPost()->toArray();
            $form->setData($postData);


            if ($form->isValid()) {

                $finalData = [];

                if(!empty($_FILES['fileupload']) &&  $_FILES['fileupload']['name']!='') {
                    echo $paymentFile    =   $_FILES['fileupload']['name'];die;
                    $filetype       =   $_FILES['fileupload']['type'];
                    $ext = pathinfo($paymentFile, PATHINFO_EXTENSION);
                    $paymentFile    =   file_get_contents($_FILES['fileupload']['tmp_name']);
                    $paymentFileName = date("d-m-Y") ."-".time()."-"."payment_proof.".$ext;
                    //$paymentFile = 'data:'.$filetype.";base64encode:".base64_encode($paymentFile);
                    $base64File = base64_encode($paymentFile);
                    $basepath = $this->config()->getConfig()->base_url->file_path;
                    $filePath = $basepath. $userId . "/" . $paymentFileName;
                    //$filePath = PUBLIC_PATH . '/upload/' . $userId.'/'.$paymentFileName;
                    $fileData['base64image']= $base64File;
                    $fileData['filepath']= $filePath;
                    $this->CommonModel->uploadimageapi($fileData);
                }

                $finalData = [
                    'user_id' => $userId,
                    '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(),
                ];
                
                $finalData = array_filter($finalData);
                $url = $this->apiUrl() . "/driver-payment";
                $val = $this->post($url, $finalData);
                $JsonData = $val->getBody();
                $JsonData = Json::decode($JsonData, true);


                if ((!empty($JsonData)) && (!isset($JsonData['error']))) {
                    $msg = "Credit Request Insert Successfully";
                    $msg_color = "green";
                } else {
                    $msg = "Credit Request Not Inserted";
                    $msg_color = "red";
                }
                $this->redirect()->toRoute('profile', ['action' => 'credit-request']);
                $this->flashMessenger()->addMessage(array('success' => $msg));
            } else {

                //echo'<pre>';print_r($form->getMessages());die();
            }
        }
        $viewModel = new ViewModel(['form' => $form, 'tab' => 'credit-request', 'msg' => $msg, 'msg_color' => $msg_color]);
        return $viewModel;
    }

    /**
     * Payment Detail...
     * @return ViewModel
     */
    public function dutyDetailAction() {
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_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();



        //Debug::dump($userPaymentTypeList);
        //exit;
        $request = $this->getRequest();
        if ($request->isPost()) {
            $postData = $this->getRequest()->getPost()->toArray();
            $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']),
                    'working_shift' => implode(",", $postData['shift_of_login']),
                    'speak' => implode(",", $postData['language_speak']),
                    'write' => implode(",", $postData['language_write']),
                    'week_off' => implode(",", $postData['week_days']),
                    'user_id' => $userId,
                    'created_date' => date('Y-m-d'),
                    'created_by' => $userId
                ];
                //Debug::dump($finalData);
                //exit;
                $url = $this->apiUrl() . "/user/addDutyDetail";
                $val = $this->post($url, $finalData);
                $JsonData = $val->getBody();
                $JsonData = Json::decode($JsonData, true);
                //Debug::dump($JsonData);
                //exit;
                $this->redirect()->toRoute('profile', ['action' => 'index']);
            } else {
                //echo "Jain";
                //$msg = $form->getMessages();
                //Debug::dump($msg); exit;
            }
        }

        $userPrefDriveCityList = $this->userModel->getUserprefDriveCity($userId);
        $userDutyTypeList = $this->userModel->getUserdutyTypeList($userId);
        $userPaymentTypeList = $this->userModel->getUserpaymentTypeList($userId);
        $userSpeakLangList = $this->userModel->getUserSpeakLanguageList($userId);
        $userWriteLangList = $this->userModel->getUserWriteLanguageList($userId);
        $userShiftLoginList = $this->userModel->getUserShiftLoginList($userId);
        $userWeekDaysList = $this->userModel->getUserWeekDaysList($userId);

        if($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',
            'city_name_string'=>$city_name_string,
            'city_ids'=>$city_ids,
            ]);
        return $viewModel;
    }

    /**
     * Licence Detail...
     * @return ViewModel
     */
    public function licenseDetailAction() {
        $msg = "";
        $msg_color = "";
        $getDocument = '';
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;

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

        $val = '{"where": {"user_id": "' . $userId . '"}}';
        $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];
            $url = $this->apiUrl() . "/state/" . $userDetails['license_state'];
            $resp = $this->get($url);
            $stateJsonData = Json::decode($resp->getBody(), true);
            $form->setData($userDetails);
            $form->get('license_state')->setValue(isset($stateJsonData['name']) ? $stateJsonData['name'] : '');
            $form->get('license_state_value')->setValue($userDetails['license_state']);
        }

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

        if ($request->isPost()) {
            $postData = $this->getRequest()->getPost()->toArray();
            $form->setData($postData);

            if ($form->isValid()) {

                $finalData = [];
                $finalData = [
                    'license_state' => $postData['license_state_value'],
                    'driving_license_no' => $postData['driving_license_no'],
                    //'license_proof' => $licenseProofImageName,
                    'license_validity' => $postData['license_validity'],
                    'gps' => $postData['gps'],
                    'pancard_no' => $postData['pancard_no'],
                    //'pancard_proof' => $pancardProofImageName,
                    //'police_report' => $policeProofImageName,
                    //'audit_report' => $auditProofImageName,
                    'user_id' => $userId,
                    'id' => $userDetails['id']
                ];

                //$val = '{"id": "' . $userDetails['id'] . '"}';
                $finalData = array_filter($finalData);
                $val = '{"user_id": "' . $userId . '"}';
                $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_color = "green";
                } else {
                    $msg = "License Details Not Updated";
                    $msg_color = "red";
                }
            } else {
                $aa = $form->getMessages();
            }
        }

        $viewModel = new ViewModel(['form' => $form, 'tab' => 'license-detail', 'msg' => $msg, 'msg_color' => $msg_color,'getdoc'=>$getDocument,'id' => $userId]);
        return $viewModel;
    }
    
    /**
     * Change Password...
     * @return ViewModel
     */
    public function securityAction() {
        $success = "";
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;

        //$userId = 10;

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

        $url = $this->apiUrl() . "/user/userpersonalinfo?user_id=" . $userId;
        $val = $this->get($url);
        $JsonData = $val->getBody();
        $JsonData = Json::decode($JsonData, true);
        if ($JsonData['responsedata']['status'] == 'success') {
            $userDetails = $JsonData['responsedata']['data'];
            $otp_status =   $userDetails['login_otp_status'];

        }
        if ($request->isPost()) {
            $postData = $this->getRequest()->getPost()->toArray();
                $finalData = [];
                $finalData = [
                    'login_otp_status' => $postData['login_otp_status'],
                    'user_id' => $userId
                ];
                $url = $this->apiUrl() . "/user/updatepersonalinfo";
                $val = $this->post($url, $finalData);
                $resp = $val->getBody();
                $resp = Json::decode($resp, true);
                $success = $resp['response']['message'];
                $url = $this->apiUrl() . "/user/userpersonalinfo?user_id=" . $userId;
                $val = $this->get($url);
                $JsonData = $val->getBody();
                $JsonData = Json::decode($JsonData, true);
                if ($JsonData['responsedata']['status'] == 'success') {
                $userDetails = $JsonData['responsedata']['data'];
                $otp_status =   $userDetails['login_otp_status'];
            }
        }
        $viewModel = new ViewModel(['form' => $form, 'msg_value' => $success, 'tab' => 'security', 'otp_status'=>$otp_status]);
        return $viewModel;
    }

    public function otherDetailAction() {
        $msg = "";
        $msg_color = "";
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        $form = new ProfileOtherDetailForm();
        $request = $this->getRequest();

        $val = '{"where": {"user_id": "' . $userId . '"}}';
        $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();
            $form->setData($postData);
            if ($form->isValid()) {
                $finalData = [];
                $finalData = [
                    'route_know' => $postData['route_know'],
                    'zone' => $postData['zone'],
                    'user_id' => $userId,
                    'id' => $userDetails['id']
                ];

                $finalData = array_filter($finalData);
                $val = '{"user_id": "' . $userId . '"}';
                $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_color = "green";
                } else {
                    $msg = "Other Details Not Updated";
                    $msg_color = "red";
                }
            }
        }

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



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

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

        $url = $this->apiAdminUrl() . "user/showlicencedetail/?&user_id=" . $userId;
        $val = $this->get($url, $finalData);
        $JsonData = $val->getBody();
        $JsonData = Json::decode($JsonData, true);


        if (($request->isXmlHttpRequest())) {


            if (!empty($JsonData[result][0])) {


                $userDetails = $JsonData[result][0];
                $form->setData($userDetails);
            }

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


            if ($request->isPost()) {

                $postData = array_merge_recursive(
                        $this->getRequest()->getPost()->toArray(), $this->getRequest()->getFiles()->toArray()
                );
                $form->setData($postData);


                if ($form->isValid()) {

                    $fileNameLicensecProof = $postData['license_proof']['name'];
                    $fileTmpNameLicenseProof = $postData['license_proof']['tmp_name'];
                    $licenseProofImageName = date("d-m-Y") . "-" . time() . $$fileNameLicensecProof;
                    $targetPath = "public/upload/license/licenseproof/" . $licenseProofImageName;
                    move_uploaded_file($fileTmpNameLicenseProof, $targetPath);

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

                    $fileNamepoliceProof = $postData['police_proof']['name'];
                    $fileTmpNamePoliceProof = $postData['pancard_proof']['tmp_name'];
                    $policeProofImageName = date("d-m-Y") . "-" . time() . $fileNamepoliceProof;
                    $targetPath = "public/upload/license/policeproof/" . $policeProofImageName;
                    move_uploaded_file($fileTmpNamePoliceProof, $targetPath);


                    $fileNameauditProof = $postData['audit_proof']['name'];
                    $fileTmpNameAuditProof = $postData['audit_proof']['tmp_name'];
                    $auditProofImageName = date("d-m-Y") . "-" . time() . $fileNameauditProof;
                    $targetPath = "public/upload/license/auditproof/" . $auditProofImageName;
                    move_uploaded_file($fileTmpNameAuditProof, $targetPath);

                    $finalData = [];
                    $finalData = [
                        'license_state' => $postData['license_state'],
                        'license_no' => $postData['driving_license_no'],
                        'license_proof' => $licenseProofImageName,
                        'license_validity' => $postData['license_validity'],
                        'gps_device_no' => $postData['gps'],
                        'pancard' => $postData['pancard_no'],
                        'pancard_proof' => $pancardProofImageName,
                        'police_report' => $policeProofImageName,
                        'audit_report' => $auditProofImageName,
                        'user_id' => $userId
                    ];

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

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


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


                        $this->redirect()->toRoute('profile', ['action' => 'index']);
                    } else {

                        echo "some error";
                        die;
                    }
//
                } else {
                    echo "php";
                    Debug::dump($postData);
                    exit;
                }
                $viewModel = new ViewModel(['form' => $form]);
            }
        }
        return $viewModel;
        $request = $this->getRequest();
        $form = new ProfileLicenseDetailForm();
        $typeSelect = 'select';
        $typeSubmit = 'submit';

        //Call API here...
        $licenseData = [
            'license_state' => 'haryana',
            'badge_license_number' => 'df456',
            'license_proof' => 'license.jpg',
            'license_validity' => '12 months',
            'insurance_validity' => 'one year',
            'gps_device_number' => '1234567',
            'pancard' => '123456789',
            'pancard_proof' => 'pan.jpg',
            'police_report' => 'p-report',
            'audit_report' => 'audit.jpg'
        ];

        if (($request->isXmlHttpRequest() && $typeSubmit == $request->getPost()['submit_type'])) {
            //echo 'submit';die;
            //file start...
            $postFile = $this->getRequest()->getFiles()->toArray();
            $fileNameLicenseProof = $postFile['license_proof']['name'];
            $fileTmpNameLicenseProof = $postFile['license_proof']['tmp_name'];
            $licenseProofImageName = date("d-m-Y") . "-" . time() . $fileNameLicenseProof;
            //$targetpath = EMAIL_IMAGE_PATH.$filename;
            $targetPath = "public/upload/profile/licenseproof/" . $licenseProofImageName;
            move_uploaded_file($fileTmpNameLicenseProof, $targetPath);

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

            $fileNameAuditReport = $postFile['audit_report']['name'];
            $fileTmpNameAuditReport = $postFile['audit_report']['tmp_name'];
            $auditReportProofImageName = date("d-m-Y") . "-" . time() . $fileNameAuditReport;
            //$targetpath = EMAIL_IMAGE_PATH.$filename;
            $targetPath = "public/upload/profile/auditreport/" . $auditReportProofImageName;
            move_uploaded_file($fileTmpNameAuditReport, $targetPath);
            //file end...

            $postData = [
                'license_state' => $request->getPost()['license_state'],
                'badge_license_number' => $request->getPost()['badge_license_number'],
                'license_proof' => $licenseProofImageName,
                'license_validity' => $request->getPost()['license_validity'],
                'insurance_validity' => $request->getPost()['insurance_validity'],
                'gps_device_number' => $request->getPost()['gps_device_number'],
                'pancard' => $request->getPost()['pancard'],
                'pancard_proof' => $pancardProofImageName,
                'police_report' => $request->getPost()['police_report'],
                'audit_report' => $auditReportProofImageName
            ];
            //$jsonData = json_encode($postData);
            //print_r($jsonData);die;
            //save data here...
            //Call API here...

            $msg = 'Successfully Saved';
            $form->setData($postData);
            $viewModel = new ViewModel(['form' => $form, 'msg' => $msg]);
            $viewModel->setTemplate('/profile/license-detail');
            $viewModel->setTerminal(true);
            return $viewModel;
            exit;
        } elseif (($request->isXmlHttpRequest() && $typeSelect == $request->getPost()['type'])) {
            //echo 'select';die;
            $form->setData($licenseData);
        }

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


    /**
     * State List...
     * @return ViewModel
     */
    public function stateListAction() {
        $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;
    }

    /**
     * City List...
     * @return ViewModel
     */
    public function cityListAction() {
        $request = $this->getRequest();
        $postdata = $request->getPost();
        $term = $postdata['term'];
        $state = $postdata['state'];
        $val = '{"where":{"and": [{"state_id": "' . $state . '"},{"name": {"like": "' . $term . '%"}}]},"limit":10}';
        $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[] = ["label" => $value['name'], "value" => $value['id']];
            }
        } else {
            $data[] = ["label" => 'Not Exist'];
        }

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

    public function allCityListAction() {
        $request = $this->getRequest();
        $postdata = $request->getPost();
        $term = $postdata['term'];
        $val = '{"where": {"name": {"like": "' . $term . '%"}},"limit":10}';
        $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[] = ["label" => $value['name'], "value" => $value['id']];
            }
        } else {
            $data[] = ["label" => 'Not Exist'];
        }

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

    /**
     * Check Already Exist Password...
     * @return ViewModel
     */
    public function checkAlreadyExistPasswordAction() {
        $request = $this->getRequest();
        if ($request->isPost()) {
            $fieldName = $request->getPost("id");
            $value = $request->getPost("value");
            //call API here...
            $size = 0;
        }

        if ($size == 0) {
            return new JsonModel(["id" => $fieldName, "message" => "<p style='color:green;'>Available</p>"]);
        } else {
            return new JsonModel(["id" => $fieldName, "message" => "<p style='color:red;'>Not Matched</p>"]);
        }

        exit();
    }

    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 uploadFile($arrVal = array()) {

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

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

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

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

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

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

            $file = '/upload/';

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

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

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

            $this->CommonModel->uploadimageapi($finalData);
            //move_uploaded_file($fileTmpNameOfficeAdd, $targetPath);

            $fileUploadName = $base64string;
            $url2 = $this->apiUrl() . "/user/uploadDocument";
            $finalData2 = ['user_id' => $userId, 'doc_type_id' => $docTypeId, 'doc_file_upload' => $fileUploadName,'status'=>1];
            $this->post($url2, $finalData2);


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

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

}
