<?php

namespace backend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Procurement;
use common\components\RoleDefinition;

/**
 * ProcurementSearch represents the model behind the search form about `common\models\Procurement`.
 */
class ProcurementSearch extends Procurement
{
	
	public $date_start;
	public $date_end;
	
	public $timestampStart;
	public $timestampEnd;
	
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [[ 'id_warehouse', 'id_user', 'id_product', ], 'integer'],
            [[ 'date_start',  ], 'date'  , 'timestampAttribute' => 'timestampStart' ,'timestampAttributeFormat' => 'yyyy-MM-dd'  ],
            [[ 'date_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 = Procurement::find();

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

        if ( RoleDefinition::isReception()){
        	$query->andWhere(['id_user' => Yii::$app->user->id ]);
        }
        
        $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;
        }

        
        if ( empty($this->date_start) ){
        	$this->timestampStart = '';
        }
        if ( empty($this->date_end) ){
        	$this->timestampEnd = '';
        }
        
        $query->andFilterWhere([
            'id_warehouse' => $this->id_warehouse,
            'id_user' => $this->id_user,
            'id_product' => $this->id_product,
        ]);
        
        $query->andFilterWhere([ '>=', 'created_at', $this->timestampStart ]   );
        $query->andFilterWhere([ '<', 'created_at', $this->timestampEnd ]   );


        return $dataProvider;
    }
}
