<?php

namespace App\Controller;

use App\Entity\CarteFractal;
use App\Entity\ClasseurFractal;
use App\Form\CarteFractalType;
use App\Repository\CarteFractalRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
#[Route('/carte')]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
class CarteFractalController extends AbstractController
{
    #[Route('/',name: 'app_carte_fractal_index',methods: ['GET'])]
    public function index(CarteFractalRepository $carteRepository): Response
    {
        $cartesFractal=$carteRepository->findAll();
        $membre = $this->getUser()->getMembreFractal();
        if ($this->isGranted('ROLE_ADMIN')) {
            $cartesFractal = $carteRepository->findAll();
        }
        else {
            $cartesFractal = $carteRepository->findMemberCartesFractal($membre);
        }
        return $this->render('carte_fractal/index.html.twig',[
            'cartesfractal'=>$cartesFractal,
            'membre'=>$membre
            ]);
    }
    
    #[Route('/{id}',name: 'app_carte_fractal_show',methods: ['GET'])]
    public function showAction(CarteFractal $carte): Response
    {
        return $this->render('carte_fractal/show.html.twig',[
            'carte'=>$carte,
        ]);
    }
    #[Route('/new/{id}', name: 'app_carte_fractal_new', methods: ['GET', 'POST'])]
    public function new(Request $request, CarteFractalRepository $carteRepository, ClasseurFractal $classeur,EntityManagerInterface $entityManager): Response
    {
            $carte = new CarteFractal();
            $carte->setClasseurFractal($classeur);
            $form = $this->createForm(CarteFractalType::class, $carte);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager->persist($carte);
            $entityManager->flush();

            return $this->redirectToRoute('app_carte_fractal_index', [], Response::HTTP_SEE_OTHER);
        }
        return $this->render('carte_fractal/new.html.twig', [
            'carte_fractal' => $carte,
            'classeur' => $classeur,
            'membre_fractal'=>$classeur->getMembrefractal(),
            'form' => $form,
        ]);
    }
}