<?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\Period;
use App\Form\PeriodType;
use App\Repository\PeriodRepository;

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

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

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

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

    #[Route('/admin/period/{id}/delete', name: 'app_admin_period_delete', requirements: ['id' => '\d+'], methods: ['GET'])]
    public function delete(?Period $period, EntityManagerInterface $manager): Response
    {
        $event = $period->getEvent();
        if ($period->isLocked()) {
            $this->addFlash('danger', 'Cette période est utilisée dans les slots ! Supprimez les slots avant de supprimer la période !');
        } else {
            $manager->remove($period);
            $manager->flush();
        }
        
        return $this->redirectToRoute('app_admin_event_config_period', ['id' => $event->getId()]);
    }
}
