<?php

namespace App\Controller\Dashboard;

use App\Form\AccountPasswordType;
use App\Logger\AppLogger;
use App\Service\Mailer\Mailer;
use Doctrine\ORM\EntityManagerInterface;
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 Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Csrf\TokenGenerator\TokenGeneratorInterface;

// ... imports identiques

class ProfilsController extends AbstractController
{
    #[Route(path: '/crm/profils', name: 'app_crm_profils', methods: ['GET', 'POST'])]
    public function crmProfils(
        Request $request,
        EntityManagerInterface $em,
        UserPasswordHasherInterface $passwordHasher,
        Mailer $mailer,
        AppLogger $appLogger,
        TokenGeneratorInterface $tokenGenerator
    ): Response {
        /** @var \App\Entity\User $user */
        $user = $this->getUser();

        // --- PROTECTION : REDIRECTION SI ROLE_ROOT ---
        if ($this->isGranted('ROLE_ROOT')) {
            return $this->redirectToRoute('app_crm');
        }

        $action = $request->query->get('act');

        // --- LOGIQUE 2FA : DÉSACTIVATION ---
        if ($action === 'disable2fa') {
            if ($user->getGoogleAuthenticatorSecret()) {
                $user->setGoogleAuthenticatorSecret(null);
                $em->flush();

                $mailer->send(
                    $user->getEmail(),
                    $user->getFirstName() . " " . $user->getName(),
                    "[Alerte Sécurité] Désactivation de votre double authentification",
                    "mails/account/2fa-disable.twig",
                    ['account' => $user, 'who' => $user]
                );

                $appLogger->record('2FA_DISABLED', sprintf(
                    "L'utilisateur %s %s a désactivé son propre 2FA (ID: %d)",
                    $user->getFirstName(), $user->getName(), $user->getId()
                ));

                $this->addFlash('warning', "Votre protection 2FA a été désactivée.");
                return $this->redirectToRoute('app_crm_profils');
            }
        }

        // --- LOGIQUE 2FA : ENVOI DU LIEN D'ACTIVATION ---
        if ($action === 'sendLink2faenable') {
            $token = $tokenGenerator->generateToken();
            $user->setConfirmationToken($token);

            $setupUrl = $this->generateUrl('app_2fa_setup_confirm', [
                'id' => $user->getId(),
                'token' => $token
            ], UrlGeneratorInterface::ABSOLUTE_URL);

            $em->flush();

            $mailer->send(
                $user->getEmail(),
                $user->getFirstName() . " " . $user->getName(),
                "[Sécurité] Configuration de votre double authentification (2FA)",
                "mails/account/2fa-invite.twig",
                [
                    'account'    => $user,
                    'setup_url'  => $setupUrl,
                    'who'        => $user,
                    'expires_at' => (new \DateTime('+1 hour'))->format('H:i')
                ]
            );

            $appLogger->record('2FA_INVITE', sprintf(
                "Invitation 2FA auto-générée par %s %s",
                $user->getFirstName(), $user->getName()
            ));

            $this->addFlash('success', "Un lien de configuration vous a été envoyé par mail.");
            return $this->redirectToRoute('app_crm_profils');
        }

        // --- LOGIQUE MOT DE PASSE ---
        $formPassword = $this->createForm(AccountPasswordType::class, $user);
        $formPassword->handleRequest($request);

        if ($formPassword->isSubmitted() && $formPassword->isValid()) {
            $plainPassword = $formPassword->get('plainPassword')->getData();
            $user->setPassword($passwordHasher->hashPassword($user, $plainPassword));

            $em->flush();

            $appLogger->record('PASSWORD_UPDATE', sprintf(
                "L'utilisateur %s %s a mis à jour son mot de passe",
                $user->getFirstName(), $user->getName()
            ));

            $this->addFlash('success', 'Mot de passe mis à jour avec succès.');
            return $this->redirectToRoute('app_crm_profils');
        }

        // --- LOG DE CONSULTATION ---
        $appLogger->record('VIEW', 'Consultation de son profil');

        return $this->render('dashboard/profil.twig', [
            'user' => $user,
            'formPassword' => $formPassword->createView(),
        ]);
    }
}
