<?php

namespace common\modules\testings\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use yii\helpers\ArrayHelper;

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

class SearchPassing extends Passing
{
	public $filter_user_email;
	public $filter_user_last_name;

	/**
     * @inheritdoc
     */
    public function rules()
	{
		return [
			[['id', 'user_id', 'test_id', 'status'], 'integer'],
			[['id', 'user_id', 'test_id', 'status', 'end_date', 'filter_user_email', 'filter_user_last_name'], 'safe'],
		];
	}

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params, $order = null, $limit = null)
    {
        $query = Passing::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => ['pageSize' => self::PAGE_SIZE],
            'sort' => [
                'defaultOrder'=>'start_date DESC',
            ],
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $dataProvider->query = $this->query($params, $order, $limit);

        return $dataProvider;
    }

    public function query($params, $order = null, $limit = null)
    {
        $query = Passing::find();

        $with = ['test' => true];

        $query->andFilterWhere([
            'id' => $this->id,
            'user_id' => $this->user_id,
            'test_id' => $this->test_id,
            'start_date' => $this->start_date,
            Test::tableName() . '.session_id' => Yii::$app->request->get('session'),
        ]);

        if($this->filter_user_email)
        {
            $with['user'] = true;
            $query->andFilterWhere(['like', User::tableName() . '.email', $this->filter_user_email]);
        }

        if($this->filter_user_last_name)
        {
            $with['user'] = true;
            $query->andFilterWhere(['like', User::tableName() . '.last_name', $this->filter_user_last_name]);
        }

        //         $tpassing = Yii::app()->request->getQuery('Passing');

//      $end_date = 'CONCAT( RIGHT( LEFT( end_date, 10 ) , 4 ) ,  "-", TRIM( 
// TRAILING CONCAT(  ".", SUBSTRING_INDEX( LEFT( end_date, 10 ) ,  ".", -1 ) ) 
// FROM TRIM( 
// LEADING CONCAT( SUBSTRING_INDEX( LEFT( end_date, 10 ) ,  ".", 1 ) ,  "." ) 
// FROM LEFT( end_date, 10 ) ) ) ,  "-", LEFT( end_date, 2 ) )';

//      if (($tpassing['end_date']) && (Yii::app()->request->getQuery('date_to'))) {

//          $criteria->addCondition($end_date.' BETWEEN "'.$tpassing['end_date'].'" AND "'.Yii::app()->request->getQuery('date_to').'"');
//      }
//      elseif(Yii::app()->request->getQuery('date_to')) {
//          $criteria->addCondition($end_date.' < "'.Yii::app()->request->getQuery('date_to').'"');
//      }
//      elseif($tpassing['end_date']) {
//          $criteria->addCondition($end_date.' > "'.Yii::app()->request->getQuery('end_date').'"');
//      }

        // switch ($this->status) 
        // {
        //     case Passing::AUTH:
        //         $with['user'] = true;
        //         $query->andFilterWhere(['>', 'ser.start_date', '2014-06-05 00:00:00']);
        //         $query->andFilterWhere([User::tableName() . '.is_auth' => 0]);
        //         break;

        //     case Passing::STARTED:
        //         $query->andFilterWhere([
        //             'status' => 0,
        //             'end_date' => null,
        //             Mistake::tableName() . '.passing_id' => null
        //         ]);
        //         break;

        //     case Passing::MISTAKE:
        //         $with['mistake'] = true;
        //         $query->andFilterWhere(['=', Mistake::tableName() . '.passing_id', 'id']);
        //         break;

        //     case Passing::PASSED:
        //         $with['mistake'] = true;
        //         $query->andFilterWhere([
        //             'status' => 1,
        //             Mistake::tableName() . '.passing_id' => null
        //         ]);
        //         break;

        //     case Passing::FAILED:
        //         $with['mistake'] = true;
        //         $query->andFilterWhere([
        //             'status' => 0,
        //             Mistake::tableName() . '.passing_id' => null
        //         ]);
        //         $query->andFilterWhere(['not', 'end_date', null]);
        //         break;

        //     case Passing::NOT_STARTED:
        //         $with['mistake'] = true;
        //         $query->andFilterWhere([
        //             'status' => null,
        //             Mistake::tableName() . '.passing_id' => null
        //         ]);
        //         break;
        // }

        if(!empty($order))
            $query->orderBy($order);

        if(!empty($limit))
            $query->limit($limit);

        $query->joinWith(array_keys($with));

        return $query;
    }

    public function getCountPassed() 
    {
        $query = $this->query(Yii::$app->request->queryParams);

        $query->andWhere(['status' => 1]);
        
        return $query->count();
    }

    public function getCountNotPassed()
    {
        $query = $this->query(Yii::$app->request->queryParams);

        $query->andWhere(['status' => 0]);
        
        return $query->count();
    }

    public function getCountPassedError() 
    {
        $query = $this->query(Yii::$app->request->queryParams);

        $query->andWhere(['status' => 2]);
        
        return $query->count();
    }

    public function getCountNotPassedYet() 
    {
        $query = $this->query(Yii::$app->request->queryParams);

        $query->andWhere(['status' => null]);
        
        return $query->count();
    }
}
