<?php

namespace common\modules\event\models;

use common\components\Helper;
use common\components\RoleDefinition;
use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use common\models\Event;
use yii\db\Expression;
use yii\db\Query;
use yii\rbac\Role;

/**
 * EventSearch represents the model behind the search form about `common\models\Event`.
 */
class EventSearch extends Event
{

    public $roomName;
    public $trainerName;
    public $eventTypeName;


    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'roomName', 'trainerName', 'eventTypeName'], 'string', 'max' => 250],
            [['startDateString',], 'date', 'format' => Yii::$app->formatter->datetimeFormat, 'timestampAttribute' => 'start', 'timeZone' => 'UTC'],
            [['endDateString',], 'date', 'format' => Yii::$app->formatter->datetimeFormat, 'timestampAttribute' => 'end', 'timeZone' => 'UTC'],
        ];
    }

    /**
     * @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 = new Query();

        $query->select([
            'event.id as event_id',
            'event.start as event_start',
            'event.end as event_end',
            'event.created_at as event_created_at',
            'event.updated_at as event_updated_at',
            'event.deleted_at as event_deleted_at',
            'event.seat_count as event_seat_count',
            'trainer.name as trainer_name',
            'room.name as  room_name',
            'event_type.name as event_type_name',
            'event_type.theme as event_type_theme',
            new Expression('count(event_registration.id) as registration_count')
        ]);

        $query->from("event");
        $query->innerJoin('trainer', 'event.id_trainer = trainer.id');
        $query->innerJoin('room', 'event.id_room = room.id');
        $query->innerJoin('event_type', 'event_type.id = event.id_event_type');
        $query->leftJoin('event_registration', 'event_registration.id_event = event.id and event_registration.canceled_at is null and event_registration.deleted_at is null ');
        $query->groupBy(
            [
                'event_id',
                'event_start',
                'event_end',
                'event_created_at',
                'event_updated_at',
                'event_deleted_at',
                'trainer_name',
                'room_name',
                'event_type_name',
            ]
        );

        if ( RoleDefinition::isTrainer() ){
            $query->innerJoin('user_trainer_assignment', 'user_trainer_assignment.id_trainer = trainer.id' );
            $query->andWhere(['user_trainer_assignment.id_user' => \Yii::$app->user->id ]);
        }


        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'sort' => [
                'defaultOrder' => [
                    'event_start' => SORT_DESC
                ],
                'attributes' => Helper::mkYiiSortItems([
                    ['event_id'],
                    ['event_start'],
                    ['event_end'],
                    ['trainer_name'],
                    ['room_name'],
                    ['event_type_name'],
                    ['customer_name'],
                    ['event_created_at'],
                    ['event_updated_at'],
                    ['event_deleted_at'],
                    ['registration_count'],
                    ['event_seat_count'],
                ]),
            ]
        ]);

        $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->andFilterWhere([
            'event.id' => $this->id,
        ]);
        $query->andFilterWhere(
            ['room.id' => $this->roomName]
        );

        $query->andFilterWhere(
            ['trainer.id' => $this->trainerName]
        );

        $query->andFilterWhere(
            ['event_type.id' => $this->eventTypeName]
        );

        if (isset($this->start)) {
            $query->andWhere(
                [
                    '>=',
                    'start',
                    $this->start
                ]
            );
        }

        if (isset($this->end)) {
            $query->andWhere(
                [
                    '<=',
                    'end',
                    $this->end
                ]
            );
        }

        return $dataProvider;
    }
}
