<?php

namespace app\controllers;

use Yii;
use app\models\Evaluations;
use app\models\EvaluationsSearch;
use app\models\Trainings;
use app\models\TrainingRequests;
use app\models\Branches;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;

class EvaluationsController extends Controller
{
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'rules' => [
                    [
                        'allow' => false,
                        'roles' => ['?']
                    ],
                    [
                        'allow' => true,
                        'actions' => ['index', 'view', 'advanced-search'],
                        'roles' => ['Admin']
                    ],
                    [
                        'allow' => true,
                        'actions' => ['create', 'update', 'view', 'evaluated-trainees', 'get-evaluations-total'],
                        'roles' => ['Branch 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 EvaluationsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->setSort([
            'attributes' => [
                '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]
                ],
                'trainee_university_name' => [
                    'asc'  => ['training_requests.university_name' => SORT_ASC],
                    'desc' => ['training_requests.university_name' => SORT_DESC]
                ],
                'trainee_training_start_date' => [
                    'asc'  => ['trainings.start_date' => SORT_ASC],
                    'desc' => ['trainings.start_date' => SORT_DESC]
                ],
                'trainee_training_end_date' => [
                    'asc'  => ['trainings.end_date' => SORT_ASC],
                    'desc' => ['trainings.end_date' => SORT_DESC]
                ],
                'trainee_training_branch' => [
                    'asc'  => ['branches.branch' => SORT_ASC],
                    'desc' => ['branches.branch' => SORT_DESC]
                ],
                'trainee_mobile_phone' => [
                    'asc'  => ['training_requests.mobile' => SORT_ASC],
                    'desc' => ['training_requests.mobile' => SORT_DESC]
                ],
                'evaluation'
            ]
        ]);

        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,
                'branches' => Branches::find()->all()
            ]);
        }

        if($from_date != null && $to_date != null){
            $dataProvider->query->andWhere(['or', ['between', 'start_date', $from_date, $to_date], ['between', 'end_date', $from_date, $to_date]]);
        }
        elseif($from_date != null && $to_date == null){
            $dataProvider->query->andWhere(['or', ['>=', 'start_date', $from_date], ['>=', 'end_date', $from_date]]);
        }
        elseif($from_date == null && $to_date != null){
            $dataProvider->query->andWhere(['or', ['<=', 'start_date', $to_date], ['<=', 'end_date', $to_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($id)
    {
        $model = new Evaluations();
        $training_model = Trainings::findOne($id);
        $training_request_model = $training_model->trainingRequest;
        $training_request_model->scenario = TrainingRequests::UPDATE_STATUS;

        if ($model->load(Yii::$app->request->post())){
            $model->branch_user_id = Yii::$app->user->getId();
            $model->training_request_id = $training_request_model->id;
            $model->training_id = $id;
            $model->evaluation = $this->getEvaluationsTotal($model);
            if($model->save()) {
                $training_request_model->training_request_status = 'Finish';
                if($training_request_model->save()){
                    return $this->redirect(['view', 'id' => $model->id]);
                }
            }
        }

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

    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {
            $model->evaluation = $this->getEvaluationsTotal($model);
            if($model->save()){
                return $this->redirect(['view', 'id' => $model->id]);
            }
        }

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

    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

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

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

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

    public function actionEvaluatedTrainees(){
        $searchModel = new EvaluationsSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
        $dataProvider->query->andWhere(['branches.branch_user_id' => Yii::$app->user->getId()]);
        $dataProvider->setSort([
            'attributes' => [
                '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]
                ],
                'evaluation'
            ]
        ]);

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

    public function getEvaluationsTotal($model){
        $total = 0;
        $values = [
            'Weak' => 1,
            'Intermediate' => 2,
            'Good' => 3,
            'Very Good' => 4,
            'Excellent' => 5,
        ];
        $total += $values[$model->attendance_and_moral_behavior];
        $total += $values[$model->communication_skills];
        $total += $values[$model->self_confidence];
        $total += $values[$model->academic_knowledge];
        $total += $values[$model->ability_to_absorb_tasks];
        $total += $values[$model->speed_and_flexibility_in_completing_tasks];
        $total += $values[$model->working_within_the_team];
        $total += $values[$model->desire_to_learn];
        return $total * 10 / 4;
    } 

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

        if(Yii::$app->request->isPost){
            $data = Yii::$app->request->post();
            if(isset($data['Evaluations'])){
                $from_date = $data['Evaluations']['from_date'];
                $to_date = $data['Evaluations']['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
        ]);
    }
}
