<?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\ViewHelper\AbstractConditionViewHelper;

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

    /**
     * This method decides if the condition is TRUE or FALSE. It can be overriden in extending viewhelpers
     * to adjust functionality.
     *
     * @param array $arguments ViewHelper arguments to evaluate the condition for this ViewHelper, allows for
     *                         flexiblity in overriding this method.
     * @return bool
     */
    protected static function evaluateCondition($arguments = null)
    {
        $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;
    }
}
