<?php

namespace frontend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\AccountState;
use common\components\Helper;

/**
 * AccountstateSearch represents the model behind the search form about `common\models\AccountState`.
 */
class AccountstateSearch extends AccountState
{
	
	public $start;
	public $end;
	
	public $timestampStart;
	public $timestampEnd;
	
		
	public $accounts;
	public $users;
    /**
     * @inheritdoc
     */
    public function rules()
    {
       return [
            [[ 'start',  ], 'date', 'format' =>Yii::$app->formatter->datetimeFormat  , 'timestampAttribute' => 'timestampStart' ,'timestampAttributeFormat' => 'yyyy-MM-dd HH:mm' ,'timeZone' => 'UTC' ],
            [[ 'end' , ], 'date'  ,'format' =>Yii::$app->formatter->datetimeFormat  , 'timestampAttribute' => 'timestampEnd' ,'timestampAttributeFormat' => 'yyyy-MM-dd HH:mm' ,'timeZone' => 'UTC' ],
       		[ [ 'id_account','id_user' ,'type'  ] , 'integer'],
        ];
    }

    /**
     * @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)
    {
        $query = AccountState::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        	'sort' => false
        ]);

        $this->load($params);

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

        
        $query->innerJoinWith('account');
        $query->innerJoinWith('account.userAccountAssignments');
        $query->andWhere(['user_account_assignment.id_user' => Yii::$app->user->id]);
        $query->andFilterWhere([
        		'account_state.id_user' => $this->id_user,
        		'account_state.type' => $this->type,
        		'account_state.id_account' => $this->id_account,
        ]);
        
        $query->andFilterWhere([ '>=', 'account_state.created_at', $this->timestampStart ]   );
        $query->andFilterWhere([ '<', 'account_state.created_at', $this->timestampEnd ]   );
        
        Helper::restrictIfNotAdminTheStartDate($query, $this->timestampStart, ['account_state.created_at']);
        
        $query->orderBy( 'created_at desc'  );

        $query->limit = 20;
        
        return $dataProvider;
    }
}
