<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CmsBundle\EventListener\ContentElement;

use Contao\CoreBundle\DependencyInjection\Attribute\AsHook;
use Contao\CoreBundle\Routing\ScopeMatcher;
use Contao\CoreBundle\Security\Authentication\Token\TokenChecker;
use Contao\Model;
use Ferienpass\CoreBundle\Repository\EditionRepository;
use Symfony\Component\HttpFoundation\RequestStack;

#[AsHook('isVisibleElement')]
class VisibleElementListener
{
    public function __construct(private readonly EditionRepository $editions, private readonly TokenChecker $tokenChecker, private readonly RequestStack $requestStack, private readonly ScopeMatcher $scopeMatcher)
    {
    }

    public function __invoke(Model $element, bool $visible): bool
    {
        if (false === $visible) {
            return false;
        }

        $request = $this->requestStack->getCurrentRequest();

        if ($request instanceof \Symfony\Component\HttpFoundation\Request && $this->scopeMatcher->isFrontendRequest($request) && $element->ferienpass_task_condition) {
            if ($this->tokenChecker->isPreviewMode()) {
                // Do not apply further logic.
                return $visible;
            }

            $passEdition = $this->editions->findOneWithActiveTask((string) $element->ferienpass_task_condition);

            if ($element->ferienpass_task_condition_inverted) {
                return !$passEdition instanceof \Ferienpass\CoreBundle\Entity\Edition;
            }

            return $passEdition instanceof \Ferienpass\CoreBundle\Entity\Edition;
        }

        return $visible;
    }
}
