<?php

namespace App\Controller;

use App\Entity\CollectionFractal;
use App\Entity\CarteFractal;
use App\Entity\MembreFractal;
use App\Form\CollectionFractalType;
use Symfony\Bridge\Doctrine\Attribute\MapEntity;
use App\Repository\CollectionFractalRepository;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;

#[Route('/collection')]
#[IsGranted('IS_AUTHENTICATED_FULLY')]
class CollectionFractalController extends AbstractController
{
    #[IsGranted('ROLE_USER')]
    #[Route('/', name: 'app_collection_fractal_index', methods: ['GET'])]
    public function index(CollectionFractalRepository $collectionFractalRepository): Response
    {   
        $privateCollectionsFractal = array();
        if ($this->isGranted('ROLE_ADMIN')) {
            $privateCollectionsFractal = $collectionFractalRepository->findAll();
        }
        else {$user = $this->getUser();
            if($user) {
                    $membre = $user->getMembreFractal();
            $privateCollectionsFractal = $collectionFractalRepository->findBy(
                    [
                          'ispublic' => false,
                          'membrefractal' => $membre
                    ]);
            }}

        return $this->render('collection_fractal/index.html.twig', [
            'collection_fractales' => $collectionFractalRepository->findBy(['ispublic'=>true]),
            'priv_collections_fractal' => $privateCollectionsFractal,
            'user' => $this->getUser(),
        ]);
    }

    #[IsGranted('ROLE_USER')]
    #[Route('/new/{id}', name: 'app_collection_fractal_new', methods: ['GET', 'POST'])]
    public function new(Request $request, CollectionFractalRepository $collectionRepository, EntityManagerInterface $entityManager, MembreFractal $membre): Response
    {
        $collectionFractal = new CollectionFractal();
        $collectionFractal->setMembrefractal($membre);
        $form = $this->createForm(CollectionFractalType::class, $collectionFractal);
        $form->handleRequest($request);

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

            $this->addFlash('message', 'bien ajouté');

            return $this->redirectToRoute('app_collection_fractal_index', [], Response::HTTP_SEE_OTHER);
        }

        return $this->render('collection_fractal/new.html.twig', [
            'collection_fractal' => $collectionFractal,
            'form' => $form,
        ]);
    }
    #[IsGranted('ROLE_USER')]
    #[Route('/{id}', name: 'app_collection_fractal_show', requirements: ['id' => '\d+'], methods: ['GET'])]
    public function showAction(CollectionFractal $collection): Response
    {
        $hasAccess = false;
        if($this->isGranted('ROLE_ADMIN') || $collection->isIspublic()) {
                $hasAccess = true;
        }
        else {
                $user = $this->getUser();
                if( $user ) {
                        $member = $user->getMembreFractal();
                        if ( $member &&  ($member == $collection->getMembrefractal()) ) {
                                $hasAccess = true;
                        }
                }
        }
        if(! $hasAccess) {
                throw $this->createAccessDeniedException("You cannot access the requested resource!");
        }
        return $this->render('collection_fractal/show.html.twig', [
                'collection_fractal' => $collection,
        ]);
    }
    #[IsGranted('ROLE_USER')]
    #[Route('/{collection_id}/carte/{carte_id}', methods: ['GET'], name: 'app_collection_carte_show')]
    public function carteShow(
        #[MapEntity(id: 'collection_id')]
        CollectionFractal $collection,
        #[MapEntity(id: 'carte_id')]
        CarteFractal $carte
    ): Response
    {   
        if(! $collection->getCartesFractal()->contains($carte)) {
            throw $this->createNotFoundException("Couldn't find such a carte in this collection!");
    }

    $hasAccess = false;
    if($this->isGranted('ROLE_ADMIN') || $collection->isIspublic()) {
            $hasAccess = true;
    }
    else {
            $user = $this->getUser();
              if( $user ) {
                      $member = $user->getMembreFractal();
                      if ( $member &&  ($member == $collection->getMembreFractal()) ) {
                              $hasAccess = true;
                      }
              }
    }
    if(! $hasAccess) {
            throw $this->createAccessDeniedException("You cannot access the requested ressource!");
    }

    return $this->render('collection_fractal/carte_show.html.twig', [
            'carte_fractal' => $carte,
            'collection_fractal' => $collection
      ]);

    }
    #[IsGranted('ROLE_USER')]
    #[Route('/{id}/edit', name: 'app_collection_fractal_edit', methods: ['GET', 'POST'])]
    public function edit(Request $request, CollectionFractal $collectionFractal, EntityManagerInterface $entityManager): Response
    {   
        $hasAccess = $this->isGranted('ROLE_ADMIN') ||
            ($this->getUser()==$collectionFractal->getMembrefractal()->getUser());
        if(! $hasAccess) {
            throw $this->createAccessDeniedException("Vous ne pouvez pas accéder à une collection qui n'est pas la vôtre.");
        }
        $form = $this->createForm(CollectionFractalType::class, $collectionFractal);
        $form->handleRequest($request);

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

            return $this->redirectToRoute('app_collection_fractal_index', [], Response::HTTP_SEE_OTHER);
        }

        return $this->render('collection_fractal/edit.html.twig', [
            'collection_fractal' => $collectionFractal,
            'form' => $form,
        ]);
    }
    #[IsGranted('ROLE_ADMIN')]
    #[Route('/{id}', name: 'app_collection_fractal_delete', methods: ['POST'])]
    public function delete(Request $request, CollectionFractal $collectionFractal, EntityManagerInterface $entityManager): Response
    {   
        $hasAccess = $this->isGranted('ROLE_ADMIN') ||
            ($this->getUser()==$collectionFractal->getMembrefractal()->getUser());
        if(! $hasAccess) {
            throw $this->createAccessDeniedException("Vous ne pouvez pas accéder à une collection qui n'est pas la vôtre.");
        }
        if ($this->isCsrfTokenValid('delete'.$collectionFractal->getId(), $request->request->get('_token'))) {
            $entityManager->remove($collectionFractal);
            $entityManager->flush();
        }

        return $this->redirectToRoute('app_collection_fractal_index', [], Response::HTTP_SEE_OTHER);
    }
}
