<?php

namespace frontend\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Key;
use yii\db\Query;

/**
 * KeySearch represents the model behind the search form about `common\models\Key`.
 */
class KeySearch extends Key
{
	
	public $card;
	
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
        ];
    }

    /**
     * @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 = new Query();
    	$query->select([ 'user.username as user_username', 'card.id_card as card_id_card', 'key.id_key as key_id_key', 'card.number as card_number' ,  'key.number as key_number','card_key_assignment.created_at as assign_created_at'] );
    	$query->from('card');
    	$query->innerJoin('card_key_assignment','card.id_card = card_key_assignment.id_card' );
    	$query->innerJoin('key','key.id_key = card_key_assignment.id_key' );
    	$query->innerJoin('user','user.id = card_key_assignment.id_user' );
    	$query->andWhere(['card_key_assignment.id_card' => $this->card->id_card]);
    	$query->orderBy( ['card_key_assignment.created_at' => SORT_ASC] );

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

        $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->andFilterWhere([
            'type' => $this->type,
        ]);

        $query->andFilterWhere(['like', 'number', $this->number])
            ->andFilterWhere(['like', 'rfid_key', $this->rfid_key]);

        return $dataProvider;
    }
}
