<?php

namespace App\Controller\Dashboard;

use App\Entity\Prestaire;
use App\Form\PrestaireType;
use App\Logger\AppLogger;
use App\Repository\PrestaireRepository;
use Doctrine\ORM\EntityManagerInterface;
use Knp\Component\Pager\PaginatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Routing\Attribute\Route;

use App\Service\Mailer\Mailer;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

#[Route('/crm/prestataire')]
class PrestaireController extends AbstractController
{
    public function __construct(
        private readonly EntityManagerInterface $em,
        private readonly AppLogger $appLogger,
        private readonly Mailer $mailer,
        private readonly UrlGeneratorInterface $urlGenerator
    ) {
    }

    #[Route('', name: 'app_crm_prestataire', options: ['sitemap' => false], methods: ['GET'])]
    public function index(PrestaireRepository $repository, PaginatorInterface $paginator, Request $request): Response
    {
        $this->appLogger->record('VIEW', 'Consultation de la liste des Prestataires');

        $query = $repository->createQueryBuilder('p')
            ->orderBy('p.name', 'ASC')
            ->getQuery();

        return $this->render('dashboard/prestaire.twig', [
            'prestataires' => $paginator->paginate($query, $request->query->getInt('page', 1), 10),
        ]);
    }

    #[Route('/add', name: 'app_crm_prestataire_add', options: ['sitemap' => false], methods: ['GET', 'POST'])]
    public function add(Request $request, UserPasswordHasherInterface $passwordHasher): Response
    {
        $prestataire = new Prestaire();
        $form = $this->createForm(PrestaireType::class, $prestataire);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            // Génération mot de passe aléatoire temporaire
            $plainPassword = bin2hex(random_bytes(10));
            $prestataire->setPassword($passwordHasher->hashPassword($prestataire, $plainPassword));

            // Rôles par défaut
            $prestataire->setRoles(['ROLE_PRESTAIRE']);

            $this->em->persist($prestataire);
            $this->em->flush();

            // Envoi de l'email de bienvenue
            $this->mailer->send(
                $prestataire->getEmail(),
                "{$prestataire->getSurname()} {$prestataire->getName()}",
                "Bienvenue sur l'interface de prestataire Ludikevent",
                "mails/prestataire/create.twig",
                [
                    'prestataire' => $prestataire,
                    'password' => $plainPassword,
                    'login_url' => 'https://prestataire.ludikevent.fr/etl'
                ]
            );

            $this->appLogger->record('CREATE', sprintf(
                "Création du Prestataire : %s %s (%s)",
                $prestataire->getSurname(), $prestataire->getName(), $prestataire->getEmail()
            ));

            $this->addFlash('success', "Le prestataire {$prestataire->getName()} a été créé avec succès et ses identifiants ont été envoyés par email.");

            return $this->redirectToRoute('app_crm_prestataire');
        }

        return $this->render('dashboard/prestaire/add.twig', [
            'form' => $form->createView()
        ]);
    }

    #[Route('/{id}', name: 'app_crm_prestataire_view', options: ['sitemap' => false], methods: ['GET', 'POST'])]
    public function view(Prestaire $prestataire, Request $request): Response
    {
        $form = $this->createForm(PrestaireType::class, $prestataire);
        $form->handleRequest($request);

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

            $this->appLogger->record('UPDATE', sprintf(
                "Mise à jour du Prestataire : %s %s",
                $prestataire->getSurname(), $prestataire->getName()
            ));

            $this->addFlash('success', "Informations mises à jour.");
            return $this->redirectToRoute('app_crm_prestataire_view', ['id' => $prestataire->getId()]);
        }

        $this->appLogger->record('VIEW', "Consultation fiche Prestataire : {$prestataire->getName()}");

        return $this->render('dashboard/prestaire/view.twig', [
            'prestataire' => $prestataire,
            'form' => $form->createView()
        ]);
    }

    #[Route('/delete/{id}', name: 'app_crm_prestataire_delete', options: ['sitemap' => false], methods: ['GET'])]
    public function delete(Prestaire $prestataire, Request $request): Response
    {
        if ($this->isCsrfTokenValid('delete' . $prestataire->getId(), $request->query->get('_token'))) {
            $name = $prestataire->getSurname() . ' ' . $prestataire->getName();

            $this->em->remove($prestataire);
            $this->em->flush();

            $this->appLogger->record('DELETE', "Suppression Prestataire : $name");
            $this->addFlash('success', "Le prestataire $name a été supprimé.");
        } else {
            $this->addFlash('error', "Token de sécurité invalide.");
        }

        return $this->redirectToRoute('app_crm_prestataire');
    }
}
