<?php

namespace App\Controller;

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

use App\Security\Voter\PartyAccessVoter;
use App\Entity\Party;
use App\Entity\Participation;

final class CheckinController extends AbstractController
{
    #[Route('/checkin/participant/{id}', name: 'app_check', requirements: ['id' => Requirement::UUID_V7], methods: ['POST'])]
    public function participant(?Participation $participation, Request $request, EntityManagerInterface $manager): JsonResponse
    {
        // On récupère la participation
        if (!$participation) {
            return $this->json(['error' => 'Participation not found'], 404);
        }

        // ON check la partie
        $party = $participation->getParty();
        if (!$party) {
            return $this->json(['error' => 'Party not found'], 404);
        }

        // Voteur sur la partie : ADMIN, GESTIONNAIRE ou STAFF/si MJ de la partie
        $this->denyAccessUnlessGranted(PartyAccessVoter::ACCESS_PARTY, $party);
        // TODO: retourner une erreur 503

        $returnCode = "ERROR";

        if ($participation->isCheckin()) {
            $participation->setCheckin(false);
            $manager->persist($participation);
            $manager->flush();
            $returnCode = "UNCHECKED";
        } else {
            $participation->setCheckin(true);
            $manager->persist($participation);
            $manager->flush();
            $returnCode = "CHECKED";
        }
    
        return $this->json(["status" => $returnCode]);
    }

    // Gérer l'affichage du contenu de la modale pour les checkins
    #[Route('/checkin/party/{id}', name: 'app_checkin_party', requirements: ['id' => Requirement::UUID_V7], methods: ['GET'])]
    public function party(?Party $party): Response
    {
        // Est-ce que c'est bien une partie ?
        if (!$party) {
            $this->addFlash('danger', 'Aucune partie avec cet identifiant.');
            return $this->redirectToRoute('app_main');
        }

        // Voteur sur la partie : ADMIN, GESTIONNAIRE ou STAFF/si MJ de la partie
        $this->denyAccessUnlessGranted(PartyAccessVoter::ACCESS_PARTY, $party);
        
        // Donc, ça marche
        return $this->render('checkin/_modal.checkin.html.twig', [
            'party' => $party,
            'participations' => $party->getParticipations()
        ]);

    }


}
