<?php

namespace app\models;

use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\ItemVariations;

/**
 * ItemVariationsSearch represents the model behind the search form of `app\models\ItemVariations`.
 */
class ItemVariationsSearch extends ItemVariations
{
    /**
     * {@inheritdoc}
     */

    public $arabic_name;
    public $english_name;
    public $main_category;
    public $sub_category;

    public function rules()
    {
        return [
            [['id', 'item_id'], 'integer'],
            [['arabic_desription', 'english_description', 'arabic_details', 'english_details', 'arabic_name', 'english_name', 'main_category', 'sub_category'], 'safe'],
            [['price'], 'number'],
        ];
    }

    /**
     * {@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 = ItemVariations::find();

        // add conditions that should always apply here

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

        // $query->joinWith('item');
        $query->joinWith('item.mainCategory');

        $this->load($params);
        
        $dataProvider->sort->attributes['arabic_name'] = [
            'asc' => ['items.arabic_name' => SORT_ASC],
            'desc' => ['items.arabic_name' => SORT_DESC],
        ];

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

        $dataProvider->sort->attributes['main_category'] = [
            'asc' => ['items.main_category_id' => SORT_ASC],
            'desc' => ['items.main_category_id' => SORT_DESC],
        ];

        $dataProvider->sort->attributes['sub_category'] = [
            'asc' => ['items.sub_category_id' => SORT_ASC],
            'desc' => ['items.sub_category_id' => SORT_DESC],
        ];

        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;
        }

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            //'item_id' => $this->item_id,
            'price' => $this->price,
            'main_category_id' => $this->main_category,
            'sub_category_id' => $this->sub_category,
        ]);
        
        $query->andFilterWhere(['like', 'items.arabic_name', $this->arabic_name])
            ->andFilterWhere(['like', 'items.english_name', $this->english_name]);

        return $dataProvider;
    }
}
