<?php

namespace common\modules\testings\controllers;

use Yii;
use yii\web\NotFoundHttpException;
use yii\web\Response;

use common\models\Settings;
use common\modules\testings\models\Test;
use common\modules\testings\models\Passing;
use common\modules\testings\models\Question;
use common\modules\testings\models\QuestionPassing;

class TestController extends \common\components\BaseController
{
	public static function actionsTitles()
	{
		return array(
			'Info' => 'Начало теста',
			'Pass' => 'Тестирование',
			'Finish-test' => 'Завершение теста',
			'Set-answer' => 'Запись ответа на вопрос',
			'Gen-pass' => 'Генерация тестирования',
			'Statistic' => 'Статистика тестирования',
            'Send-not-attempt' => 'Отправка письма при использовании попыток',
		);
	}

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

		if($model)
		{
			$passing = Passing::find()->where([
        		'user_id' => Yii::$app->user->identity->id,
        		'test_id' => $id
        	])->one();

        	if($passing && $passing->passed == Passing::PASSED)
        	{
        		return $this->redirect(['/testing/statistic/'.$passing->id]);
        	}

			return $this->render('info', [
				'model' => $model
			]);
		}
		else
		{
			throw new NotFoundHttpException('The requested page does not exist.');
		}
	}

	public function actionGenPass($id)
	{
		$transaction = Yii::$app->db->beginTransaction();

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

		try 
        {
        	$passing = Passing::find()->where([
        		'user_id' => Yii::$app->user->identity->id,
        		'test_id' => $id
        	])->one();

        	if(!$passing)
        	{
        		$passing = new Passing;
        		$passing->user_id = Yii::$app->user->identity->id;
        		$passing->test_id = $test->id;
        		$passing->status = Passing::NOT_STARTED;
        	}

        	if($passing && $passing->passed == Passing::PASSED)
	    	{
	    		return $this->redirect(['/testing/statistic/'.$passing->id]);
	    	}

        	// Проверяем статус прохождения
        	switch ($passing->status) 
			{
				case Passing::NOT_STARTED :
				case Passing::ENDED :
					$passing->start_date = date('d.m.Y H:i:s');
					$passing->passed = Passing::FAILED;
					$passing->end_date = null;
					$passing->percent = 0;
					$passing->attempt = 0;
					break;

				case Passing::STARTED :
					return $this->redirect(['/testing/pass/'.$passing->id]);
					break;

				case null :
					throw new NotFoundHttpException('Что-то пошло не так! Обратитесь к администратору.');
					break;
			}

			$passing->status = Passing::STARTED;
			$passing->save();

			// Берем все активные вопросы относящиеся к тесту
			$questions = Question::find()->where([
				'test_id' => $test->id,
				'is_active' => Question::ACTIVE,
			])->all();

			if(count($questions) < $test->questions)
			{
				throw new NotFoundHttpException('В тесте не хватает вопросов для заполнения прохождения! Обратитесь к администратору.');
			}

			// Перемешиваем
			shuffle($questions);

			// Чистим старые вопросы
			QuestionPassing::deleteAll(['passing_id' => $passing->id]);

			$s = true;
			for ($i = 1; $i <= $test->questions; $i++) 
			{
				$pq = new QuestionPassing;

				$pq->passing_id = $passing->id;
				$pq->question_id = $questions[$i]->id;
				$pq->question_text = $questions[$i]->text;
				$pq->answer_text = $questions[$i]->rightAnswer;

				if(!$pq->save())
				{
					$s = false;
				}
			}

			if($s)
			{
        		$transaction->commit();
			}

			if ($passing->end_date === null && $passing->status === Passing::STARTED)
			{
				return $this->redirect(['/testing/pass/'.$passing->id]);
			} 
			else 
			{
				return $this->redirect(['/testing/statistic/'.$passing->id]);
			}
        } 
        catch (\Exception $e) 
        {
            $transaction->rollBack();
            throw $e;
        }
	}

	public function actionPass($id)
	{
		$this->view->registerJsFile('/js/testing.js', ['position' => yii\web\View::POS_END ]);

		$passing = $this->findPassing($id);

		if($passing->attempt >= $passing->test->attempt || strtotime($passing->start_date) + ($passing->test->minutes * 60) < time())
		{
			$passing->end_date = date('d.m.Y H:i:s');
			$passing->status = Passing::ENDED;
			$passing->save(false, ['end_date', 'status']);

			return $this->redirect(['/testings/test/statistic', 'id' => $passing->id]);
		}

		switch ($passing->status) 
		{
			case Passing::STARTED :
				$passing->attempt += 1;
				$passing->save(false, ['attempt']);

				$count_answer = QuestionPassing::find()->where(['passing_id' => $id])->andWhere(['!=', 'user_answer', ''])->count();

				return $this->render('test', [
					'model' => $passing,
					'current_answer' => $count_answer + 1
				]);
				break;

			case Passing::PASSED :
				return $this->redirect(['/testings/test/statistic', 'id' => $passing->id]);
				break;
		}
	}

	public function actionSendNotAttempt($id)
	{
		if(Yii::$app->request->isAjax)
		{
			Yii::$app->response->format = Response::FORMAT_JSON;

			$passing = $this->findPassing($id);

			try 
	        {
	            $email = Settings::getValue('bids-support-email');

	            $message = 'Сообщение: ' . Yii::$app->request->post('message') . '<br>Прохождение: ' . $passing->id;

	            $headers = "MIME-Version: 1.0\r\n".
	                "Content-Transfer-Encoding: 8bit\r\n".
	                "Content-Type: text/html; charset=\"UTF-8\"\r\n".
	                "X-Mailer: PHP v.".phpversion()."\r\n".
	                "From: Ошибка в тестировании на TaskOn <".Settings::getValue('bids-support-email-from').">\r\n";

	            $subject = "Ошибка в тестировании на TaskOn";

	            @mail($email, $subject, $message, $headers);
	        } 
	        catch (Exception $e) 
	        {
	        }

			return [
				'success' => true,
				'message' => 'Сообщение отправлено!'
			];
		}
		else
		{
			throw new NotFoundHttpException('The requested page does not exist.');
		}
		
	}

	public function actionSetAnswer($id)
	{
		if(Yii::$app->request->isAjax)
		{
			Yii::$app->response->format = Response::FORMAT_JSON;
			
			$passing = $this->findPassing($id);

			$pq = QuestionPassing::find()->where([
				'question_id' => $_POST['question_id'],
				'passing_id' => $passing->id,
			])->one();

			$pq->user_answer = $_POST['userAnswer'];
			$pq->answer_time = ceil($_POST['time']);

            if($pq->save())
            {
				$passing->recountPassResult();
				$passing->percent = $passing->getPercentRight();

				if($passing->status == Passing::PASSED)
				{
					$passing->end_date = date('d.m.Y H:i:s');
				}

				$passing->save();

            	return [
					'success' => true,
					'percent' => $pq->passing->percent,
				];
            }
            else
            {
            	return [
					'massage' => 'Временные неполадки на сервере, попробуйте еще раз.'
				];
            }		
		}
		else
		{
			throw new NotFoundHttpException('The requested page does not exist.');
		}
	}

	public function actionFinishTest($id)
	{
		if(Yii::$app->request->isPost)
		{      
			Yii::$app->response->format = Response::FORMAT_JSON;

			$passing = $this->findPassing($id);

			// если тест сдан, результаты модифицировать нельзя
			if ($passing->end_date === null) 
			{
				$passing->end_date = date('d.m.Y H:i:s');
				$passing->status = Passing::ENDED;
				$passing->recountPassResult();
				$passing->percent = $passing->getPercentRight();
				$passing->addPoints();

                $passing->save();

				return ['status' => 'ok'];
			} 
			else 
			{
				return ['massage'=>'Тест уже был сдан!'];
			}
		}
		else
		{
			throw new NotFoundHttpException('The requested page does not exist.');
		}
	}

	public function actionStatistic($id)
	{
		$passing = $this->findPassing($id);

		if($passing->attempt >= $passing->test->attempt 
			|| ($passing->end_date && strtotime($passing->start_date) + ($passing->test->minutes * 60) < strtotime($passing->end_date)) 
			|| (!$passing->end_date && strtotime($passing->start_date) + ($passing->test->minutes * 60) < time()))
		{
			return $this->render('error', [
				'model' => $passing,
			]);
		}
		
		return $this->render('statistics', [
			'model' => $passing,
		]);
	}

	/**
     * Finds the Faq model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Faq the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Test::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }

    /**
     * Finds the Faq model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Faq the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findPassing($id)
    {
        if (($model = Passing::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
