Your IP : 216.73.216.79


Current Path : /var/www/html/mydlvsacc/frontend/controllers/
Upload File :
Current File : /var/www/html/mydlvsacc/frontend/controllers/SiteController.php

<?php
namespace frontend\controllers;

use Yii;
use common\models\LoginForm;
use frontend\models\PasswordResetRequestForm;
use frontend\models\ResetPasswordForm;
use frontend\models\SignupForm;
use frontend\models\ContactForm;
use yii\base\InvalidParamException;
use yii\web\BadRequestHttpException;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use frontend\models\application\DlsAiApplicationid;
use frontend\models\application\DlsAiApplication;
use frontend\models\application\DlsAiDirectorowner;
use frontend\models\application\DlsAiAuthorizeduser;
use backend\models\application\AiAppstatus;
use frontend\models\application\DlsAiDocupload;
use Hashids\Hashids;
use backend\models\Template;
use backend\models\Staff;
use backend\models\frontenduser\FrontendUser;
use backend\models\agents\AgentTransfer;

/**
 * Site controller
 */
class SiteController extends Controller
{
    /*constant*/
    const ID_EMAIL_NOTIFIKASI = 12;
    const ID_EMAIL_NOTIFIKASI_ADMIN = 14;

    public $enableCsrfValidation = false;

    public $csrfwhitelist = [
        'save-app-info',
        'save-app-director',
        'save-app-authorized-officer',
        'delete-director',
        'delete-officer',
    ];

