<?php

namespace app\models;

use yii\db\ActiveRecord;

/**
 * @property int $id
 * @property int $game_id
 * @property string $date
 * @property string $start_time
 * @property string $address
 * @property float $price
 * @property string $created_at
 */
class Event extends ActiveRecord
{

    public $max_players = 10;

    public static function tableName()
    {
        return 'event';
    }

    public function rules()
    {
        return [
            [['game_id', 'date', 'start_time', 'address', 'price', 'max_players'], 'required'],
            ['date', 'date', 'format' => 'php:Y-m-d'],
            ['date', 'compare', 'compareValue' => date('Y-m-d'), 'operator' => '>=',
                'message' => 'Дата не может быть в прошлом'],
            ['start_time', 'match', 'pattern' => '/^([01]?[0-9]|2[0-3]):[0-5][0-9]$/'],
            ['price', 'number', 'min' => 0],
            ['max_players', 'integer', 'min' => 1, 'max' => 50],
            ['address', 'string', 'max' => 255],
        ];
    }

    public function attributeLabels()
    {
        return [
            'game_id' => 'Игра',
            'date' => 'Дата',
            'start_time' => 'Время начала',
            'address' => 'Адрес',
            'price' => 'Стоимость',
            'max_players' => 'Максимум игроков',
            'created_at' => 'Дата создания',
        ];
    }

    public function getGame()
    {
        return $this->hasOne(Game::class, ['id' => 'game_id']);
    }

    public function getApplications()
    {
        return $this->hasMany(Application::class, ['event_id' => 'id']);
    }

    public function getReviews()
    {
        return $this->hasMany(Review::class, ['event_id' => 'id']);
    }

    public function getAvailableSeats()
    {
        return $this->max_players - count($this->applications);
    }

    public function isFull()
    {
        return $this->getAvailableSeats() <= 0;
    }
}