<?php

declare(strict_types=1);

namespace App\Controller;

use App\Entity\Client;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;
use Twig\Environment;

class MenuBrowserController extends AbstractController
{
    public function __construct(
        protected readonly EntityManagerInterface $entityManager,
        private Environment $twig,
    )
    {
    }

    #[Route('/menu-browser')]
    public function index(Request $request): Response
    {
        $host = $request->getClientIp();

        $partitions = [];

        $client = $this->entityManager->getRepository(Client::class)->findOneBy(['ip' => $host]);

        if ($client) {
            $partitions = $client->getPartitions();
        }

        $menuName = $client->getMenu()->getPublicUrl();

        return $this->render('browser/' . $menuName . '.html.twig', [
            'ip' => $host,
            'mac' => $client ? $client->getMac() : null,
            'partitions' => $partitions,
        ]);
    }

    #[Route('/menu/{templateName}', name: 'render_menu_template')]
    public function renderMenu(string $templateName, Request $request): Response
    {
        $templatePath = 'browser/' . $templateName . '.html.twig';

        if (!$this->twig->getLoader()->exists($templatePath)) {
            throw $this->createNotFoundException(sprintf('La plantilla "%s" no existe.', $templateName));
        }

        return $this->render($templatePath, [
            'ip' => 'invitado',
            'partitions' => [],
        ]);
    }
}