    /**
     * @inheritdoc
     */
    public function beforeAction($action)
    {            
        if (in_array($action->id, $this->csrfwhitelist)) {
            $this->enableCsrfValidation = false;
        }

        return parent::beforeAction($action);
    }

    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'only' => ['logout', 'signup'],
                'rules' => [
                    [
                        'actions' => ['signup', 'generateid', 'save-app-info', 'save-app-director','logout','get-form-data', 'get-director-data','get-appstatus', 'get-doc-upload-data', 'save-app-authorize-officer','get-authorized-officer-data', 'delete-officer','get-approve-operator-code','forgetpass','changepass'],
                        'allow' => true,
                        'roles' => ['?'],
                    ],
                    [
                        'actions' => ['logout'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    // 'logout' => ['post'],
                    'save-app-info' => ['post'],
                    'save-app-director' => ['post']
                ],
            ],
        ];
    }

    /*field map for input name and db col*/
    private function fieldmap(){
        return [
            "kategori"                    =>  "aiap_transportcategory",
            "jenis_orang"                 =>  "aiap_persontype",
            "mod_pengangkutan"            =>  "aiap_transportationmode",
            "no_syarikat_pemohon"         =>  "aiap_businessno",
            "nama_pemohon"                =>  "aiap_applicantname",
            "nama_pengendali"             =>  "aiap_operatorname",
            "kod_pengendali"              =>  "aiap_operatorcode",
            "negara_asal_pengendali"      =>  "aiap_countryorigin",
            "jenis_alamat"                =>  "aiap_businessaddresstype",
            "alamat_1_perniagaan"         =>  "aiap_businessaddress1",
            "alamat_2_perniagaan"         =>  "aiap_businessaddress2",
            "alamat_3_perniagaan"         =>  "aiap_businessaddress3",
            "alamat_poskod_perniagaan"    =>  "aiap_businessposcode",
            "alamat_negeri_perniagaan"    =>  "aiap_businessstate",
            "alamat_negara_perniagaan"    =>  "aiap_businesscountry",
            "jenis_alamat_1"              =>  "aiap_correspondencetype",
            "alamat_11_perniagaan"        =>  "aiap_correspondenceaddress1",
            "alamat_12_perniagaan"        =>  "aiap_correspondenceaddress2",
            "alamat_13_perniagaan"        =>  "aiap_correspondenceaddress3",
            "alamat_poskod_perniagaan_1"  =>  "aiap_correspondenceposcode",
            "alamat_negeri_perniagaan_1"  =>  "aiap_correspondencestate",
            "alamat_negara_perniagaan_1"  =>  "aiap_correspondencecountry",
            "nama_perdagangan_pengendali" =>  "aiap_operatortradename",
            "no_telefon"                  =>  "aiap_telno",
            "no_telefon_code"             =>  "aiap_telnocode",
            "no_fax"                      =>  "aiap_faxno",
            "no_fax_code"                 =>  "aiap_faxnocode",
            "alamat_emel"                 =>  "aiap_email",
            "ahli_persatuan"              =>  "aiap_memberassociate",
            "cukai_pendapatan"            =>  "aiap_incometax",
            "tarikh_mula"                 =>  "aiap_datecommencement",
            "bilangan_orang_asean"        =>  "aiap_estimatepersonasean",
            "bilangan_orang_lain"         =>  "aiap_estimatepersonnotasean",
            "nama_akaun"                  =>  "aiap_acchaldername",
            "nama_bank"                   =>  "aiap_bankname",
            "jenis_akaun"                 =>  "aiap_accounttype",
            "nombor_swift"                =>  "aiap_swiftcode",
            // "alamat_bank"                 =>  "aiap_bankaddress",
            "alamat_bank_rumah"           =>  "aiap_bankaddress1",
            "alamat_bank_taman"           =>  "aiap_bankaddress2",
            "alamat_bank_bandar"          =>  "aiap_bankaddress3",
            "alamat_bank_poskod"          =>  "aiap_bankaddresspostcode",
            "alamat_bank_negeri"          =>  "aiap_bankaddressstate",
            "alamat_bank_negara"          =>  "aiap_bankaddresscountry",
            "nombor_akaun"                =>  "aiap_noaccount",
            "hubungi_nama"                =>  "aiap_contactname",
            "hubungi_tel"                 =>  "aiap_contacttelno",
            "hubungi_tel_code"            =>  "aiap_contacttelnocode",
            "hubungi_fax"                 =>  "aiap_contactfaxno",
            "hubungi_fax_code"            =>  "aiap_contactfaxnocode",
            "hubungi_emel"                =>  "aiap_contactemail",
            "hubungi_jawatan"             =>  "aiap_contactdesignation",
            "akuan_tarikh"                =>  "aiap_declarationdate",
            "akuan_nama"                  =>  "aiap_nameofapplicant",
            "akuan_ic"                    =>  "aiap_icofapplicant",
            "akuan_jawatan"				  =>  "aiap_designationofapplicant",
            "akuan_warganegara"           =>  "aiap_nationalityofapplicant",
            "alamat_11_pengendali"		  =>  "aiap_operatoraddress1",
            "alamat_12_pengendali"		  =>  "aiap_operatoraddress2",
            "alamat_13_pengendali"		  =>  "aiap_operatoraddress3",
            "alamat_poskod_pengendali"	  =>  "aiap_operatorpostcode",
            "alamat_negeri_pengendali"	  =>  "aiap_operatorstate",
            "alamat_negara_pengendali"	  =>  "aiap_operatorcountry",
            "jenis_alamat_2"	  		  =>  "aiap_operatoraddresstype",
            "hubungi_nama_surname"		  =>  "aiap_contactsurname",
            "nama_airport"                =>  "aiap_primarydepaturecode",
        ];
    }

    /**
     * @inheritdoc
     */
    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    /**
     * Displays homepage.
     *
     * @return mixed
     */
    public function actionIndex()
    {
        return $this->render('index');
    }

    /**
     * Logs in a user.
     *
     * @return mixed
     */
    public function actionLogin()
    {  
        // if (!\Yii::$app->user->isGuest) {
        //     return $this->redirect(['site/index','id'=>'2','page_id'=>'5']);
        // }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->loginFrontend()) {
            return $this->redirect(['site/index','id'=>'2','page_id'=>'5']);
        } else {
            // return $this->render('login', [
            //     'model' => $model,
            // ]);
            // yii::$app->session->setFlash('danger','Id atau Katalaluan salah.');
            return $this->redirect(['index']);
        }
    }

    /**
     * Logs out the current user.
     *
     * @return mixed
     */
    public function actionLogout()
    {
        Yii::$app->user->logout();

        return $this->goHome();
    }

    /**
     * Displays contact page.
     *
     * @return mixed
     */
    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
                Yii::$app->session->setFlash('success', 'Thank you for contacting us. We will respond to you as soon as possible.');
            } else {
                Yii::$app->session->setFlash('error', 'There was an error sending email.');
            }

            return $this->refresh();
        } else {
            return $this->render('contact', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Displays about page.
     *
     * @return mixed
     */
    public function actionAbout()
    {
        return $this->render('about');
    }

    /**
     * Signs user up.
     *
     * @return mixed
     */
    public function actionSignup()
    {
        $model = new SignupForm();
        if ($model->load(Yii::$app->request->post())) {
            if ($user = $model->signup()) {
                if (Yii::$app->getUser()->login($user)) {
                    return $this->goHome();
                }
            }
        }

        return $this->render('signup', [
            'model' => $model,
        ]);
    }

    /**
     * Requests password reset.
     *
     * @return mixed
     */
    public function actionRequestPasswordReset()
    {
        $model = new PasswordResetRequestForm();
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            if ($model->sendEmail()) {
                Yii::$app->session->setFlash('success', 'Check your email for further instructions.');

                return $this->goHome();
            } else {
                Yii::$app->session->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
            }
        }

        return $this->render('requestPasswordResetToken', [
            'model' => $model,
        ]);
    }

    /**
     * Resets password.
     *
     * @param string $token
     * @return mixed
     * @throws BadRequestHttpException
     */
    public function actionResetPassword($token)
    {
        try {
            $model = new ResetPasswordForm($token);
        } catch (InvalidParamException $e) {
            throw new BadRequestHttpException($e->getMessage());
        }

        if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->resetPassword()) {
            Yii::$app->session->setFlash('success', 'New password was saved.');

            return $this->goHome();
        }

        return $this->render('resetPassword', [
            'model' => $model,
        ]);
    }

    public function actionFrontendDashboard(){
        return $this->render('frontend-dashboard');
    }

    public function actionGenerateid(){
        $result = [];
        
        /*generate id*/
        $result = yii::$app->db->createCommand('SELECT UUID() AS UUID')->queryOne();

        /*insert id*/
        $now = date('Y-m-d H:i:s');
        $model = new DlsAiApplicationid();
        $model->aiad_aiapid = $result['UUID'];
        $model->aiad_ip = $this->getUserIpAddr() . '|' .$_SERVER['HTTP_USER_AGENT'];
        $model->created_at  = $now;
        
        if($model->save()){
            $result['PK'] = $model->aiad_id;
            $result['CREATED_AT'] = $now;
            
            return $this->asJson($result);
        }

    }

    public function actionSaveAppInfo(int $stat=null){
        /*object*/
        $result = [];
        
        /*flag*/
        $isnewrecord = false;

        /*convert json to array*/
        $formdata = json_decode($_POST['formJSON']);

        /*assign id*/
        $id = $_POST['UUID'] ?? null;

        /*application*/
        $model = DlsAiApplication::find()->where(['aiap_uuid'=> $id])->one();


        if(empty($model)){
            /* new instance if id no exist */
            $model = new DlsAiApplication();

            /*set uiid*/
            $model->aiap_uuid = $id;

            /*created at*/
            $model->created_at = date('Y-m-d H:i:s');

            /*flag*/
            $isnewrecord = true;
        }

        /*map array to field send by form*/
        $fieldmap = $this->fieldmap();

        /*date*/
        $datefield = [
            'aiap_datecommencement',
            'aiap_declarationdate'
        ];

        /* loop trough each map*/
        foreach ($formdata as $data) {
            if(isset($fieldmap[$data->name])){

                if(in_array($fieldmap[$data->name],$datefield)){
                    // $myDateTime = \DateTime::createFromFormat('d/m/Y', '22/02/2019');
                    $datetime = \DateTime::createFromFormat('d/m/Y', $data->value);
                    
                    if(!$datetime == false){
                        $model->{$fieldmap[$data->name]} = $datetime->format('Y-m-d');
                    }
                    continue;
                }

                /*check for empty*/
                if(!empty($data->value) || $data->value == 0)
                    $model->{$fieldmap[$data->name]} = $data->value;
            }
        }

        try{

            if(empty($id)){
                throw new \Exception("NO UUID PRESENT", 1);
                
            }

            /*TEMPORARY ID ASSIGNMENT*/
            if(!empty($model->aiap_id)){
                $model->aiap_tempid = $this->actionGetAppidbyid($model->aiap_id);
            }

            // if(empty($model->aiap_operatorcode)){
            //     throw new \Exception("NO OPERATOR CODE PRESENT", 1);
            // }

            if($model->save()){


                /*app status*/
                $chkappstat = AiAppstatus::find()->where(['aias_applicationid'=> $model->aiap_id,'aias_activeind' => '1'])->one();

                /*application id*/
                $hashids = new Hashids(Yii::$app->params['urlidcryptokey'] , 6);
                $result['APPID'] = $hashids->encode($model->aiap_id);

                /*if record is new  */
                if($stat === 1 && empty($chkappstat)){

                    /*sent first time email*/
                    $email = Template::find()->where(['dt_id' => self::ID_EMAIL_NOTIFIKASI])->one();

                    $content = $email->dt_header;
                    $content .= "<hr>";
                    // $content .= $email->dt_title;
                    $content .= $email->dt_body;
                    $content .= $email->dt_footer;

                    $emailprop = [
                        '#NAMAPEMOHON#'     => $model->aiap_applicantname,
                        '#NAMAOPERATOR#'    => $model->aiap_operatorname,
                        '#NOPERNIAGAAN#'    => $model->aiap_businessno,
                        '#IDPERMOHONAN#'        => $result['APPID'],
                        '#TARIKHPERMOHONAN#'    => date('d/m/Y'),
                        '#STATUSPERMOHONAN#'    => 'PROSES PERMOHONAN'
                    ];

                    $contentfinal = strtr($content,$emailprop);

                    /*primary email*/
                    $pemail =  filter_var($model->aiap_email, FILTER_VALIDATE_EMAIL);
                    /*secondary email*/
                    // $semail =  filter_var($model->aiap_contactemail, FILTER_VALIDATE_EMAIL);

                    // if(!$pemail && !$semail){
                    if(!$pemail){
                        throw new \Exception("Email dan format Email Tidak Sah <br> <span class='translation'>Email and email format is invalid</span>");
                    }   
                    
                    $appemail = [
                        $pemail,
                        // $model->aiap_contactemail
                    ];

                    /*email to applicant ---disable for testing*/
                    // Yii::$app->mailer->compose()
                    //         ->setFrom(Yii::$app->params['adminEmail'])
                    //         ->setTo($appemail)
                    //         ->setSubject($email->dt_title)
                    //         ->setTextBody('Plain text content')
                    //         ->setHtmlBody($contentfinal)
                    //         ->send();


                    /*set status for new application if email valid*/
                    $appstat = new AiAppstatus();
                    $appstat->aias_applicationid = $model->aiap_id;
                    $appstat->aias_statuscode = 'N';
                    $appstat->aias_activeind  = '1';
                    $appstat->save();


                    /*email to admin*/
                    $staff = Staff::find()->joinWith('roles')->where(['role_code'=>'SUP'])->all();
                    $staffemail = [];

                    foreach ($staff as $staffkey) {
                        $staffemail[] = $staffkey->user->email;
                    }

                    /*sent first time email*/
                    // $emailadmin = Template::find()->where(['dt_id' => self::ID_EMAIL_NOTIFIKASI])->one();

                    // $contentadmin = $emailadmin->dt_header;
                    // $contentadmin .= "<hr>";
                    // $contentadmin .= $emailadmin->dt_title;
                    // $contentadmin .= $emailadmin->dt_body;
                    // $contentadmin .= $emailadmin->dt_footer;

                    // $epropadmin = [
                    //     '#NAMAPEMOHON#'         => $model->aiap_applicantname,
                    //     '#NAMAOPERATOR#'        => $model->aiap_operatorname,
                    //     '#NOPERNIAGAAN#'        => $model->aiap_businessno,
                    //     '#IDPERMOHONAN#'        => $result['APPID'],
                    //     '#TARIKHPERMOHONAN#'    => date('d/m/Y'),
                    //     '#STATUSPERMOHONAN#'    => 'PROSES PERMOHONAN'
                    // ];

                    // $contentfinaladmin = strtr($contentadmin,$epropadmin);


                    // Yii::$app->mailer->compose()
                    //         ->setFrom(Yii::$app->params['adminEmail'])
                    //         ->setTo($staffemail)
                    //         ->setSubject($email->dt_title)
                    //         ->setTextBody('Plain text content')
                    //         ->setHtmlBody($contentfinaladmin)
                    //         ->send();



                /*if record come from reject status*/
                }elseif (isset($chkappstat->aias_statuscode) && $chkappstat->aias_statuscode == 'R' && $stat === 1) {
                    /*check status*/
                    $chkappstat->aias_activeind = '0';
                    $chkappstat->save(false);

                    /*set status for new application*/
                    $appstat = new AiAppstatus();
                    $appstat->aias_applicationid = $model->aiap_id;
                    $appstat->aias_statuscode = 'U';
                    $appstat->aias_activeind  = '1';

                    $appstat->save();
                }

                /*director reassign pk if exist*/
                $director = DlsAiDirectorowner::find()->where(['aiad_uuid'=>$id])->all();

                if(!empty($director)){
                    foreach ($director as $dkey) {
                        $dkey->aiad_applicationid = $model->aiap_id;
                        $dkey->save();
                    }
                }


                /*officer reassign pk if exist*/
                $officer = DlsAiAuthorizeduser::find()->where(['aiau_uuid'=>$id])->all();

                if(!empty($officer)){
                    foreach ($officer as $dkey) {
                        $dkey->aiau_applicationid = $model->aiap_id;
                        $dkey->save();
                    }
                }


                /*document upload reassign pk if exist*/
                $docupload = DlsAiDocupload::find()->where(['aidu_uuid'=>$id])->all();

                if(!empty($docupload)){
                    foreach ($docupload as $dockey) {
                        $dockey->aidu_applicationid = $model->aiap_id;
                        $dockey->save();
                    }
                }

                /*status*/
                $result['STATUS'] = "OK";
                $result['DATE']   = date('Y-m-d H:i:s');
            	$result['ID'] = $model->aiap_id;

                return $this->asJson($result);
            }else{

                /*status*/
                $result['DATE'] = date('Y-m-d H:i:s');
                $result['STATUS'] = "ERROR";
                $result['MESSAGE'] = $model->errors;
                return $this->asJson($result);
            }

        }catch(\Exception $e){

                // var_dump($e);
                /*status*/
                $result['DATE'] = date('Y-m-d H:i:s');
                $result['STATUS'] = "ERROR";
                $result['APPID'] = "-";
                $result['MESSAGE'] = $e->getMessage();
                return $this->asJson($result);
        }

    }

    public function actionSaveAppDirector($rowid=null){

        /*object*/
        $result = [];

        /*convert json to array*/
        $formdata = json_decode($_POST['formJSON']);

        /*assign id*/
        $id = $_POST['UUID'];

        if(!empty($rowid)){
        	$model = DlsAiDirectorowner::findOne($rowid);
        }else{
        	$model = new DlsAiDirectorowner();
        }

        $model->aiad_uuid = $id;

        /*map array to field send by form*/
        $fieldmap = [
            "nama_pengarah"         	=> "aiad_name",
            "alamat_pengarah_norumah"  	=> "aiad_address",
            "alamat_pengarah_taman"     => "aiad_address1",
            "alamat_pengarah_bandar"    => "aiad_address2",
            "alamat_negeri_pengarah"    => "aiad_state",
            "alamat_negara_pengarah"    => "aiad_country",
            "alamat_pengarah_poskod"    => "aiad_postcode",
            "jenis_alamat_pengarah"     => "aiad_addresstype",
            "tel_pengarah"          	=> "aiad_notel",
            "ic_pengarah"           	=> "aiad_ic",
            "warganegara_pengarah"  	=> "aiad_citizenship",
            "tarikh_pengarah"       	=> "aiad_appoinmentdate",
            "no_telefon_pengarah_code"	=> "aiad_kodnotel",
        ];

          /* loop trough each map*/
        foreach ($formdata as $data) {
            if(isset($fieldmap[$data->name])){
                $model->{$fieldmap[$data->name]} = $data->value;

                if($data->name == "tarikh_pengarah")
                	$model->{$fieldmap[$data->name]} = date('Y-m-d', strtotime($data->value));
            }
        }

        
        if($model->save()){
            $result['DATE']   = date('Y-m-d H:i:s');
            $result['STATUS'] = "OK";
            $result['UUID']  = $id;
            $result['ID']  = $model->aiad_id;
            return $this->asJson($result);
        }else{
            $result['DATE'] = date('Y-m-d H:i:s');
            $result['STATUS'] = "ERROR";
            $result['MESSAGE'] = $model->errors;
            return $this->asJson($result);
        }
    }

    public function actionSaveAppAuthorizedOfficer($rowid=null){

    	/*object*/
        $result = [];

        /*convert json to array*/
        $formdata = json_decode($_POST['formJSON']);

        /*assign id*/
        $id = $_POST['UUID'];

        if(!empty($rowid)){
        	$model = DlsAiAuthorizeduser::findOne($rowid);
        }else{
        	$model = new DlsAiAuthorizeduser();
        }

        $model->aiau_uuid = $id;

        /*map array to field send by form*/
        $fieldmap = [
            "nama_individu_dibenarkan"	=> "aiau_name",
            "ic_individu_dibenarkan"	=> "aiau_ic",
            "kod_notel_dibenarkan"      => "aiau_notelcode",
            "notel_dibenarkan"          => "aiau_notel",
            "emel_dibenarkan"			=> "aiau_email",
            "jawatan_dibenarkan"		=> "aiau_designation",
        ];

          /* loop trough each map*/
        foreach ($formdata as $data) {
            if(isset($fieldmap[$data->name])){
                $model->{$fieldmap[$data->name]} = $data->value;
            }
        }

        
        if($model->save()){
            $result['DATE']   = date('Y-m-d H:i:s');
            $result['STATUS'] = "OK";
            $result['UUID']  = $id;
            $result['ID']  = $model->aiau_id;
            return $this->asJson($result);
        }else{
            $result['DATE'] = date('Y-m-d H:i:s');
            $result['STATUS'] = "ERROR";
            $result['MESSAGE'] = $model->errors;
            return $this->asJson($result);
        }


    }

    public function actionDeleteDirector($id){
        /*model*/
        $director = DlsAiDirectorowner::findOne($id);
        $director->delete(); 

        return $this->asJson(['STATUS'=>'OK','DATE' => date('Y-m-d H:i:s'),'ID'=>$id]);
    }

    public function actionDeleteOfficer($id){
        /*model*/
        $director = DlsAiAuthorizeduser::findOne($id);
        $director->delete(); 

        return $this->asJson(['STATUS'=>'OK','DATE' => date('Y-m-d H:i:s'),'ID'=>$id]);
    }

    public function actionGetFormData(string $uuid){
        /*application*/
        $model = DlsAiApplication::find()->where(['aiap_uuid'=> $uuid])->one();

        if(!empty($model)){
            /*status*/
            $appstat = AiAppstatus::find()->where(['aias_applicationid'=> $model->aiap_id, 'aias_activeind' => '1'])->one();

            if(!empty($appstat)){
                if($appstat->aias_statuscode != 'N' && $appstat->aias_statuscode != 'U'){
                    $result['STATUS'] = "DATA_PROCESS_EXCEPTION";
                    $result['MESSAGE'] = "Data anda sudah pun diproses. Anda akan memulakan pengisian permohonan yang baru";

                    $this->asJson($result);
                }
            }

            /*flip array*/
            $fieldmap = array_flip($this->fieldmap());

            /*date*/
	        $datefield = [
	            'aiap_datecommencement',
	            'aiap_declarationdate'
	        ];

            $i=0;
            foreach ($model->attributes as $mkey => $mval) {
                

                if(isset($fieldmap[$mkey]))
                    $result['APPDATA'][$i]['fieldname'] =  $fieldmap[$mkey];

                $result['APPDATA'][$i]['dbcolname'] =  $mkey;
                $result['APPDATA'][$i]['value']     = $mval;

                if(in_array($mkey,$datefield)){
                    	// $myDateTime = \DateTime::createFromFormat('d/m/Y', '22/02/2019');
                    	$datetime = new \DateTime($mval);
                    
                    	if(!$datetime == false){
                        	$result['APPDATA'][$i]['value'] = $datetime->format('d/m/Y');
	                    }
                	}

            $i++;}
                        
            /*application id*/
            $hashids = new Hashids(Yii::$app->params['urlidcryptokey'] , 6);
            $result['APPID'] = $hashids->encode($model->aiap_id);
            $result['ID'] = $model->aiap_id;

            //debug
            // $result['APPIDDECODE'] = $hashids->decode($result['APPID']);
            if(!empty($appstat)){
                $result['APPSTATUS'] = $appstat->aias_statuscode;
            }else{
                $result['APPSTATUS'] = null;
            }
            
            $result['STATUS'] = "OK";
        }else{    
            $result['STATUS'] = "NULL_RECORD";
            $result['MESSAGE'] = "NO DATA FOUND FOR APPLICATION ";
        }

        $result['DATE']   = date('Y-m-d H:i:s');
        $result['UUID']  = $uuid;
        
        return $this->asJson($result);
    }

    public function actionGetDirectorData(string $uuid){

    	/*model*/
        $director = DlsAiDirectorowner::find()->where(['aiad_uuid' => $uuid])->all();

        if(!empty($director)){
        	foreach ($director as $dkey) {
        		/*change date format*/
        		$appointdate = new \DateTime($dkey->aiad_appoinmentdate);
        		$dkey->aiad_appoinmentdate = $appointdate->format('d/m/Y');

        		/*put result into array*/
        		$result['DIRECTOR'][] = $dkey->attributes;
			}

        	$result['STATUS'] = "OK";
        }else{
        	$result['STATUS'] = "NULL_RECORD";
        	$result['MESSAGE'] = "NO DATA FOUND FOR DIRECTOR";
        }

        return $this->asJson($result);

    }

    public function actionGetAuthorizedOfficerData(string $uuid){

    	/*model*/
        $officer = DlsAiAuthorizeduser::find()->where(['aiau_uuid' => $uuid])->all();

        if(!empty($officer)){
        	foreach ($officer as $dkey) {
        		$result['OFFICER'][] = $dkey->attributes;
			}

        	$result['STATUS'] = "OK";
        }else{
        	$result['STATUS'] = "NULL_RECORD";
        	$result['MESSAGE'] = "NO DATA FOUND FOR OFFICER";
        }

        return $this->asJson($result);

    }

    public function actionGetAppstatus(string $appid){

    	$result = [];
    	
    	if(!empty($appid)){
    		
    		/*decode*/
    		$hashids = new Hashids(Yii::$app->params['urlidcryptokey'] , 6);
    		$id = $hashids->decode($appid);

    		$appstat = AiAppstatus::find()->where(['aias_applicationid'=> $id,'aias_activeind' => '1'])->one();
            $appdata = DlsAiApplication::findOne($id);

    		if(!empty($appstat)){
                $result['UUID'] = $appdata->aiap_uuid;
    			$result['STATUS'] = 'OK';
    			$result['APPSTAT'] = $appstat->attributes;
    		}else{
                
                if(!empty($appdata)){
                    $result['UUID'] = $appdata->aiap_uuid;
                    $result['STATUS'] = 'OK';
                    $result['APPSTAT'] = ['aias_statuscode'=>'D'];
                }else{
                    $result['STATUS'] = 'NULL_RECORD';
                    $result['MESSAGE'] = 'NO DATA FOR THIS APPID';
                }
    		}

    	}

    	return $this->asJson($result);

    }

    public function actionGetDocUploadData(string $uuid){

    	/*model*/
        $director = DlsAiDocupload::find()->where(['aidu_uuid' => $uuid])->all();

        if(!empty($director)){
        	foreach ($director as $dkey) {
        		$result['DOCUPLOAD'][] = $dkey->attributes;
			}

        	$result['STATUS'] = "OK";
        }else{
        	$result['STATUS'] = "NULL_RECORD";
        	$result['MESSAGE'] = "NO DATA FOUND FOR UPLOAD";
        }

        return $this->asJson($result);

    }

    public function actionGetAppidbyid($id){
    	$hashids = new Hashids(Yii::$app->params['urlidcryptokey'] , 6);
        return $hashids->encode($id);
    }

    public function actionGetApproveOperatorCode(){
        
        try{
            /* exclude agent exchange */
            $agenttrans = AgentTransfer::find()->where(['agtr_approverstatus' => 'A'])->asArray()->all();
            $agentarray = [];

            array_walk($agenttrans, function($v, $i) use (&$agentarray) {
                $agentarray[$i] = $v['agtr_appid'];
            });

            $app = DlsAiApplication::find()
            ->joinWith('dlsAiAppstatus')
            ->where(['aias_statuscode'=>'A','aiap_transportcategory'=>'11','aias_activeind'=> 1])
            ->andWhere(['not in', 'aiap_id', $agentarray])->all();

            

            $codearr = [];

            array_walk($app, function($v,$i) use (&$codearr){
                $codearr[$i] = $v->aiap_operatorcode;
            });

            return $this->asJson(['CODE' => $codearr,'STATUS' => 'OK']);
        }catch(\Exception $e){
            return $this->asJson(['STATUS' => 'ERROR','MESSAGE' => $e->getMessage()]);
        }

    }

    public function getUserIpAddr(){
	    if(!empty($_SERVER['HTTP_CLIENT_IP'])){
	        //ip from share internet
	        $ip = $_SERVER['HTTP_CLIENT_IP'];
	    }elseif(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
	        //ip pass from proxy
	        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
	    }else{
	        $ip = $_SERVER['REMOTE_ADDR'];
	    }
	    return $ip;
	}


    public function actionForgetpass(){

        $modelUser = new FrontendUser();
        if (!empty($_POST['email'])) {

            /*post variable*/
            $mailTo = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
            $registrantid = filter_var($_POST['registrant_id'], FILTER_SANITIZE_STRING);
            $uid = uniqid();

            /* check user */
            $checkUser = FrontendUser::find()->where(['email' => $mailTo,'registrant_id'=>$registrantid])->one();


            if (is_object($checkUser) || $checkUser instanceof FrontendUser ) {

                try {
                    $emailPassword = Yii::$app->mailer->compose()
                        ->setFrom(Yii::$app->params['adminEmail'])
                        ->setTo($mailTo) //replace email sini untuk testing
                        ->setSubject('Sistem Mydlv - Terlupa kata laluan')
                        ->setHtmlBody('Kata Laluan Sementara anda untuk email:- '.$mailTo.' dan Id Pendaftaran:- '.$registrantid.' ialah:- '.$uid.'. Sila Log masuk dan tukar kata laluan anda pada menu tukar kata laluan.')
                        ->send();
                        
                } catch (\Exception $e) {
                    return $this->asJson($e->getMessage());
                    throw $e;
                }
                
                $checkUser->password_hash = Yii::$app->security->generatePasswordHash($uid);
                
                if($checkUser->update(false)){
                    return $this->asJson(['success'=> true ,'message' => 'Emel Telah Dihantar. Sila tukar kata laluan anda selepas log masuk.']);
                }else{
                    return $this->asJson(['success'=> false ,'message' => 'Server encounter an error.']);
                }
            } else {
                return $this->asJson(['success'=> false,'message' => 'Emel Pengguna Tidak Wujud']);
            }
        }
    }

    public function actionChangepass(){

        $modelUser = new FrontendUser();

        $post = Yii::$app->request->post();

        /*post variable*/
        $userid = filter_var($post['userid'], FILTER_SANITIZE_NUMBER_INT);
        $oldpassword = filter_var($post['oldpassword'],FILTER_SANITIZE_STRING);
        $password = filter_var($post['password'],FILTER_SANITIZE_STRING);

        if ( !empty($userid) && !empty($oldpassword) && !empty($password) ) {

            /* check user */
            $checkUser = FrontendUser::findOne($userid);

            /*check if old pass is true*/
            if ((is_object($checkUser) || $checkUser instanceof FrontendUser) && Yii::$app->getSecurity()->validatePassword($oldpassword, $checkUser->password_hash) === true ) {
                
                $checkUser->password_hash = Yii::$app->security->generatePasswordHash($password);
                
                if($checkUser->save(false)){
                    return $this->asJson(['success'=> true ,'message' => 'Password telah ditukar sila log keluar dan log masuk semula.'.PHP_EOL.'Password has been changed please sign out and sign in again.']);
                }else{
                    var_dump($checkUser->errors);
                    return $this->asJson(['success'=> false ,'message' => 'Server encounter an error.']);
                }
            } else {
                return $this->asJson(['success'=> false,'message' => 'Kata laluan lama tidak sama.'.PHP_EOL.'Old Password is incorrect.']);
            }
        }
    }

    public function actionStub(){

        echo 'YES it is.';
        // $email = Template::find()->where(['dt_id' => 7])->one();

        // $content = $email->dt_header;
        // $content .= "<hr>";
        // // $content .= $email->dt_title;
        // $content .= $email->dt_body;
        // $content .= $email->dt_footer;

        // // $emailprop = [
        // //     '#NAMAPEMOHON#'     => $model->aiap_applicantname,
        // //     '#NAMAOPERATOR#'    => $model->aiap_operatorname,
        // //     '#NOPERNIAGAAN#'    => $model->aiap_businessno,
        // //     '#IDPERMOHONAN#'        => $result['APPID'],
        // //     '#TARIKHPERMOHONAN#'    => date('d/m/Y'),
        // //     '#STATUSPERMOHONAN#'    => 'PROSES PERMOHONAN'
        // // ];

        // // $contentfinal = strtr($content,$emailprop);


        // /*email to applicant*/
        // Yii::$app->mailer->compose()
        //         ->setFrom(Yii::$app->params['adminEmail'])
        //         ->setTo('zerofrost92@gmail.com')
        //         ->setSubject($email->dt_title)
        //         ->setTextBody('Plain text content')
        //         ->setHtmlBody($content)
        //         ->send();

    }
}