<?php

namespace app\controllers;

use Yii;
use app\models\TrainingRequests;
use app\models\TrainingRequestsSearch;
use app\models\RejectedRequestsCauses;
use app\models\Settings;
use app\models\EmailTemplates;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;
use yii\filters\AccessControl;
use kartik\mpdf\Pdf;

class TrainingRequestsController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => false,
                        'roles' => ['?']
                    ],
                    [
                        'allow' => true,
                        'actions' => ['view', 'create'],
                        'roles' => ['User']
                    ],
                    [
                        'allow' => true,
                        'roles' => ['Admin']
                    ],
                ],
                'denyCallback' => function(){
                    if(Yii::$app->user->isGuest){
                        return Yii::$app->response->redirect(['/users/login']);
                    }
                    else{
                        return Yii::$app->response->redirect(['/dashboard/index']);
                    }
                }
            ],
            'verbs' => [
                'class' => VerbFilter::class,
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    public function actionIndex($from_date = null, $to_date = null)
    {
        $searchModel = new TrainingRequestsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        if($from_date != null && $to_date != null && strtotime($from_date) > strtotime($to_date)){
            Yii::$app->session->setFlash('wrong_selected_dates', Yii::t('app', 'Wrong Selected Dates'));
            return $this->render('index', [
                'searchModel' => $searchModel,
                'dataProvider' => $dataProvider,
            ]);
        }

        if($from_date != null && $to_date != null){
            $dataProvider->query->andWhere(['between', 'create_date', $from_date, $to_date]);
        }
        elseif($from_date != null && $to_date == null){
            $dataProvider->query->andWhere(['>=', 'create_date', $from_date]);
        }
        elseif($from_date == null && $to_date != null){
            $dataProvider->query->andWhere(['<=', 'create_date', $to_date]);
        }

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

    public function actionView($id)
    {
        $model = $this->findModel($id);
        return $this->render('view', [
            'model'      => $model,
            'rejections' => $model->rejections,
            'interviews' => $model->interviews,
            'trainings'  => $model->trainings
        ]);
    }

    public function uploadFile($model, $attribute, $random_number){
        $model->{$attribute} = UploadedFile::getInstance($model, $attribute);
        if($model->{$attribute} && $model->validate($attribute)){
            $file = $model->{$attribute};
            $extension = $file->extension;
            if(in_array($extension, ['jpg', 'jpeg', 'png'])){
                $rnd = mt_rand(10000, 999999);
                $path = "images/{$random_number}-{$attribute}-{$file->baseName}-{$rnd}.{$extension}";
                $file->saveAs($path);
                $model->{$attribute} = $path;
            }
        }
        return $model;
    }

    public function actionCreate()
    {
        $model = new TrainingRequests();
        $old_request = TrainingRequests::find()->where(['trainee_user_id' => Yii::$app->user->getId()])->one();
        $readonly_essential_info = false;
        if($old_request){
            $readonly_essential_info = true;
            $model->full_name = $old_request->full_name;
            $model->full_name_english = $old_request->full_name_english;
            $model->mother_name = $old_request->mother_name;
            $model->gender = $old_request->gender;
        }

        if ($model->load(Yii::$app->request->post())) {
            $last_serial = TrainingRequests::find()->orderBy(['id' => SORT_DESC])->one();
            
            $serial_number = 'T' . sprintf('%08d', 1);
            if($last_serial){
                $last_serial_number = str_replace('T', '', $last_serial->serial_number);
                $serial_number = 'T' . sprintf('%08d', (int)$last_serial_number + 1);
            }

            $model->create_date = date('Y-m-d');
            $model->serial_number = $serial_number;
            $model->trainee_user_id = Yii::$app->user->getId();

            // Files upload
            $model = $this->uploadFile($model, 'university_training_request', $serial_number);
            $model = $this->uploadFile($model, 'personal_photo', $serial_number);
            $model = $this->uploadFile($model, 'identity', $serial_number);

            if($model->save()){
                if($this->checkSendEmailSetting()){
                    $email_template = EmailTemplates::findOne(['dedicated_for' => 'EMAIL_TEMPLATE_CONFIRM_CREATING_TRAINING_REQUEST']);
                    if($email_template && $email_template->is_active == 1){
                        $content = $email_template->content;
                        $template_variables = $email_template->variables;
                        if($template_variables != null){
                            foreach($template_variables as $variable){
                                $code = $variable->variable->var_code;
                                EmailTemplates::replaceVariablesCode($content, $code, $model, null, null, null, $model->user);
                            }
                        }

                        $this->sendEmail($model->user->email, $content, 'إنشاء طلب تدريب');
                    }
                }

                return $this->redirect(['view', 'id' => $model->id]);
            }
            else{
                if(file_exists($model->university_training_request)){
                    unlink($model->university_training_request);
                }
                if(file_exists($model->personal_photo)){
                    unlink($model->personal_photo);
                }
                if(file_exists($model->identity)){
                    unlink($model->identity);
                }
                return var_dump($model->getErrors());
            }
        }

        // Get distinct universities names and faculties names
        $universities_names = TrainingRequests::find()->select(['university_name'])->distinct()->all();
        $faculties_names = TrainingRequests::find()->select(['faculty'])->distinct()->all();

        return $this->render('create', [
            'model' => $model,
            'readonly_essential_info' => $readonly_essential_info,
            'universities_names' => $universities_names,
            'faculties_names' => $faculties_names
        ]);
    }

    protected function findModel($id)
    {
        if (($model = TrainingRequests::findOne($id)) !== null) {
            return $model;
        }

        throw new NotFoundHttpException(Yii::t('app', 'The requested page does not exist.'));
    }

    public function actionRejectTraining($id, $url = null){
        $model = new RejectedRequestsCauses();
        $training_request = $this->findModel($id);
        $training_request->scenario = TrainingRequests::UPDATE_STATUS;

        if($model->load(Yii::$app->request->post())){
            $model->training_request_id = $id;
            $model->rejection_date = date('Y-m-d');
            $model->rejector_user_id = Yii::$app->user->getId();
            $model->request_status_when_rejected = $training_request->training_request_status;
            if($model->save()){
                $training_request->training_request_status = 'Rejected';
                if($training_request->save()){
                    if($this->checkSendEmailSetting()){
                        $email_template = EmailTemplates::findOne(['dedicated_for' => 'EMAIL_TEMPLATE_REJECT_TRAINING_REQUEST']);
                        if($email_template && $email_template->is_active == 1){
                            $content = $email_template->content;
                            $template_variables = $email_template->variables;
                            if($template_variables != null){
                                foreach($template_variables as $variable){
                                    $code = $variable->variable->var_code;
                                    EmailTemplates::replaceVariablesCode($content, $code, $training_request, null, null, $model, $training_request->user);
                                }
                            }

                            $this->sendEmail($training_request->user->email, $content, 'رفض طلب التدريب');
                        }
                    }

                    Yii::$app->session->setFlash('request_rejected', Yii::t('app', 'The request has been rejected'));
                    if($url == 'Dashboard'){
                        return $this->redirect(['/dashboard/index']);    
                    }
                    elseif($url == 'View'){
                        return $this->redirect(['view', 'id' => $id]);
                    }
                    return $this->redirect(['index']);
                }
            }
        }

        return $this->renderAjax('reject-training-request-modal', ['model' => $model]);
    }

    public function actionReactivateRequest($id, $url = null){
        $model = $this->findModel($id);
        $model->scenario = TrainingRequests::UPDATE_STATUS;
        
        if($model->training_request_status == 'Rejected'){
            $model->training_request_status = 'Reactivated';
            if($model->save()){
                if($this->checkSendEmailSetting()){
                    $email_template = EmailTemplates::findOne(['dedicated_for' => 'EMAIL_TEMPLATE_REACTIVATING_TRAINING_REQUEST']);
                    if($email_template && $email_template->is_active == 1){
                        $content = $email_template->content;
                        $template_variables = $email_template->variables;
                        if($template_variables != null){
                            foreach($template_variables as $variable){
                                $code = $variable->variable->var_code;
                                EmailTemplates::replaceVariablesCode($content, $code, $model, null, null, null, $model->user);
                            }
                        }

                        $this->sendEmail($model->user->email, $content, 'إعادة تفعيل طلب التدريب');
                    }
                }

                Yii::$app->session->setFlash('request_reactivated', Yii::t('app', 'The request has been reactivated'));
                if($url == 'View'){
                    return $this->redirect(['view', 'id' => $id]);
                }
                return $this->redirect(['index']);
            }
            return var_dump($model->getErrors());
        }
    }

    public function actionAdvancedSearch($from_date = null, $to_date = null){
        $model = new TrainingRequests();

        if(Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            if(isset($data['TrainingRequests'])){
                $from_date = $data['TrainingRequests']['from_date'];
                $to_date = $data['TrainingRequests']['to_date'];

                return $this->redirect(['index', 'from_date' => $from_date, 'to_date' => $to_date]);
            }
        }

        $model->from_date = $from_date;
        $model->to_date   = $to_date;
        
        return $this->renderAjax('advanced-search', [
            'model' => $model
        ]);
    }

    public function actionPrintCertificate($id){
        $model = $this->findModel($id);
        $evaluation = $model->evaluation;
        $training = $evaluation->training;

        $start_date = explode('-', $training->start_date);
        $end_date   = explode('-', $training->end_date);

        $content = $this->renderPartial('_certificate', [
            'serial_number' => $model->serial_number,
            'full_name' => $model->full_name,
            'full_name_english' => $model->full_name_english,
            'gender' => $model->gender,
            'training_branch' => $training->branch->branch,
            'training_branch_english' => $training->branch->branch_english,
            'training_start_date_year' => $start_date[0],
            'training_start_date_month' => $this->getMonthName((int)$start_date[1]),
            'training_start_date_day' => $start_date[2],
            'training_end_date_year' => $end_date[0],
            'training_end_date_month' => $this->getMonthName((int)$end_date[1]),
            'training_end_date_day' => $end_date[2],
            'evaluation' => Yii::t('app', $evaluation->evaluation)
        ]);
    
        $pdf = new Pdf([
            'mode' => Pdf::MODE_UTF8, 
            'format' => Pdf::FORMAT_A4, 
            'orientation' => Pdf::ORIENT_PORTRAIT, 
            'destination' => Pdf::DEST_BROWSER, 
            'cssFile' => '@vendor/kartik-v/yii2-mpdf/src/assets/kv-mpdf-bootstrap.css',
            'cssInline' => '#f1 {width: 5px !important;}',
            'content' => $content, 
            'options' => ['title' => 'Certificate'],
        ]);
        
        return $pdf->render();
    }

    public function getMonthName($num){
        $monthes = [
            1 => 'January', 2 => 'February', 3 => 'March', 4 => 'April',
            5 => 'May', 6 => 'June', 7 => 'July', 8 => 'August',
            9 => 'September', 10 => 'October', 11 => 'November', 12 => 'December',
        ];
        return $monthes[$num];
    }

    public function checkSendEmailSetting(){
        $sending_emails_setting = Settings::findOne(['name' => 'sending_emails']);
        if($sending_emails_setting && $sending_emails_setting->value == 1){
            return true;
        }
        return false;
    }

    public function sendEmail($email, $content, $subject){
        Yii::$app->mailer->compose('mail', ['content' => $content])
            ->setFrom(Yii::$app->params['emailToSendMails'])
            ->setTo($email)
            ->setSubject($subject)
            ->send();
    }

    public function actionChangeEnglishFullName($id){
        if(Yii::$app->request->isAjax){
            $data = Yii::$app->request->get();
            $full_name_english = $data['TrainingRequests']['full_name_english'];
            $model = TrainingRequests::findOne($id);
            if($model){
                $model->scenario = TrainingRequests::UPDATE_ENGLISH_FULL_NAME;
                $model->full_name_english = $full_name_english;
                Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
                if($model->save()){
                    return ['status' => true, 'data' => Yii::t('app', 'The english full name has changed successfully')];
                }
                else{
                    $errors = $model->getErrors();
                    $msg = '';
                    foreach($errors as $error){
                        $msg .= $error[0] . '. ';
                    }
                    return ['status' => false, 'message' => $msg];
                }
            }
            return ['status' => true, 'error' => Yii::t('app', 'No Such User')];
        }
    }
}
