<?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;

use Contao\PageModel;
use Symfony\Component\EventDispatcher\Attribute\AsEventListener;
use Symfony\Component\HttpKernel\Event\RequestEvent;

final class LocalizeResponseListener
{
    #[AsEventListener('kernel.request')]
    public function onKernelRequest(RequestEvent $event): void
    {
        $request = $event->getRequest();

        if (!$event->isMainRequest()) {
            return;
        }

        /** @var PageModel $pageModel */
        $pageModel = $request->attributes->get('pageModel');
        if (!$pageModel instanceof PageModel) {
            return;
        }

        $pageModel->language = $request->getLocale();

        if ($pageModel->rootLanguage !== $pageModel->language) {
            $request->attributes->set('_machine_translated', true);
        }
    }
}
