<?php

namespace App\Controller\Admin;

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 Symfony\Component\String\Slugger\AsciiSlugger;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;

use App\Entity\Event;
use App\Form\EventType;
use App\Repository\EventRepository;
use App\Service\PictureService;

final class EventController extends AbstractController
{
    /*
     * Lister tous les événements
     */
    #[Route('/admin/event', name: 'app_admin_event')]
    public function index(EventRepository $repository): Response
    {
        $events = $repository->findAll();

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

    /*
     * Supprimer un événement
     */
    #[Route('/admin/event/{id}/delete', name: 'app_admin_event_delete', requirements: ['id' => Requirement::UUID_V7], methods: ['GET'])]
    public function delete(?Event $event, EntityManagerInterface $manager, ParameterBagInterface $params): Response
    {
        // Effacer toutes images associée
        if ($event->getPicture()) {
            $fullPath = $params->get('upload_images_directory') . '/events/' . $event->getPicture();
            unlink($fullPath);
        }
        
        $manager->remove($event);
        $manager->flush();
        
        $this->addFlash('success', 'Événement supprimé avec succès.');
        return $this->redirectToRoute('app_admin_event');
    }

    /*
     * Supprimer l'image d'un événement
     */
    #[Route('/admin/event/{id}/del-pic', name: 'app_admin_event_del_pic', requirements: ['id' => Requirement::UUID_V7], methods: ['GET'])]
    public function deletePicture(?Event $event, EntityManagerInterface $manager, ParameterBagInterface $params): Response
    {
        // Effacer toutes images associée
        if ($event->getPicture()) {
            $fullPath = $params->get('upload_images_directory') . '/events/' . $event->getPicture();
            unlink($fullPath);
        }
        $event->setPicture(null);
        $manager->flush();
        
        $this->addFlash('success', 'Illustration supprimée avec succès.');
        return $this->redirectToRoute('app_admin_event_edit', ['id' => $event->getId()]);
    }

    /* 
     * Modifier un jeu
     */
    #[Route('/admin/event/{id}/edit', name: 'app_admin_event_edit', requirements: ['id' => Requirement::UUID_V7], methods: ['GET', 'POST'])]
    public function edit(?Event $event, Request $request, EntityManagerInterface $manager, PictureService $pictureService): Response
    {
        $form = $this->createForm(EventType::class, $event);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            $slug = $form->get('slug')->getData();
            // Aucun slug n'a été proposé par l'utilisateur
            if (!$slug) {
                $slugger = new AsciiSlugger('fr_FR');
                $slug = $slugger->slug(strtolower($event->getName()));
                $event->setSlug($slug);
            }
            
            // Traiter l'image proposée
            $tmpPicture = $form->get('picture')->getData();
            if ($tmpPicture) {
                $picture = $pictureService->banner($tmpPicture, '/events/', $slug);
                $event->setPicture($picture);
            }
            $manager->persist($event);
            $manager->flush();

            $this->addFlash('success', 'Événement modifié avec succès.');
            return $this->redirectToRoute('app_admin_event');
        }

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

    /* 
     * Ajouter un jeu
     */
    #[Route('/admin/event/add', name: 'app_admin_event_add', methods: ['GET', 'POST'])]
    public function add(Request $request, EntityManagerInterface $manager, PictureService $pictureService): Response
    {
        // Initialisation d'un nouveau jeu
        $event = new Event();

        $form = $this->createForm(EventType::class, $event);

        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            
            $slug = $form->get('slug')->getData();
            // Aucun slug n'a été proposé par l'utilisateur
            if (!$slug) {
                $slugger = new AsciiSlugger('fr_FR');
                $slug = $slugger->slug(strtolower($event->getName()));
                $event->setSlug($slug);
            }
            
            // Traiter l'image proposée
            $tmpPicture = $form->get('picture')->getData();
            if ($tmpPicture) {
                $picture = $pictureService->banner($tmpPicture, '/events/', $slug);
                $event->setPicture($picture);
            }

            $manager->persist($event);
            $manager->flush();

            $this->addFlash('success', 'Événement ajouté à la base de données avec succès.');
            return $this->redirectToRoute('app_admin_event');
        }

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

    #[Route('/admin/event/{id}/configure', name: 'app_admin_event_config', requirements: ['id' => Requirement::UUID_V7], methods: ['GET', 'POST'])]
    public function configure(?Event $event, Request $request, EntityManagerInterface $manager, PictureService $pictureService): Response
    {
        return $this->render('admin/event/config/index.html.twig', [
            'event' => $event
        ]);
    }

    #[Route('/admin/event/{id}/publish', name: 'app_admin_event_config_publish', requirements: ['id' => Requirement::UUID_V7], methods: ['GET'])]
    public function publish(?Event $event, EntityManagerInterface $manager): Response
    {
        if ($event->isPublished()) {
            $this->addFlash('danger', 'Événement déjà publié !');
        } else {
            // Respecte les conditions de publications. Dispose de slots, au moins un MJ et un jeu...
            if (count($event->getSlots()) > 0) {
                $event->setPublished(true);
                $manager->persist($event);
                $manager->flush();
                $this->addFlash('success', 'Événement publié.');
            } else {
                $this->addFlash('danger', 'Un événement doit disposer d\'au moins un slot, d\'un(e) meneur(euse) de jeu et d\'un jeu.');
            }
        }
        return $this->redirectToRoute('app_admin_event_config', [
            'id' => $event->getId()
        ]);
    }

    #[Route('/admin/event/{id}/unpublish', name: 'app_admin_event_config_unpublish', requirements: ['id' => Requirement::UUID_V7], methods: ['GET'])]
    public function unpublish(?Event $event, EntityManagerInterface $manager): Response
    {
        if ($event->isPublished()) {
            $event->setPublished(false);
            $manager->persist($event);
            $manager->flush();
            $this->addFlash('success', 'Événement dépublié !');
        } else {
            $this->addFlash('danger', 'Cet événement n\'est pas publié.');
        }
        return $this->redirectToRoute('app_admin_event_config', [
            'id' => $event->getId()
        ]);
    }


}
