<?php

namespace common\models;

use Yii;
use yii\behaviors\TimestampBehavior;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "event_type".
 *
 * @property integer $id
 * @property string $name
 * @property string $theme
 * @property string $created_at
 * @property string $updated_at
 */
class EventType extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'event_type';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['name','theme'], 'required'],
            [['name'], 'unique'],
            [['name'], 'string', 'max' => 255],
            [['theme'], 'string', 'max' => 50]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('event-type', 'ID'),
            'name' => Yii::t('event-type', 'Name'),
            'created_at' => Yii::t('event-type', 'Created At'),
            'updated_at' => Yii::t('event-type', 'Updated At'),
        ];
    }

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

    public function asOptions(){
        $items  = ArrayHelper::map(EventType::find()->all(),'id','name');
        return ArrayHelper::merge(['' => \Yii::t('event-type','All')],$items);
    }

    public static function eventTypeOptions($all = false, $emptyString = false){
        $items  = ArrayHelper::map(EventType::find()->all(),'id','name');
        $extra = [];
        if ( $all ) {
            $extra = ['' => \Yii::t('event-type','All')];
        }
        if ( $emptyString ) {
            $extra = ['' => '' ];
        }
        return ArrayHelper::merge($extra,$items);
    }

    /**
     * Find the first ticket, which allows this event type
     * @param \common\models\Ticket[] $tickets the list of active tickets
     * @return Ticket|null
     */
    public function findTicketAllowingEventType($tickets){
        if  (!isset($tickets)){
            return null;
        }
        if ( sizeof($tickets) == 0 ){
            return null;
        }
        $possibleTickets = [];

        foreach ($tickets as $ticket ){
            if ( $ticket->hasOpenReservationCount() ){
                $possibleTickets[] = $ticket;
            }
        }

        if ( sizeof($possibleTickets) == 0 ){
            return null;
        }

        // TODO: implement bossiness logic to select ticket
        return $possibleTickets[0];
    }

    static function themes() {
        $themes = [];
        for ($x = 0; $x < 10; $x++) {
            $themes[$x] = "Színtéma " . ($x+1);
        }
        return $themes;
    }
}
