<?php

namespace App\Controller;

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\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\String\Slugger\AsciiSlugger;
use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
use App\Form\UserProfileType;
use App\Form\GamemasterProfileType;
use App\Form\GameProfileType;
use App\Repository\GameRepository;
use App\Entity\User;
use App\Entity\Gamemaster;
use App\Entity\Game;
use App\Service\PictureService;
use App\Entity\Participation;
use App\Repository\ParticipationRepository;


final class ProfileController extends AbstractController
{
    #[Route('/profile', name: 'app_profile', methods: ['GET', 'POST'])]
    public function index(Request $request, UserPasswordHasherInterface $userPasswordHasher, EntityManagerInterface $manager): Response
    {
        $user = $this->getUser();
        $form = $this->createForm(UserProfileType::class, $user);

        // Mise à jour de l'utilisateur à partir du formulaire
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
            // Si un nouveau mot de passe a été proposé
            if ($form->get('newPassword')->getData()) {
                // Encoder le mot de passe
                $newPassword = $form->get('newPassword')->getData();
                $user->setPassword($userPasswordHasher->hashPassword($user, $newPassword));
            }
            if ($user->getLinkToGamemaster()) {
                $user->getLinkToGamemaster()->setPhone($user->getPhone());
                $user->getLinkToGamemaster()->setFirstName($user->getFirstName());
                $user->getLinkToGamemaster()->setLastName($user->getLastName());
            }
            // Mettre à jour l'utilisateur
            $user->setLastUpdate();
            $manager->persist($user);
            $manager->flush();
            $this->addFlash('success', 'Compte modifié avec succès.');
            return $this->redirectToRoute('app_profile');
        }

        return $this->render('profile/index.html.twig', [
            'form' => $form,
            'user' => $user,
        ]);
    }

    #[Route('/profile/gamemaster', name: 'app_profile_gamemaster', methods: ['GET', 'POST'])]
    public function gamemasterProfile(Request $request, UserPasswordHasherInterface $userPasswordHasher, EntityManagerInterface $manager, PictureService $pictureService): Response
    {
        $user = $this->getUser();
        $gamemaster = $user->getLinkToGamemaster();
        if (!$gamemaster) {
            $this->addFlash('error', 'Vous n\'avez pas de profil de meneur(euse) de jeu.');
            return $this->redirectToRoute('app_profile');
        }
        $form = $this->createForm(GamemasterProfileType::class, $gamemaster);

        // Mise à jour de l'utilisateur à partir du formulaire
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {
                       if (!$form->get('preferedName')->getData()) {
                $gamemaster->setPreferedName($form->get('firstName')->getData() ." ". $form->get('lastName')->getData());
            }

            $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($gamemaster->getPreferedName()));
                $gamemaster->setSlug($slug);
            }

            
            // Traiter l'image proposée
            $tmpPicture = $form->get('picture')->getData();
            if ($tmpPicture) {
                $picture = $pictureService->square($tmpPicture, '/gamemasters/', $slug);
                $gamemaster->setPicture($picture);
            }

            // Mettre à jour l'utilisateur
            $manager->persist($gamemaster);
            $manager->flush();
            $this->addFlash('success', 'Profil MJ modifié avec succès.');
            return $this->redirectToRoute('app_profile_gamemaster');
        }

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

    /*
     * Supprimer l'image du MJ
     */
    #[Route('/profile/gamemaster/{id}/del-pic', name: 'app_profile_gamemaster_del_pic', requirements: ['id' => Requirement::UUID_V7], methods: ['GET'])]
    public function deletePicture(?Gamemaster $gamemaster, EntityManagerInterface $manager, ParameterBagInterface $params): Response
    {
        $user = $this->getUser();
        $gamemaster = $user->getLinkToGamemaster();
        if (!$gamemaster) {
            $this->addFlash('error', 'Vous n\'avez pas de profil de meneur(euse) de jeu.');
            return $this->redirectToRoute('app_profile');
        }
        // Effacer toutes images associée
        if ($gamemaster->getPicture()) {
            $fullPath = $params->get('upload_images_directory') . '/gamemasters/' . $gamemaster->getPicture();
            unlink($fullPath);
        }
        $gamemaster->setPicture(null);
        $manager->flush();
        
        $this->addFlash('success', 'Illustration supprimée avec succès.');
        return $this->redirectToRoute('app_profile_gamemaster');
    }

    #[Route('/profile/gamelist', name: 'app_profile_gamelist')]
    public function gameList(GameRepository $repository): Response
    {
        $user = $this->getUser();
        $gamemaster = $user->getLinkToGamemaster();
        if (!$gamemaster) {
            $this->addFlash('error', 'Vous n\'avez pas de profil de meneur(euse) de jeu.');
            return $this->redirectToRoute('app_profile');
        }
        $games = $repository->findAllValid();
        return $this->render('profile/gamelist.html.twig', [
            'games' => $games,
        ]);
    }

    #[Route('/profile/gameadd', name: 'app_profile_gameadd', methods: ['GET', 'POST'])]
    public function gameAdd(Request $request, EntityManagerInterface $manager, PictureService $pictureService): Response
    {
        $user = $this->getUser();
        $gamemaster = $user->getLinkToGamemaster();
        if (!$gamemaster) {
            $this->addFlash('error', 'Vous n\'avez pas de profil de meneur(euse) de jeu.');
            return $this->redirectToRoute('app_profile');
        }
        // 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(GameProfileType::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. Il sera prochainement validé par l\'équipe d\'administration.');
            return $this->redirectToRoute('app_profile_gamelist');
        }

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



    #[Route('/profile/participations', name: 'app_profile_participations')]
    public function participations(ParticipationRepository $repository): Response
    {
        $user = $this->getUser();
        if (!$user) {
            $this->addFlash('danger', 'Aucun utilisateur connecté');
        }
        // Retrouver le mail de l'utilisateur
        $email = $user->getEmail();
        $participations = $repository->findAllByEmail($email);
        
        return $this->render('profile/participations.html.twig', [
            'participations' => $participations,
            'user' => $user
        ]);
    }


    #[Route('/profile/participations/gamemastering', name: 'app_profile_participations_gming')]
    public function participationsGM(): Response
    {
        $user = $this->getUser();
        if (!$user) {
            $this->addFlash('danger', 'Aucun utilisateur connecté');
            $this->redirectToRoute('app_main');
        }
        $gamemaster = $user->getLinkToGamemaster();
        if (!$gamemaster) {
            $this->addFlash('danger', 'Profil non MJ !');
            $this->redirectToRoute('app_profile_participations');
        }

        $participations = $gamemaster->getParties();
        
        return $this->render('profile/gamemastering.html.twig', [
            'participations' => $participations,
            'user' => $user
        ]);
    }

    #[Route('/profile/participations/requests', name: 'app_prodile_participations_requests')]
    public function participationRequests(): Response
    {
        $user = $this->getUser();
        if (!$user) {
            $this->addFlash('danger', 'Aucun utilisateur connecté');
            $this->redirectToRoute('app_main');
        }
        $partyRequests = $user->getPartyRequests();
        
        return $this->render('profile/partyrequests.html.twig', [
            'user' => $user,
            'partyRequests' => $partyRequests
        ]);
    }
}
