<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Subscriptions;

/**
 * SubscriptionsSearch represents the model behind the search form about `app\models\Subscriptions`.
 */
class SubscriptionsSearch extends Subscriptions
{

    public $category_name;
    public $fio;
    public $email;
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['category_id'], 'integer'],
            [['fio', 'category_name', 'email'], 'string'],
        ];
    }

    /**
     * @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 = Subscriptions::find()->joinWith(['category', 'user']);

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => [
                'defaultOrder' => ['created_at' => SORT_DESC],
            ]
        ]);

        $dataProvider->sort->attributes['email'] = [
            'asc' => ['user.email' => SORT_ASC],
            'desc' => ['user.email' => SORT_DESC],
        ];

        $dataProvider->sort->attributes['fio'] = [
            'asc' => ['user.fio' => SORT_ASC],
            'desc' => ['user.fio' => SORT_DESC],
        ];

        $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(!Yii::$app->user->can('admin')){
            $query->andWhere(['user_id' => Yii::$app->user->getId()]);
        }

        $query->andFilterWhere([
            'category_id' => $this->category_id,
        ]);
        $query->andFilterWhere(['like', 'user.email', $this->email])
        ->andFilterWhere(['like', 'user.fio', $this->fio]);

        return $dataProvider;
    }
}
