<?php

namespace common\modules\testings\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;

use common\modules\testings\models\Test;
use common\modules\testings\models\User;
use common\modules\testings\models\Passing;
use common\modules\testings\models\UserGroup;

class Session extends \common\components\ActiveRecordModel
{
    const PAGE_SIZE = 10;

	public $csv_file;
	public $file;

	const TEMP_FOLDER = '/uploads/temp/';

	const SCENARIO_UPLOAD = 'upload';

	const IS_PRESENT = 0;
	const IS_PAST = 1;
	const IS_FUTURE = 2;

    public static $state_list = [
        self::IS_PRESENT => 'Сессия в данный момент активна',
		self::IS_PAST => 'Сессия закончилась',
		self::IS_FUTURE => 'Сессия ещё не начиналась',
    ];

	public static function tableName()
	{
		return 'testings_sessions';
	}

	/**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            [
	            'class' => TimestampBehavior::className(),
	            'createdAtAttribute' => 'create_date',
	            'updatedAtAttribute' => null,
	            'value' => new Expression('NOW()'),
	        ],
        ];
    }

    public function name()
    {
        return 'Сессия';
    }

	public function rules()
	{
		return [
			[['name', 'start_date', 'end_date'], 'required', 'except' => self::SCENARIO_UPLOAD],
			[['name'], 'string', 'max' => 80, 'except' => self::SCENARIO_UPLOAD],
			[['csv_file'], 'file', 'skipOnEmpty' => false, 'extensions' => 'xls, xlsx', 'on' => self::SCENARIO_UPLOAD],
		];
	}

	public function getTests()
    {
        return $this->hasMany(Test::className(), ['session_id' => 'id']);
    }

    public function getGroups()
    {
        return $this->hasMany(UserGroup::className(), ['session_id' => 'id']);
    }

	public function attributeLabels() 
	{
		return [
			'name' => 'Наименование сессии',
			'start_date' => 'Дата начала',
			'end_date' => 'Дата окончания',
			'create_date' => 'Дата создания сессии',
			'csv_file' => 'Загрузить csv-файл',
		];
	}

	public function getUsersOverall() 
	{
		$query = Passing::find()->joinWith('test');

		$query->andWhere([
            Test::tableName() . '.session_id' => $this->id,
        ]);

        $query->groupBy(['user_id', 'test_id']);

		return $query->count();
	}

	public function getUsersPassed() 
	{
		$query = Passing::find()->joinWith('test');

		$query->andWhere([
            Test::tableName() . '.session_id' => $this->id,
            'passed' => Passing::PASSED,
        ]);

        $query->groupBy(['user_id', 'test_id']);

		return $query->count();
	}

	public function getUsersFailed() 
	{
		return $this->usersOverAll - $this->usersPassed;
	}

	public function getCurrentState() 
	{
		$start_date = strtotime($this->start_date);
		$end_date = strtotime($this->end_date);
		$now = strtotime(date('d.m.Y H:i'));

		$result = null;

		if ($start_date > $now) 
		{
			$result = self::IS_FUTURE;
		}

		if ($end_date <= $now) 
		{
			$result = self::IS_PAST;
		}

		if (($start_date <= $now) && ($end_date > $now)) 
		{
			$result = self::IS_PRESENT;
		}

		return $result;
	}

	public function getUsers() 
	{
		$query = User::find()->joinWith('passings.test');

		$query->andWhere([
             Test::tableName() . '.session_id' => $this->id,
        ]);

        $query->groupBy(['t.id']);

		return $query->all();
	}

	private function getPath()
	{
		return Yii::getAlias('@webroot') . self::TEMP_FOLDER;
	}

	public function upload()
    {
        if($this->validate()) 
        {
        	if(!file_exists($this->getPath()))
        	{
        		mkdir($this->getPath(), 0777, true);
        	}

        	$this->file = $this->getPath() . date('dmYHis-') . uniqid() . '.' . $this->csv_file->extension;
            $this->csv_file->saveAs($this->file);
            return true;
        } 
        else 
        {
            return false;
        }
    }

    public function deleteFile()
    {
    	if(file_exists($this->file))
        {
        	unlink($this->file);
        }
    }
}