<?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\CoreBundle\EventListener;

use Ferienpass\CoreBundle\Settings\PageConfigManager;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Twig\Environment;

#[AsEventListener(event: KernelEvents::REQUEST, priority: 100)]
class RequestConfigListener
{
    public function __construct(private readonly PageConfigManager $pageConfigManager, private readonly Environment $twig)
    {
    }

    public function __invoke(RequestEvent $event): void
    {
        if (!$event->isMainRequest()) {
            return;
        }

        $config = $this->pageConfigManager->getPageConfig();

        if ($language = $config->getLanguage()) {
            $event->getRequest()->setLocale($language);
        }

        if ($timezone = $config->getTimezone()) {
            // Only change view timezone, never server timezone (i.e., date_default_timezone_set())
            $this->twig->getExtension(\Twig\Extension\CoreExtension::class)->setTimezone($timezone);
        }
    }
}
