<?php
namespace customerapi\manager;

use common\models\EventRegistration;
use common\modules\event\manager\EventManager;
use customerapi\models\available\EventInterval;
use customerapi\models\dto\EventDTO;
use customerapi\models\dto\EventRegistrationDTO;
use yii\web\NotFoundHttpException;

class EventRegistrationManager
{

    /** Get Customer registrations
     * @throws \Exception
     */
    public function findCustomerRegistrationsWithEvent($idCustomer)
    {
        $interval = EventInterval::createInterval();
        $now =  new \DateTime();
        $eventRegistrations = EventRegistration::find()
            ->andWhere(['id_customer' => $idCustomer])
//            ->andWhere(['>=', 'event.start', $now->getTimestamp()])
            ->all();


        $result = [];
        $eventManager = new EventManager();
        foreach ($eventRegistrations as $registration ){
            $dto = EventRegistrationDTO::fromEventRegistration($registration);

            $event = $eventManager->findActiveEvent($registration->id_event, $interval,true);
            if ( isset($event)){
                $dto->event =  EventDTO::fromEventWithRelatedObjects($event);
                $result[] = $dto;
            }
        }

        return $result;
    }


    /**
     * @throws NotFoundHttpException
     */
    public function findRegistration($id_registration, $id_customer)
    {
        $interval = EventInterval::createInterval();

        $registration = EventRegistration::findOne(['id' => $id_registration, 'id_customer' => $id_customer]);

        if ( !isset($registration)){
            throw new NotFoundHttpException();
        }

        $eventManager = new EventManager();
        $event =  $eventManager->findActiveEvent($registration->id_event,$interval,true);

        if ( !isset($event)){
            throw new NotFoundHttpException();
        }

        return EventRegistrationDTO::fromEventRegistrationWithEvent($registration,$event);
    }



}
