<?php

namespace Dashboard\Controller;

use Application\Controller\RestAPIClientController;
use Dashboard\Form\{
    ProfilePersonalForm,
    ProfileCompanyDetailForm,
    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']);
            $form->get('refer_by')->setValue($userDetails['referral_key']);
            $form->get('refer_by')->setAttribute('readonly', 'true');
            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;
                $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;
    }

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

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

    /**
     * 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, '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'])) {
                    $paymentFile    =   $_FILES['fileupload']['name'];
                    $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(),
                ];
                //echo '<pre>';print_r($finalData);die();
                $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();

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

        //Debug::dump($userSpeakLangList);
        //exit;
        $request = $this->getRequest();
        if ($request->isPost()) {
            $postData = $this->getRequest()->getPost()->toArray();
            $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' => $userId,
                    '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);
                //Debug::dump($JsonData);
                //exit;
            } else {
                //echo "Jain";
                //$msg = $form->getMessages();
                //Debug::dump($msg); exit;
            }
        }


        $viewModel = new ViewModel(['form' => $form, 'userPrefDriveCityList' => $userPrefDriveCityList, 'userDutyTypeList' => $userDutyTypeList, 'userPaymentTypeList' => $userPaymentTypeList, 'userSpeakLangList' => $userSpeakLangList, 'userWriteLangList' => $userWriteLangList, 'userShiftLoginList' => $userShiftLoginList, 'userWeekDaysList' => $userWeekDaysList, 'tab' => 'duty-detail']);
        return $viewModel;
    }

    /**
     * Licence Detail...
     * @return ViewModel
     */
    public function licenseDetailAction() {
        $msg = "";
        $msg_color = "";
        $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']);
        }


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



    /**
     * 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 =  $this->config()->getConfig()->base_url->file_path;//$_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;
            $filepath = $uploaddir . $folderpath;
            /* $fileCreate = mkdir($filepath, 0777, true);
              chmod($filepath, 0777); */
            $fileUploadName = $documentName . '.' . $extension;
            $targetPath = $filepath . "/" . $fileUploadName;

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

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

            $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];
            $this->post($url2, $finalData2);


            return array("status" => "success", "fileUploadName" => $base64string);
        }
        return array("status" => "error");
    }
    
    /**
     * Index...
     * @return ViewModel
     */
    public function wishListAction() {
        $msg = "";
        $msg_color = "";
        $sessionContainer = new Container('userlogin');
        $userTypeId = $sessionContainer->userTypeId;
        $userId = $sessionContainer->user_id;
        $viewModel = new ViewModel();
        return $viewModel;
    }

}
