<?php

namespace app\models;

use dektrium\user\models\UserSearch as BaseUserSearch;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;

/**
 * UsersSearch represents the model behind the search form about `app\models\Users`.
 */
class UsersSearch extends BaseUserSearch
{

    public $role;
    public $role_user;
    public $member_phone;
    public $org_type;
    public $at_org;
    public $fio;
    public $status;
    public $flags;
    public $fax;
    /**
     * @inheritdoc
     */
    public function rules()
    {
        $rules = parent::rules();
        $rules[] = [['role', 'org_type', 'status', 'flags'], 'integer'];
        $rules[] = [['fio', 'at_org', 'member_phone', 'fax'], 'string', 'max' => 255];
        $rules[] = [['role_user'], 'safe'];
        return $rules;
    }

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

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

        $dataProvider->sort->attributes['at_org'] = [
            'asc' => ['profile.at_org' => SORT_ASC],
            'desc' => ['profile.at_org' => 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;
        }

        $query->joinWith(['profile']);

        $query->andFilterWhere([
            'id' => $this->id,
            'role' => $this->role,
            'org_type' => $this->org_type,
        ]);

        $query->andFilterWhere(['like', 'user.username', $this->username])
            ->andFilterWhere(['like', 'user.email', $this->email])
            ->andFilterWhere(['like', 'user.fio', $this->fio])
            ->andFilterWhere(['like', 'user.at_org', $this->at_org])
            ->andFilterWhere(['like', 'user.member_phone', $this->member_phone])
            ->andFilterWhere(['like', 'user.fax', $this->fax])
            ->andFilterWhere(['like', 'user.registration_ip', $this->registration_ip])
            ->andFilterWhere(['like', 'user.created_at', $this->created_at])            
            ->andFilterWhere(['user.role' => $this->role_user]);

        return $dataProvider;
    }

    public function attributeLabels(){
        $labels = parent::attributeLabels();
        $labels['at_org'] = Yii::t('app', 'At Org');
        $labels['role_user'] = Yii::t('app', 'Role');
        return $labels;
    }
}
