<?php
/**
 * Created by IntelliJ IDEA.
 * User: rocho
 * Date: 2018.08.29.
 * Time: 21:58
 */

namespace customerapi\controllers;


use common\helpers\AppArrayHelper;
use common\helpers\AppDateTimeHelper;
use common\models\Event;
use common\models\EventRegistration;
use common\models\EventType;
use common\models\Trainer;
use common\modules\event\manager\EventManager;
use customerapi\manager\EventRegistrationManager;
use customerapi\models\available\EventInterval;
use customerapi\models\available\EventAvailable;
use customerapi\models\available\EventTypeAvailable;
use customerapi\models\available\RoomAvailable;
use customerapi\models\available\TrainerAvailable;
use customerapi\models\DayToDisplay;
use customerapi\models\details\EventDetailsView;
use customerapi\models\details\EventRegistrationView;
use customerapi\models\details\EventTypeDetailsView;
use customerapi\models\details\RoomDetailsView;
use customerapi\models\details\TrainerDetailsView;
use DateTime;
use Exception;
use yii\db\ActiveQuery;
use yii\db\Query;
use yii\web\Response;

/** @noinspection PhpUnused */

class EventController extends \customerapi\controllers\CustomerApiController
{
    /** @noinspection PhpUnused */
    /**
     *  interface EventsAvailableResponse {
     * days: DayToDisplay[];
     * events: Event[];
     * }
     * @throws Exception
     */
    public function actionAvailable()
    {
        $interval = EventInterval::createInterval();

        // compose day objects
        $dates = [];
        for ($i = 0; $i < $interval->daysToDisplay; $i++) {
            $day = clone $interval->firstDisplayDate;
            $day->modify('+' . $i . ' day');
            $dayToDisplay = new DayToDisplay();
            $dayToDisplay->date = $day->getTimestamp();
            $afterFirstActiveDay = $interval->firstActiveDate < $day || $interval->firstActiveDate == $day;
            $beforeLastActiveDay = $interval->lastActiveDate > $day || $interval->lastActiveDate == $day;

            $dayToDisplay->active = ($afterFirstActiveDay && $beforeLastActiveDay);
            $dayToDisplay->comment = '#' . idate('W', $day->getTimestamp()) . ' - ' . $day->format('Y-m-d H:i:s');
            $dayToDisplay->events = [];
            $dates[] = $dayToDisplay;
        }

        $eventManager = new EventManager();
        $events = $eventManager->findActiveEvents($interval);
        $trainers = AppArrayHelper::objectArrayToMapById( TrainerAvailable::find()->all() );
        $rooms =  AppArrayHelper::objectArrayToMapById( RoomAvailable::find()->all()  );
        $eventTypes =  AppArrayHelper::objectArrayToMapById( EventTypeAvailable::find()->all()  );



        $availableEvents = [];

        /** @var $event /common/models/Event $event */
        foreach ($events as $event ){
            $availableEvent = EventAvailable::fromEvent($event);
            $availableEvent->trainer = $trainers[$event->id_trainer];
            $availableEvent->room = $rooms[$event->id_room];
            $availableEvent->eventType = $eventTypes[$event->id_event_type];

            $totalRegistrations = $eventManager->findActiveRegistrations($event->id);
            $customerRegistration = EventRegistration::filterForCustomer($totalRegistrations,\Yii::$app->user->id);
            $availableEvent->registrationCount = count($totalRegistrations);
            $availableEvent->eventRegistrations = $customerRegistration;
            $availableEvent->hasFreeSeats =  $availableEvent->registrationCount < $availableEvent->seat_count;


            $availableEvents[] = $availableEvent;


        }

        // set events per day
        /** @var EventAvailable $event */
        foreach ($availableEvents as $event) {
            $eventDay = new DateTime();
            $eventDay->setTimestamp($event->start);
            $eventDay->setTime(0, 0);

            /** @var DayToDisplay $date */
            foreach ($dates as $date) {
                if ($date->date === $eventDay->getTimestamp()) {
                    $date->events[] = $event;
                    break;
                }
            }
        }

        $eventTypes = EventTypeDetailsView::find()->all();
        $trainers = TrainerDetailsView::find()->all();

        return
            $this->asJson([
                'interval' => $interval,
                'dates' => $dates,
                'trainers' => $trainers,
                'eventTypes' => $eventTypes
            ]);
    }


    /**
     * @param integer $id_event the id of the event
     * @return Response     the response
     * @throws \yii\base\Exception on any error
     * @throws Exception
     */
    public function actionEvent($id_event)
    {
        $interval = EventInterval::createInterval();
        $manger = new EventManager();
        try {
            /** @var Event $event */
            $event = $manger->findActiveEvent($id_event,$interval);
            $result = new EventDetailsView();
            $result->id = $event->id;
            $result->start = $event->start;
            $result->end = $event->end;
            $result->deleted_at =AppDateTimeHelper::convertMySqlDatetimeToPhpInteger( $event->deleted_at);
            $result->seatCount = $event->seat_count;
            $result->trainer = TrainerDetailsView::findOne($event->id_trainer);
            $result->room = RoomDetailsView::findOne($event->id_room);
            $result->eventType = EventTypeDetailsView::findOne($event->id_event_type);
            $registrations = EventRegistrationView::find()->andWhere(['id_event' => $event->id,'id_customer' => \Yii::$app->user->id])->all();
            $allActiveRegistrations = EventRegistration::filterActive($registrations);
            $customerActiveRegistrations = EventRegistration::filterForCustomer($allActiveRegistrations,\Yii::$app->user->id);
            $result->reservationCount = count($allActiveRegistrations);
            $result->registrations = $customerActiveRegistrations;
            $result->hasFreeSeats = $event->seat_count > count($allActiveRegistrations);



            return $this->asJson($result);
        } catch (Exception $e) {
            throw new \yii\base\Exception($e->getMessage());
        }
    }


}
