<?php
require_once 'vendor/autoload.php';
session_start();
require_once 'db.php';

use PragmaRX\Google2FA\Google2FA;

header('Content-Type: application/json');

try {
    // Init Google2FA
    $google2fa = new Google2FA();
    
    // Générer secret
    $secret = $google2fa->generateSecretKey();
    $_SESSION['temp_2fa_secret'] = $secret;
    
    // QR code URL
    $qrCodeUrl = $google2fa->getQRCodeUrl(
        'Imators',
        $_SESSION['username'],
        $secret
    );

    // Utiliser l'API Google Charts 
    $qrCode = 'https://chart.googleapis.com/chart?cht=qr&chs=300x300&chl=' . urlencode($qrCodeUrl);
    
    echo json_encode([
        'success' => true,
        'qrcode' => $qrCode,
        'secret' => $secret
    ]);

} catch(Exception $e) {
    error_log('2FA Error: ' . $e->getMessage());
    echo json_encode([
        'success' => false,
        'error' => $e->getMessage()
    ]);
}