<?php

namespace App\Controller;

use App\Entity\Account;
use App\Logger\AppLogger;
use Doctrine\ORM\EntityManagerInterface;
use Scheb\TwoFactorBundle\Security\TwoFactor\Provider\Google\GoogleAuthenticatorInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Endroid\QrCode\Builder\Builder;
use Endroid\QrCode\Encoding\Encoding;
use Endroid\QrCode\ErrorCorrectionLevel;
use Endroid\QrCode\Label\LabelAlignment;
use Endroid\QrCode\RoundBlockSizeMode;
use Endroid\QrCode\Writer\PngWriter;

class TwoController extends AbstractController
{
    #[Route(path: '/2fa/configure/{id}/{token}', name: 'app_2fa_setup_confirm', options: ['sitemap' => false], methods: ['GET', 'POST'])]
    public function index(
        ?Account $account,
        string $token,
        GoogleAuthenticatorInterface $googleAuthenticator,
        EntityManagerInterface $em,
        Request $request,
        AppLogger $appLogger
    ): Response {

        if (!$account || $account->getConfirmationToken() !== $token) {
            return $this->render('security/error_2fa.twig', ['message' => 'Lien invalide.']);
        }

        // Génération du secret si nécessaire
        if (!$account->getGoogleAuthenticatorSecret()) {
            $account->setGoogleAuthenticatorSecret($googleAuthenticator->generateSecret());
            $em->flush();
        }

        // Logique de validation
        if ($request->isMethod('POST')) {
            $checkCode = $request->request->get('_check_code');
            if ($googleAuthenticator->checkCode($account, $checkCode)) {
                $account->setConfirmationTokenName(null);
                $em->flush();
                $appLogger->record('AUTH', "2FA activée pour " . $account->getEmail());
                return $this->render('security/success_2fa.twig');
            }
            $this->addFlash('error', 'Code invalide.');
        }

// --- GÉNÉRATION DU QR CODE VIA ENDROID ---
        $qrContent = $googleAuthenticator->getQRContent($account);

// Chemin vers ton logo (ajuste le chemin si nécessaire)
        $logoPath = $this->getParameter('kernel.project_dir') . '/public/provider/images/logo.png';

        $builder = new Builder(
            writer: new PngWriter(),
            writerOptions: [],
            validateResult: false,
            data: $qrContent,
            encoding: new Encoding('UTF-8'),
            errorCorrectionLevel: ErrorCorrectionLevel::High,
            size: 250,
            margin: 10,
            roundBlockSizeMode: RoundBlockSizeMode::Margin,
            // Logo (Optionnel : vérifie si le fichier existe avant)
            labelAlignment: LabelAlignment::Center,
            // Label sous le QR Code
            logoPath: file_exists($logoPath) ? $logoPath : null,
            logoResizeToWidth: 50, // NotoSans est souvent inclus par défaut
            logoPunchoutBackground: true
        );

        $result = $builder->build();

        return $this->render('security/setup_2fa.twig', [
            'account' => $account,
            'qrCodeUrl' => $result->getDataUri() // Génère le Base64 pour le <img>
        ]);
    }
}
