<?php

namespace app\models;

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

/**
 * TrainingsSearch represents the model behind the search form of `app\models\Trainings`.
 */
class TrainingsSearch extends Trainings
{
    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['id', 'training_request_id', 'branch_id', 'created_by'], 'integer'],
            [['approved_date', 'start_date', 'end_date', 'trainee_full_name', 'trainee_mother_name', 'serial_number'], '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 = Trainings::find();

        // add conditions that should always apply here

        $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->joinWith('trainingRequest');
        $query->joinWith('branch');

        // grid filtering conditions
        $query->andFilterWhere([
            'id' => $this->id,
            'training_request_id' => $this->training_request_id,
            'approved_date' => $this->approved_date,
            'start_date' => $this->start_date,
            'end_date' => $this->end_date,
            'branch_id' => $this->branch_id,
        ]);

        $query->andFilterWhere(['like', 'training_requests.full_name', $this->trainee_full_name])
            ->andFilterWhere(['like', 'training_requests.mother_name', $this->trainee_mother_name])
            ->andFilterWhere(['like', 'training_requests.serial_number', $this->serial_number]);

        return $dataProvider;
    }
}
