<?php

namespace common\models;

use customerapi\models\details\EventEquipmentTypeAssignmentView;
use DateTime;
use DateTimeZone;
use Exception;
use Yii;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "event".
 *
 * @property integer $id
 * @property integer $start
 * @property integer $end
 * @property integer $id_room
 * @property integer $id_trainer
 * @property integer $id_user
 * @property integer $id_event_type
 * @property integer $seat_count
 * @property string $created_at
 * @property string $updated_at
 * @property string $deleted_at
 * @property integer $active
 * @property EventType $eventType
 * @property Trainer $trainer
 * @property Room $room
 * @property EventRegistration[] $eventRegistrations
 */
class Event extends ActiveRecord
{

    public $startDateString;
    public $endDateString;

    public $timestampStart;
    public $timestampEnd;


    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'event';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['startDateString',], 'date', 'format' => Yii::$app->formatter->datetimeFormat, 'timestampAttribute' => 'start',   'timeZone' => 'UTC'],
            [['endDateString',], 'date', 'format' => Yii::$app->formatter->datetimeFormat, 'timestampAttribute' => 'end' ,  'timeZone' => 'UTC'],
            [['id_trainer','id_room', 'id_event_type','seat_count'], 'required'],
            [['id_trainer','id_room', 'id_event_type','seat_count'], 'integer'],
            [['id_trainer','id_room', 'id_event_type','seat_count'], 'integer'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('event', 'ID'),
            'start' => Yii::t('event', 'Start'),
            'end' => Yii::t('event', 'End'),
            'id_room' => Yii::t('event', 'Id Room'),
            'id_trainer' => Yii::t('event', 'Id Trainer'),
            'id_event_type' => Yii::t('event', 'Id Event Type'),
            'created_at' => Yii::t('event', 'Created At'),
            'updated_at' => Yii::t('event', 'Updated At'),
            'deleted_at' => Yii::t('event', 'Deleted At'),
            'trainerName' => Yii::t('event', 'Trainer Name'),
            'roomName' => Yii::t('event', 'Room Name'),
            'eventTypeName' => Yii::t('event', 'Típus'),

            'event_start' => Yii::t('event', 'Start'),
            'event_end' => Yii::t('event', 'End'),
            'startDateString' => Yii::t('event', 'Start'),
            'endDateString' => Yii::t('event', 'End'),
            'status' => Yii::t('event', 'Status'),
            'seat_count' => Yii::t('event', 'Seat Count'),
            'eventRegistrationCount' => Yii::t('event', 'Event Registration Count'),
            'openSeatCount' => Yii::t('event', 'Open Seat Count'),
        ];
    }

    /**
     * @throws Exception
     */
    public function afterFind()
    {
        parent::afterFind(); // TODO: Change the autogenerated stub
        $format = 'Y.m.d H:i';
        $date = new DateTime();
        $date->setTimestamp($this->start);
        $date->setTimezone(new DateTimeZone('UTC'));
        $this->startDateString = $date->format($format);
        $date->setTimestamp($this->end);
        $this->endDateString = $date->format($format);
    }

    public function behaviors()
    {
        return ArrayHelper::merge(  [
            [
                'class' => TimestampBehavior::class,
                'value' => static function(){ return date('Y-m-d H:i:s' ); }
            ]
        ],
            parent::behaviors());
    }

    /** @noinspection PhpUnused */
    public function getEventType(){
        return $this->hasOne($this->getEventTypeClass(),['id' => 'id_event_type']);
    }

    /** @noinspection PhpUnused */
    public function getTrainer(){
        return $this->hasOne($this->getTrainerClass(),['id' => 'id_trainer']);
    }/** @noinspection PhpUnused */

    /**
     * @return Room|ActiveQuery
     */
    public function getRoom() {
        return $this->hasOne($this->getRoomClass(),['id' => 'id_room']);
    }/** @noinspection PhpUnused */

    /**
     * @return Card|ActiveQuery
     */
    public function getCard() {
        return $this->hasOne(Card::class,['id_card' => 'id_card']);
    }

    /**
     * @return  EventRegistration[]|ActiveQuery
     */
    public function getEventRegistrations(){
        return $this->hasMany(EventRegistration::class,['id_event' => 'id']);
    }

    /**
     * @return  EventEquipmentTypeAssignment[]|ActiveQuery
     */
    public function getEquipmentTypeAssignments(){
        return $this->hasMany($this->getEquipmentTypeAssignmentsClass(),['id_event' => 'id']);
    }

    /**
     * @return  EventRegistration[]|ActiveQuery
     */
    public function getActiveEventRegistrations(){
        return $this->hasMany(EventRegistration::class,['id_event' => 'id'])
            ->andWhere(
            [
                'event_registration.canceled_at' => null,
                'event_registration.deleted_at' => null,
            ]
        );
    }

    /**
     * @return  integer
     */
    public function getEventRegistrationCount(){
        $registrations = EventRegistration::find()->andWhere(['id_event' => $this->id])->all();
        $activeRegistrations = EventRegistration::filterActive($registrations);
        return count($activeRegistrations);
    }

    protected function getEquipmentTypeAssignmentsClass()
    {
        return EventEquipmentTypeAssignment::class;
    }

    /** @noinspection PhpUnused */
    public function getOpenSeatCount(){
        return $this->seat_count - $this->getEventRegistrationCount();
    }

    public function hasFreeSeats(){
        $registrations = EventRegistration::find()->andWhere(['id_event' => $this->id])->all();
        $activeRegistrations = EventRegistration::filterActive($registrations);
        $registrationCount = count($activeRegistrations) ;

        $seatCount = $this->seat_count;
        if ( !isset($seatCount ) || $seatCount === 0){
            $seatCount = PHP_INT_MAX;
        }

        return  $registrationCount <   $seatCount ;
    }

    public function canReserve(){
        if ( isset($this->deleted_at)){
            return false;
        }
        if ( !$this->hasFreeSeats()){
            return false;
        }
        return true;
    }

    public function canDelete(){
        if ( isset($this->deleted_at)){
            return false;
        }
        return true;
    }


    protected function getTrainerClass(){
        return Trainer::class;
    }
    protected function getEventTypeClass(){
        return EventType::class;
    }

    protected function getRoomClass(){
        return Room::class;
    }

}
