<?php

namespace backend\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 KeyCustomerSearch extends Key
{
	
	public $customer;
	
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            /*[['id_key', 'status', 'type'], 'integer'],
            [['number', 'created_at', 'updated_at'], 'safe'],*/
            [['number'], 'safe'],
            [['rfid_key'], '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)
    {
        $query = new Query();
        $query->select(['key.number','key.rfid_key','key.created_at','key.status','key.type','card_key_assignment.created_at as assigned_at']);
        $query->from('key');

        $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([
        ]);

        $query->innerJoin('card_key_assignment', 'card_key_assignment.id_key = key.id_key');
        $query->innerJoin('customer', 'card_key_assignment.id_card = customer.id_customer_card');
        $query->andWhere(['customer.id_customer' => $this->customer->id_customer]);

        return $dataProvider;
    }
}
