<?php

declare(strict_types=1);

namespace App\Controller\School;

use App\Service\School\SchoolContext;
use App\Entity\AnneeScolaire;
use App\Entity\Ecole;
use App\Form\AnneeScolaireType;
use App\Repository\AnneeScolaireRepository;
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 Symfony\Component\Security\Http\Attribute\IsGranted;

#[Route('/school/annees', name: 'school_annee_')]
#[IsGranted('ROLE_ECOLE_ADMIN')]
final class AnneeScolaireController extends AbstractController
{
    public function __construct(private readonly SchoolContext $schoolContext)
    {
    }

    #[Route('', name: 'index', methods: ['GET'])]
    public function index(AnneeScolaireRepository $repository): Response
    {
        $ecole = $this->schoolContext->getEcole();
        return $this->render('school/annee_scolaire/index.html.twig', ['ecole' => $ecole, 'annees' => $repository->findForEcole($ecole)]);
    }

    #[Route('/new', name: 'new', methods: ['GET', 'POST'])]
    public function new(Request $request, EntityManagerInterface $em, AnneeScolaireRepository $repository): Response
    {
        $ecole = $this->schoolContext->getEcole();
        $annee = (new AnneeScolaire())->setEcole($ecole)->setLibelle('Année '.date('Y'));
        $form = $this->createForm(AnneeScolaireType::class, $annee, ['ecole' => $ecole]);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) { $this->syncCurrentYear($annee, $repository, $ecole); $em->persist($annee); $em->flush(); $this->addFlash('success', 'L’année scolaire a été créée.'); return $this->redirectToRoute('school_annee_index'); }
        return $this->render('school/annee_scolaire/form.html.twig', ['ecole' => $ecole, 'form' => $form, 'title' => 'Nouvelle année scolaire']);
    }

    #[Route('/{id}/edit', name: 'edit', requirements: ['id' => '\\d+'], methods: ['GET', 'POST'])]
    public function edit(Request $request, AnneeScolaire $annee, EntityManagerInterface $em, AnneeScolaireRepository $repository): Response
    {
        $ecole = $this->schoolContext->getEcole(); $this->schoolContext->assertSameSchool($annee->getEcole());
        $form = $this->createForm(AnneeScolaireType::class, $annee, ['ecole' => $ecole]);
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) { $this->syncCurrentYear($annee, $repository, $ecole); $em->flush(); $this->addFlash('success', 'L’année scolaire a été mise à jour.'); return $this->redirectToRoute('school_annee_index'); }
        return $this->render('school/annee_scolaire/form.html.twig', ['ecole' => $ecole, 'form' => $form, 'title' => 'Modifier l’année scolaire']);
    }

    #[Route('/{id}/delete', name: 'delete', requirements: ['id' => '\\d+'], methods: ['POST'])]
    public function delete(Request $request, AnneeScolaire $annee, EntityManagerInterface $em): Response
    {
        $this->schoolContext->assertSameSchool($annee->getEcole());
        if ($this->isCsrfTokenValid('delete_annee_'.$annee->getId(), (string) $request->request->get('_token'))) { $em->remove($annee); $em->flush(); $this->addFlash('success', 'L’année scolaire a été supprimée.'); }
        return $this->redirectToRoute('school_annee_index');
    }

    private function syncCurrentYear(AnneeScolaire $annee, AnneeScolaireRepository $repository, Ecole $ecole): void
    {
        if (!$annee->isActive() || $annee->getStatut() !== 'ACTIVE') {
            return;
        }

        foreach ($repository->findForEcole($ecole) as $other) {
            if ($other !== $annee) {
                $other->setActive(false);
            }
        }
    }
}
