<?php

namespace backend\models;

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

/**
 * AccountStateSearch represents the model behind the search form about `common\models\AccountState`.
 */
class AccountStateSearch extends AccountState
{
	
	public $type;
	public $start;
	public $end;
	
	public $timestampStart;
	public $timestampEnd;
	
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [[ 'id_account', 'type', 'id_user'], 'integer'],
        	[[ 'start',  ], 'date'  , 'timestampAttribute' => 'timestampStart' ,'timestampAttributeFormat' => 'yyyy-MM-dd'  ],
        	[[ 'end' , ], 'date'    , 'timestampAttribute' => 'timestampEnd' ,'timestampAttributeFormat' => 'yyyy-MM-dd' ],
        		
        ];
    }

    /**
     * @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();

        $query->innerJoinWith('account');
        
        if ( !RoleDefinition::isAdmin() ){
        	$query->innerJoin("user_account_assignment",'account_state.id_account = user_account_assignment.id_account' );
        	$query->andWhere(['user_account_assignment.id_user' => Yii::$app->user->id ]);
        	$query->andWhere(['account.type' => Account::TYPE_ALL ]);
        
        	if ( RoleDefinition::isReception()){
        		$query->andWhere(['transfer.id_user' => Yii::$app->user->id ]);
        	}
        	
        	Helper::restrictIfNotAdminTheStartDate($query, $this->timestampStart,['account_state.created_at'],"date" );
        }
        
        $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->orderBy(['created_at'  => SORT_DESC]);

        $query->andFilterWhere([
            'account_state.id_user' => $this->id_user,
            'account_state.id_account' => $this->id_account,
            'account_state.type' => $this->type,
        ]);

        $query->andFilterWhere([ '>=', 'account_state.created_at', $this->timestampStart ]   );
        $query->andFilterWhere([ '<', 'account_state.created_at', $this->timestampEnd ]   );
        
        return $dataProvider;
    }
}
