<?php

namespace backend\modules\sikk\controllers;
use mPDF;
use Yii;
use common\models\SikkIzinKeluar;
use common\models\SikkApproval;
use common\models\search\SikkIzinKeluarSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use common\models\checkbox;
use yii\data\ActiveDataProvider;

/**
 * SikkIzinKeluarController implements the CRUD actions for SikkIzinKeluar model.
 */
class SikkIzinKeluarController extends Controller {

    /**
     * @inheritdoc
     */
    public function behaviors() {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }
    public function actionDaftarrequest() {
            $searchModel = new \common\models\search\SikkIzinKeluarSearch();
            $akunID = Yii::$app->user->identity->id;
            $mahModel = \common\models\DimxDim::findOne(array('akun_id' => $akunID));
            $mahID = $mahModel->dim_id;
            $query = SikkIzinKeluar::find()->where(['status' => 0,'mhs_id'=>$mahID]);
            $dataProvider = new ActiveDataProvider([
                'query' => $query,
                'pagination' => [
                    'pageSize' => 10,
                ],
                'sort' => [
                    'defaultOrder' => [
                        'izin_keluar_id' => SORT_DESC,
                    ]
                ],
            ]);
            return $this->render('index', [
                        'dataProvider' => $dataProvider,
                         'searchModel' => $searchModel,
            ]);
       
    }

