<?php

/*
 * This file is part of the Serenity 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\Document\BuilderDocumentRenderer;
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\Routing\Attribute\Route;

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

    #[Route(path: [
        'fr' => '/',
        'en' => '/en',
    ], name: 'homepage', priority: 1000)]
    #[Route(path: [
        'fr' => '/',
        'en' => '/en',
    ], name: 'cms_homepage', priority: 999)]
    public function index(Request $request): Response
    {
        $page = $this->pageRepository->findOneSystemByRouteName('homepage');
        if (null === $page) {
            return $this->render('homepage.html.twig', [
                'pageBuilderMode' => false,
            ]);
        }

        $pageSections = $this->pageSectionRepository->findActiveForPageCode($page->getCode());
        $pageDocumentHtml = $this->builderDocumentRenderer->renderForLocale($page, $request->getLocale());

        if ('' === $pageDocumentHtml && [] === $pageSections) {
            return $this->render('homepage.html.twig', [
                'pageBuilderMode' => false,
            ]);
        }

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