<?php

declare(strict_types=1);

/*
 * This file is part of the VITICORE2 package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Bridge\Symfony\Bundle\Controller\Site;

use CpCreation\VitiCore\PageBuilder\Repository\PageRepository;
use CpCreation\VitiCore\PageBuilder\Repository\PageSectionRepository;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\Routing\Attribute\Route;

final class CmsPageController extends AbstractController
{
    public function __construct(
        private readonly PageRepository $pageRepository,
        private readonly PageSectionRepository $pageSectionRepository,
    ) {
    }

    #[Route(path: [
        'fr' => '/{path}',
        'en' => '/en/{path}',
    ], name: 'cms_page', requirements: ['path' => '.+'], priority: -1000)]
    public function show(Request $request, string $path): Response
    {
        $locale = $request->getLocale();
        $path = mb_trim($path, '/');
        $page = $this->pageRepository->findOnePublishedCmsByPath($path, $locale);
        if (null === $page) {
            throw new NotFoundHttpException();
        }

        return $this->render('page/show.html.twig', [
            'page' => $page,
            'pageSections' => $this->pageSectionRepository->findActiveForPageCode($page->getCode()),
            'pageBuilderMode' => false,
        ]);
    }
}