    /**
     * Lists all SikkIzinKeluar models.
     * @return mixed
     */
    public function actionIndex() {
        $searchModel = new \common\models\search\SikkApprovalSearch();

        $mus = Yii::$app->user->identity->id;

        $akunID = \common\models\HrdxPegawai::findOne(array('akun_id' => $mus));

        $muso = \common\models\SikkAkun::findOne(array('akun_id' => $mus));

        $roleID = $muso->role_id;


        if ($roleID == 2) {
            //dosen
            $roleks = 0;
            $query = \common\models\SikkIzinKeluar::findBySql("SELECT b.izin_keluar_id, b.mhs_id, b.date_start, b.date_end, b.time_start, b.time_end, b.alasan, b.deleted ,b.created_at, b.created_by, b.updated_at, b.updated_by, b.status
 FROM sikk_approval a LEFT JOIN sikk_izin_keluar b ON a.`izin_keluar_id` = b.`izin_keluar_id` WHERE a.`approver_id` = " . $akunID->pegawai_id . ' and b.status=' . $roleks . ' and a.`status_approval` = '.$roleks);
        } else if ($roleID == 3) {
            //keasramaan
            $roleks = 2;
            $query = \common\models\SikkIzinKeluar::findBySql("SELECT b.izin_keluar_id, b.mhs_id, b.date_start, b.date_end, b.time_start, b.time_end, b.alasan, b.deleted ,b.created_at, b.created_by, b.updated_at, b.updated_by, b.status
 FROM sikk_approval a LEFT JOIN sikk_izin_keluar b ON a.`izin_keluar_id` = b.`izin_keluar_id` WHERE a.`approver_id` = " . $akunID->pegawai_id . ' and b.status=' . $roleks);
        } else if ($roleID == 4) {
            //dosen wali
            $roleks = 1;
            $query = \common\models\SikkIzinKeluar::findBySql("SELECT b.izin_keluar_id, b.mhs_id, b.date_start, b.date_end, b.time_start, b.time_end, b.alasan, b.deleted ,b.created_at, b.created_by, b.updated_at, b.updated_by, b.status
 FROM sikk_approval a LEFT JOIN sikk_izin_keluar b ON a.`izin_keluar_id` = b.`izin_keluar_id` WHERE a.`approver_id` = " . $akunID->pegawai_id . ' and b.status=' . $roleks);
        
        } else if ($roleID == 1) {
            //satpam
            
            
        }

        $dataProvider = new \yii\data\ActiveDataProvider(
                ["query" => $query]);

        return $this->render('index', [
                    'searchModel' => $searchModel,
                    'dataProvider' => $dataProvider,
        ]);
    }
    public function actionIndex2() {

        $searchModel = new SikkIzinKeluarSearch();
        $dataProvider = $searchModel->searchs(Yii::$app->request->queryParams);

        return $this->render('index_1', [
                    'searchModel' => $searchModel,
                    'dataProvider' => $dataProvider,
        ]);
    }

    public function actionIndex3() {

        $searchModel = new SikkIzinKeluarSearch();
        $dataProvider = $searchModel->searchss(Yii::$app->request->queryParams);

        return $this->render('index_2', [
                    'searchModel' => $searchModel,
                    'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single SikkIzinKeluar model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id) {

        //$id_user = Yii::$app->user->identity->akun_id;
        /*  $rows2 = (new \yii\db\Query())
          ->select(['mhs_id'])
          ->from('sikk_izin_keluar')
          ->where(['izin_keluar_id' => $id])
          ->limit(1)
          ->all();
          $id = $rows2[0]["mhs_id"];

          $rows = (new \yii\db\Query())
          ->select(['nama'])
          ->from('dimx_dim')
          ->where(['dim_id' => $id])
          ->limit(1)
          ->all();
          $nama_request = $rows[0]["nama"];
          var_dump($nama_request);die(); */
        return $this->render('view', [
                    'model' => $this->findModel($id),
                        // 'nama_request' => $nama_request,
        ]);
    }

    public function actionAcceptwali($id) {

        $model = $this->findModel($id);

        $mus = Yii::$app->user->identity->id;

        $akunID = \common\models\HrdxPegawai::findOne(array('akun_id' => $mus));

        $mdlTL = \common\models\SikkApproval::findOne(array('izin_keluar_id' => $id, 'approver_id' => $akunID->pegawai_id));

        if ($mdlTL) {
            $mdlTL->status_approval = 2;
            if ($mdlTL->save()) {
                $model->status = 2;
                $model->save();
            }

            return $this->redirect(['index']);
        } else {

            return $this->render('createacceptresponsewali', [
                        'mdlTL' => $mdlTL
            ]);
        }
    }

    public function actionRejectwali($id) {

        $model = $this->findModel($id);
        $mdlTL = \common\models\SikkApproval::findOne(array('izin_keluar_id' => $id));
        $mus = Yii::$app->user->identity->id;

        $akunID = \common\models\HrdxPegawai::findOne(array('akun_id' => $mus));

        $mdlTL = \common\models\SikkApproval::findOne(array('izin_keluar_id' => $id, 'approver_id' => $akunID->pegawai_id));

        if ($mdlTL->load(Yii::$app->request->post())) {
            $mdlTL->status_approval = 22;
            if ($mdlTL->save()) {
                $model->status = 22;
                $model->save();
            }

            return $this->redirect(['index']);
        } else {

            return $this->render('createrejectresponsewali', [
                        'mdlTL' => $mdlTL
            ]);
        }
    }

    public function actionAcceptdp($id) {

        $model = $this->findModel($id);
        $mdlTL = \common\models\SikkApproval::findOne(array('izin_keluar_id' => $id));
        $mus = Yii::$app->user->identity->id;

        $akunID = \common\models\HrdxPegawai::findOne(array('akun_id' => $mus));

        $mdlTL = \common\models\SikkApproval::findOne(array('izin_keluar_id' => $id, 'approver_id' => $akunID->pegawai_id));

        $query = \common\models\SikkApproval::findBySql("SELECT COUNT(izin_keluar_id) FROM sikk_approval WHERE status_approval = 0");

        $mdlizinkeluar = \common\models\SikkIzinKeluar::findOne(array('izin_keluar_id' => $id, 'status' => 0));

        $totaldosenpengampu = \common\models\SikkApproval::find()
                ->where('status_approval != 5 and izin_keluar_id =' . $id)
                ->count();
        $telahdiresponse = \common\models\SikkApproval::find()
                ->where('status_approval != 0 && status_approval != 5 and izin_keluar_id =' . $id)
                ->count();


        if ($mdlTL) {
            if ($totaldosenpengampu - $telahdiresponse == 1) {
                $mdlTL->status_approval = 1;
                if ($mdlTL->save()) {
                    $model->status = 1;
                    $model->save();
                }
                return $this->redirect(['index']);
            } else {
                $mdlTL->status_approval = 1;
                $mdlTL->save();
                return $this->redirect(['index']);
            }
        } else {

            return $this->render('createacceptresponsewali', [
                        'mdlTL' => $mdlTL
            ]);
        }
    }

    public function actionRejectdp($id) {

        $model = $this->findModel($id);
        $mdlTL = \common\models\SikkApproval::findOne(array('izin_keluar_id' => $id));
        $mus = Yii::$app->user->identity->id;

        $akunID = \common\models\HrdxPegawai::findOne(array('akun_id' => $mus));

        $mdlTL = \common\models\SikkApproval::findOne(array('izin_keluar_id' => $id, 'approver_id' => $akunID->pegawai_id));

        if ($mdlTL->load(Yii::$app->request->post())) {
            $mdlTL->status_approval = 11;
            if ($mdlTL->save()) {
                $model->status = 11;
                $model->save();
            }

            return $this->redirect(['index']);
        } else {

            return $this->render('createrejectresponsewali', [
                        'mdlTL' => $mdlTL
            ]);
        }
    }

    public function actionAcceptkeasramaan($id) {

        $model = $this->findModel($id);
        $mdlTL = \common\models\SikkApproval::findOne(array('izin_keluar_id' => $id));
        $mus = Yii::$app->user->identity->id;

        $akunID = \common\models\HrdxPegawai::findOne(array('akun_id' => $mus));

        $mdlTL = \common\models\SikkApproval::findOne(array('izin_keluar_id' => $id, 'approver_id' => $akunID->pegawai_id));

        if ($mdlTL) {
            $mdlTL->status_approval = 3;
            if ($mdlTL->save()) {
                $model->status = 3;
                $model->save();
            }

            return $this->redirect(['index']);
        } else {

            return $this->render('createacceptresponsewali', [
                        'mdlTL' => $mdlTL
            ]);
        }
    }

    public function actionRejectkeasramaan($id) {

        $model = $this->findModel($id);
        $mdlTL = \common\models\SikkApproval::findOne(array('izin_keluar_id' => $id));
        $mus = Yii::$app->user->identity->id;

        $akunID = \common\models\HrdxPegawai::findOne(array('akun_id' => $mus));

        $mdlTL = \common\models\SikkApproval::findOne(array('izin_keluar_id' => $id, 'approver_id' => $akunID->pegawai_id));

        if ($mdlTL->load(Yii::$app->request->post())) {
            $mdlTL->status_approval = 33;
            if ($mdlTL->save()) {
                $model->status = 33;
                $model->save();
            }

            return $this->redirect(['index']);
        } else {

            return $this->render('createrejectresponsewali', [
                        'mdlTL' => $mdlTL
            ]);
        }
    }

    /**
     * Creates a new SikkIzinKeluar model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate() {
        $model = new SikkIzinKeluar();
        $modelchk = new checkbox();

        $id_user = Yii::$app->user->identity->akun_id;
        $rows = (new \yii\db\Query())
                ->select(['dim_id'])
                ->from('dimx_dim')
                ->where(['akun_id' => $id_user])
                ->limit(1)
                ->all();
        $dim = $rows[0]["dim_id"];
        $rowss = (new \yii\db\Query())
                ->select(['dosen_wali_id'])
                ->from('adak_registrasi')
                ->where(['dim_id' => $dim])
                ->limit(1)
                ->all();
        $id_wali = $rowss[0]["dosen_wali_id"];
        $rowsss = (new \yii\db\Query())
                ->select(['nama'])
                ->from('hrdx_pegawai')
                ->where(['pegawai_id' => $id_wali])
                ->limit(1)
                ->all();
        $nama_wali = $rowsss[0]["nama"];
        $rowsall = (new \yii\db\Query())
                ->select(['pegawai_id'])
                ->from('hrdx_dosen')
                ->limit(10)
                ->all();
        $nama_dosen = "";

        for ($i = 0; $i < count($rowsall); $i++) {
            $rowsdosen = (new \yii\db\Query())
                    ->select(['nama'])
                    ->from('hrdx_pegawai')
                    ->where(['pegawai_id' => $rowsall[$i]['pegawai_id']])
                    ->limit(1)
                    ->all();
            if ($rowsall[$i]['pegawai_id'] == $id_wali) {
                $rowsdosen[0]['nama'] = "";
            } else {
                $nama = $rowsdosen[0]['nama'];
                $nama_dosen = $nama_dosen . "," . $nama;
            }
        }

        $arrayNamaDosen = explode(",", substr($nama_dosen, 1));




        if ($model->load(Yii::$app->request->post()) && $modelchk->load(Yii::$app->request->post())) {
            $model->mhs_id = $dim;
            //var_dump($modelchk->namacheck);die();
            $checkedName = "";
            if ($modelchk->namacheck != "") {
                for ($it = 0; $it < count($modelchk->namacheck); $it++) {
                    $checkedName = $checkedName . "," . $arrayNamaDosen[($modelchk->namacheck[$it])];
                }
                $checkedName = substr($checkedName, 1);
                $arraycheckedName = explode(",", $checkedName);
            }


            //var_dump($arraycheckedName);die();
            $model->created_at = date('Y-m-d H:i:s');
            $model->created_by = Yii::$app->user->identity->user_name;
            $hour_start = $model->time_start;
            $model->time_start = $model->date_start . " " . $hour_start;
            $model->status = 0;
            $model->deleted = 0;
            $hour_end = $model->time_end;
            if ($model->date_end != "") {
                $model->time_end = $model->date_end . " " . $hour_end;
            } else {
                $model->time_end = $model->date_start . " " . $hour_end;
            }
            if ($model->save()) {
                for ($i = 0; $i < 2; $i++) {
                    $modelAppr = new SikkApproval();
                    $modelAppr->izin_keluar_id = $model->izin_keluar_id;
                    if ($i == 0) {
                        $modelAppr->approver_id = 5;
                    } else if ($i == 1) {
                        $modelAppr->approver_id = $id_wali;
                    }
                    $modelAppr->status_approval = 5;
                    $modelAppr->created_at = date('Y-m-d H:i:s');
                    $model->created_by = Yii::$app->user->identity->user_name;
                    $modelAppr->deleted = 0;
                    $modelAppr->isNewRecord = true;
                    $modelAppr->save();
                }
                if ($modelchk->namacheck != "") {
                    for ($j = 0; $j < count($arraycheckedName); $j++) {
                        $rows = (new \yii\db\Query())
                                ->select(['pegawai_id'])
                                ->from('hrdx_pegawai')
                                ->where(['nama' => $arraycheckedName[$j]])
                                ->limit(1)
                                ->all();
                        $id_pegawai = $rows[0]['pegawai_id'];
                        $modelAppr = new SikkApproval();
                        $modelAppr->izin_keluar_id = $model->izin_keluar_id;
                        $modelAppr->approver_id = $id_pegawai;
                        $modelAppr->status_approval = 0;
                        $modelAppr->created_at = date('Y-m-d H:i:s');
                        $modelAppr->deleted = 0;
                        $model->created_by = Yii::$app->user->identity->user_name;
                        $modelAppr->isNewRecord = true;
                        $modelAppr->save();
                    }
                }
                return $this->redirect(['view', 'id' => $model->izin_keluar_id]);
            } else {
                Yii::$app->session->setFlash('warning', 'Request yang anda buat tidak benar, coba perhatikan jika masih ada kolom yang kosong atau tanggal yang anda masukkan');
                return $this->render('create', [
                            'model' => $model,
                            'modelchk' => $modelchk,
                            'id_wali' => $id_wali,
                            'nama_wali' => $nama_wali,
                            'arrayNamaDosen' => $arrayNamaDosen,
                ]);
            }
        } else {

            return $this->render('create', [
                        'model' => $model,
                        'modelchk' => $modelchk,
                        'id_wali' => $id_wali,
                        'nama_wali' => $nama_wali,
                        'arrayNamaDosen' => $arrayNamaDosen,
            ]);
        }
    }

    /**
     * Updates an existing SikkIzinKeluar model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id) {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->izin_keluar_id]);
        } else {
            return $this->render('update', [
                        'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing SikkIzinKeluar model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id) {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the SikkIzinKeluar model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return SikkIzinKeluar the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id) {
        if (($model = SikkIzinKeluar::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
    
    // show in browser                        
    public function actionShow(){
        $mpdf= new mPDF();
        $mpdf->WriteHTML($this->renderPartial('view'));
        $mpdf->Output();
        exit;
    }
 // download     
    public function actionForceDownloadPdf(){
        $mpdf=new mPDF();
        $mpdf->WriteHTML($this->renderPartial('mpdf_view'));
        $mpdf->Output('MyPDF.pdf', 'D');
        exit;
    }

}
