<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Visitschedule;
use app\models\Attandance;

/**
 * VisitscheduleSearch represents the model behind the search form about `app\models\Visitschedule`.
 */
class VisitscheduleSearch extends Visitschedule
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['sch_id', 'date_of_screening', 'no_of_days', 'actual_date', 'visit_date', 'window_start', 'window_end', 'create_time', 'create_user', 'update_time', 'update_user', 'record_date'], 'integer'],
            [['participant_id', 'visit_code', 'status'], '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 = Visitschedule::find();
		
		$attntable=Attandance::tableName();	
        $today = strtotime(date("Y/m/d"));		
        $query = Visitschedule::find()->where("participant_id IN (SELECT pid FROM $attntable where $attntable.pid=participant_id and $attntable.record_date = $today and $attntable.out_interviewer IS NULL)")->andWhere(["IS", "visit_date", NULL])->andWhere(["<", "window_end", $today]);


        // add conditions that should always apply here

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

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

        // grid filtering conditions
        $query->andFilterWhere([
            'sch_id' => $this->sch_id,
            'date_of_screening' => $this->date_of_screening,
            'no_of_days' => $this->no_of_days,
            'actual_date' => $this->actual_date,
            'visit_date' => $this->visit_date,
			'visit_code' => $this->visit_code,
            'window_start' => $this->window_start,
            'window_end' => $this->window_end,
            'create_time' => $this->create_time,
            'create_user' => $this->create_user,
            'update_time' => $this->update_time,
            'update_user' => $this->update_user,
            'record_date' => $this->record_date,
        ]);

        $query->andFilterWhere(['like', 'participant_id', $this->participant_id])           
            ->andFilterWhere(['like', 'status', $this->status]);

        return $dataProvider;
    }
}
