<?php

namespace App\Controller\Admin\EventConfig;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Requirement\Requirement;
use Symfony\Component\Routing\Attribute\Route;
use Doctrine\ORM\EntityManagerInterface;

use App\Entity\Event;
use App\Entity\Space;
use App\Form\SpaceType;
use App\Repository\SpaceRepository;

final class SpaceController extends AbstractController
{
    #[Route('/admin/event/{id}/configure/space', name: 'app_admin_event_config_space', requirements: ['id' => Requirement::UUID_V7], methods: ['GET', 'POST'])]
    public function index(?Event $event, Request $request, EntityManagerInterface $manager, SpaceRepository $repository): Response
    {
        $space = new Space();
        $space->setEvent($event);
        
        $form = $this->createForm(SpaceType::class, $space);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            
            $manager->persist($space);
            $manager->flush();

            return $this->redirectToRoute('app_admin_event_config_space', ['id' => $event->getId()]);
        }

        return $this->render('admin/event/config/space.html.twig', [
            'event' => $event,
            'form' => $form,
        ]);
    }

    #[Route('/admin/space/{id}/delete', name: 'app_admin_space_delete', requirements: ['id' => '\d+'], methods: ['GET'])]
    public function delete(?Space $space, EntityManagerInterface $manager): Response
    {
        $event = $space->getEvent();
        if ($space->isLocked()) {
            $this->addFlash('danger', 'Cet espace est utilisé dans les slots ! Supprimez les slots avant de supprimer l\'espace !');
        } else {
            $manager->remove($space);
            $manager->flush();
        }

        return $this->redirectToRoute('app_admin_event_config_space', ['id' => $event->getId()]);
    }
}
