<?php

namespace Ig\IgReservations\ViewHelpers\Reservation;

use Ig\IgReservations\Domain\Model\Reservation;
use TYPO3\CMS\Core\Context\Context;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractConditionViewHelper;

class CanEditViewHelper extends AbstractConditionViewHelper
{
    /**
     * Initialize arguments
     */
    public function initializeArguments(): void
    {
        parent::initializeArguments();
        $this->registerArgument('reservation', Reservation::class, 'reservation to test', true);
    }

    /**
     * Static method which can be overridden by subclasses. If a subclass
     * requires a different (or faster) decision then this method is the one
     * to override and implement.
     *
     * @param array<string, mixed> $arguments
     * @param RenderingContextInterface $renderingContext
     * @return bool
     */
    public static function verdict(array $arguments, RenderingContextInterface $renderingContext): bool
    {
        $reservation = $arguments['reservation'];

        $event = $reservation->getEvent();

        if (!$event) {
            return false;
        }
        $calendar = $event->getCalendar();
        $acl = $calendar->getAcl();
        $reservationFrontendUser = $reservation->getFrontendUser();

        // Nicht Admin und nicht Reservation von User
        if (!$acl->getIsAdmin()) {
            $context = GeneralUtility::makeInstance(Context::class);
            $frontendUserId = $context->getPropertyFromAspect('frontend.user', 'id');
            if (!$reservationFrontendUser || $reservationFrontendUser->getUid() != $frontendUserId) {
                return false;
            }
        }
        $beginDateTime = $acl->getCancelBeginDateTime();

        if ($beginDateTime !== null && $event->getDateTime() < $beginDateTime) {
            return false;
        }
        $endDateTime = $acl->getCancelEndDateTime();
        if ($endDateTime !== null && $event->getDateTime() >= $endDateTime) {
            return false;
        }
        return true;
    }
}
