<?php

namespace app\controllers;

use Yii;
use app\models\Interviews;
use app\models\InterviewsSearch;
use app\models\TrainingRequests;
use app\models\Branches;
use app\models\Settings;
use app\models\EmailTemplates;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

class InterviewsController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => false,
                        'roles' => ['?']
                    ],
                    [
                        '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()
    {
        $searchModel = new InterviewsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->setSort([
            'attributes' => [
                'id',
                'serial_number' => [
                    'asc'  => ['training_requests.serial_number' => SORT_ASC],
                    'desc' => ['training_requests.serial_number' => SORT_DESC]
                ],
                'trainee_full_name' => [
                    'asc'  => ['training_requests.full_name' => SORT_ASC],
                    'desc' => ['training_requests.full_name' => SORT_DESC]
                ],
                'trainee_mother_name' => [
                    'asc'  => ['training_requests.mother_name' => SORT_ASC],
                    'desc' => ['training_requests.mother_name' => SORT_DESC]
                ],
                'branch_id' => [
                    'asc'  => ['branches.branch' => SORT_ASC],
                    'desc' => ['branches.branch' => SORT_DESC]
                ],
                'date'
            ]
        ]);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'branches' => Branches::find()->all()
        ]);
    }

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

    public function actionCreate($training_request_id)
    {
        $model = new Interviews();
        $training_request_model = TrainingRequests::findOne($training_request_id);
        $training_request_model->scenario = TrainingRequests::UPDATE_STATUS;

        if ($model->load(Yii::$app->request->post())) {
            $adding_old_interviews_setting = Settings::findOne(['name' => 'capability_to_add_old_interviews']);
            if($adding_old_interviews_setting && $adding_old_interviews_setting->value == 0){
                if(strtotime($model->date) < time()){
                    Yii::$app->session->setFlash('could_not_add_old_interviews', Yii::t('app', 'Could Not Add Old Interviews'));
                    return $this->render('create', [
                        'model' => $model,
                        'training_request_model' => $training_request_model,
                        'branches' => Branches::find()->all()
                    ]);
                }
            }

            $model->training_request_id = $training_request_model->id;
            $model->created_by = Yii::$app->user->getId();
            if($model->save()){
                $training_request_model->training_request_status = 'Interview';
                if($training_request_model->save()){
                    if($this->checkSendEmailSetting()){
                        $email_template = EmailTemplates::findOne(['dedicated_for' => 'EMAIL_TEMPLATE_INTERVIEW_DATE_AND_PLACE']);
                        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_model, $model, null, null, $training_request_model->user);
                                }
                            }
    
                            $this->sendEmail($training_request_model->user->email, $content, 'تحديد مقابلة');
                        }
                    }
                    
                    return $this->redirect(['view', 'id' => $model->id]);
                }
            }
        }

        return $this->render('create', [
            'model' => $model,
            'training_request_model' => $training_request_model,
            'branches' => Branches::find()->all()
        ]);
    }

    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $training_request_model = TrainingRequests::findOne($model->training_request_id);
        $training_request_model->scenario = TrainingRequests::UPDATE_STATUS;

        // Check if there is capaiblity to update interview
        $update_interview_criteria = Settings::find()->where(['name' => 'capability_to_update_interview_before_hours_number'])->one();
        $update_interview_criteria = $update_interview_criteria != null ? $update_interview_criteria->value * 60 * 60 : 8 * 60 * 60; // If it doesn't exist, consider it as one day
        if(time() > strtotime($model->date) - $update_interview_criteria){
            return Yii::t('app', 'You could not update this interview');
        }

        if ($model->load(Yii::$app->request->post())) {
            $adding_old_interviews_setting = Settings::findOne(['name' => 'capability_to_add_old_interviews']);
            if($adding_old_interviews_setting && $adding_old_interviews_setting->value == 0){
                if(strtotime($model->date) < time()){
                    Yii::$app->session->setFlash('could_not_add_old_interviews', Yii::t('app', 'Could Not Add Old Interviews'));
                    return $this->render('update', [
                        'model' => $model,
                        'training_request_model' => $training_request_model,
                        'branches' => Branches::find()->all()
                    ]);
                }
            }

            if($model->save()){
                if($this->checkSendEmailSetting()){
                    $email_template = EmailTemplates::findOne(['dedicated_for' => 'EMAIL_TEMPLATE_INTERVIEW_DATE_AND_PLACE']);
                    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_model, $model, null, null, $training_request_model->user);
                            }
                        }

                        $this->sendEmail($training_request_model->user->email, $content, 'تحديد مقابلة');
                    }
                }

                return $this->redirect(['view', 'id' => $model->id]);
            }
        }

        return $this->render('update', [
            'model' => $model,
            'training_request_model' => $training_request_model,
            'branches' => Branches::find()->all()
        ]);
    }

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

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

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