<?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\Game;
use App\Form\GameType;
use App\Repository\GameRepository;
use App\Service\PictureService;

final class GameController extends AbstractController
{
    /*
     * Lister tous les jeux
     */
    #[Route('/admin/game', name: 'app_admin_game', methods: ['GET'])]
    public function index(GameRepository $repository): Response
    {
        $games = $repository->findAll();

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

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

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

    /*
     * Valider le jeu
     */
    #[Route('/admin/game/{id}/valid', name: 'app_admin_game_valid', requirements: ['id' => Requirement::UUID_V7], methods: ['GET'])]
    public function valid(?Game $game, EntityManagerInterface $manager): Response
    {
        $game->setIsValidByAdmin(true);
        $game->setValidDatetime(new \Datetime('now'));
        $manager->persist($game);
        $manager->flush();
        $this->addFlash('success', 'Le jeu est validé.');
        return $this->redirectToRoute('app_admin_game');
    }

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

        $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($game->getName()));
                $game->setSlug($slug);
            }
            
            // Traiter l'image proposée
            $tmpPicture = $form->get('picture')->getData();
            if ($tmpPicture) {
                $picture = $pictureService->banner($tmpPicture, '/games/', $slug);
                $game->setPicture($picture);
            }
            $manager->persist($game);
            $manager->flush();

            $this->addFlash('success', 'Jeu modifié avec succès.');
            return $this->redirectToRoute('app_admin_game');
        }

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

    /* 
     * Ajouter un jeu
     */
    #[Route('/admin/game/add', name: 'app_admin_game_add', methods: ['GET', 'POST'])]
    public function add(Request $request, EntityManagerInterface $manager, PictureService $pictureService): Response
    {
        // Initialisation d'un nouveau jeu
        $game = new Game();
        // Initialisaiton des valeurs par défaut
        $game->setAddBy($this->getUser());
        $game->setAddDatetime(new \Datetime('now'));

        $form = $this->createForm(GameType::class, $game);

        $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($game->getName()));
                $game->setSlug($slug);
            }
            
            // Traiter l'image proposée
            $tmpPicture = $form->get('picture')->getData();
            if ($tmpPicture) {
                $picture = $pictureService->banner($tmpPicture, '/games/', $slug);
                $game->setPicture($picture);
            }

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

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

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