<?php

namespace common\modules\event\models\timetable;

use common\components\DateUtil;
use common\modules\event\manager\EventManager;
use customerapi\models\available\EventInterval;
use DateTime;
use Exception;
use Yii;
use yii\base\Model;
use yii\data\ArrayDataProvider;

/**
 * @property string[] $tableHeaders
 * @property TimeTableModel $tableModel
 */
class TimeTableSearch extends Model
{

    public $startDateString;
    public $timestampStart;


    public $tableHeaders;
    public $tableModel;

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['startDateString',], 'date', 'format' => Yii::$app->formatter->dateFormat, 'timestampAttribute' => 'timestampStart', 'timeZone' => 'UTC'],
        ];
    }

    public function attributeLabels()
    {
        return [
            'startDateString' => 'Dátum'
        ];
    }


    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ArrayDataProvider
     * @throws Exception
     */
    public function search($params)
    {

        $today = null;
        $this->load($params);
        if ($this->validate()) {
            $today =  new DateTime(  );
            $today->setTimestamp($this->timestampStart);
        }
        $interval = EventInterval::createInterval($today);

        $em = new EventManager();
        $timeTable = $em->loadTimeTable($interval,"display");
        $this->tableModel = new TimeTableModel();
        $this->tableModel->timeTableMonth = $timeTable;

        /** @var DateTime[] $displayDates */
        $displayDates = $interval->getAllDisplayDates();

        for ($i = 0; $i < 7; $i++) {
            $timeTable->weekDayNames[] = DateUtil::getLocalDayName($displayDates[$i]->format('w'));
        }

        $this->tableHeaders = [''];
        $this->tableHeaders = array_merge($this->tableHeaders, $timeTable->weekDayNames);

        $dataProvider = new ArrayDataProvider([
            'allModels' => $timeTable->weeks
        ]);

        return $dataProvider;
    }
}
