<?php
session_start();
require_once 'db.php';
require_once 'TwoFactorAuth.php';

if (!isset($_SESSION['pending_user_id'])) {
    header('Location: login.php');
    exit;
}

if (!isset($_SESSION['2fa_attempts'])) {
    $_SESSION['2fa_attempts'] = 0;
}

$error = '';
$success = '';

$db = new Database();
$twoFA = new TwoFactorAuth($db);

try {
    $stmt = $db->connect()->prepare("SELECT email, username, `profile-picture` FROM utilisateurs WHERE id = ?");
    $stmt->execute([$_SESSION['pending_user_id']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    $user = ['username' => 'User'];
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $code = preg_replace('/[^0-9]/', '', $_POST['code']);
    
    if (strlen($code) !== 6 && strlen($code) !== 8) {
        $error = "Code invalide";
    } else {
        $result = $twoFA->verifyCode($_SESSION['pending_user_id'], $code);
        
        if ($result['success']) {
            $_SESSION['user_id'] = $_SESSION['pending_user_id'];
            unset($_SESSION['pending_user_id'], $_SESSION['2fa_attempts']);
            header('Location: dashboard.php');
            exit;
        } else {
            $_SESSION['2fa_attempts']++;
            $error = $result['error'];
        }
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vérification 2FA</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600&display=swap" rel="stylesheet">
    <script src="https://cdn.tailwindcss.com"></script>
    <style>
        body {
            font-family: 'Poppins', sans-serif;
            background: linear-gradient(135deg, #000000, #0a0a0a, #141414);
        }
        .glass-effect {
            backdrop-filter: blur(16px);
            background: rgba(255, 255, 255, 0.02);
            border: 1px solid rgba(255, 255, 255, 0.05);
        }
    </style>
</head>
<body class="min-h-screen flex items-center justify-center p-4">
    <div class="w-full max-w-md">
        <div class="text-center mb-8">
            <img src="https://cdn.imators.com/logo.png" alt="Logo" class="h-12 mx-auto mb-4">
            <h1 class="text-xl text-white font-medium">Vérification en deux étapes</h1>
        </div>

        <div class="gradient-border">
            <div class="glass-effect rounded-xl p-6 sm:p-8">
                <div class="flex items-center justify-center mb-8">
                    <div class="text-center">
                        <img src="<?php echo htmlspecialchars($user['profile-picture'] ?? 'default-avatar.png'); ?>" 
                             alt="Profile" 
                             class="w-20 h-20 rounded-full mx-auto mb-4 border-2 border-white/10">
                        <h2 class="text-lg font-medium text-white">
                            <?php echo htmlspecialchars($user['username']); ?>
                        </h2>
                    </div>
                </div>

                <?php if ($error): ?>
                <div class="bg-red-500/10 border border-red-500/20 text-red-400 p-4 rounded-lg mb-6">
                    <?php echo htmlspecialchars($error); ?>
                </div>
                <?php endif; ?>

                <form method="POST" class="space-y-6">
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">
                            Code de vérification
                        </label>
                        <input type="text" 
                               name="code" 
                               maxlength="6"
                               class="w-full px-4 py-3 bg-black/30 border border-white/10 rounded-lg text-center text-2xl tracking-[0.5em] text-white"
                               placeholder="000000"
                               autocomplete="off">
                        <p class="mt-2 text-sm text-gray-400 text-center">
                            Entrez le code de votre application d'authentification
                        </p>
                    </div>

                    <button type="submit" 
                            class="w-full bg-white text-black py-3 px-6 rounded-lg font-medium hover:bg-gray-100 transition-all">
                        Vérifier
                    </button>

                    <div class="text-center">
                        <button type="button" 
                                onclick="toggleBackupCode()"
                                class="text-sm text-gray-400 hover:text-white transition-colors">
                            Utiliser un code de secours
                        </button>
                    </div>
                </form>
            </div>
        </div>

        <div class="mt-6 text-center">
            <a href="logout.php" class="text-sm text-gray-400 hover:text-white transition-colors">
                Annuler et se déconnecter
            </a>
        </div>
    </div>

    <script>
    function toggleBackupCode() {
        const input = document.querySelector('input[name="code"]');
        if (input.maxLength === 6) {
            input.maxLength = 8;
            input.placeholder = '12345678';
            input.previousElementSibling.textContent = 'Code de secours';
            input.nextElementSibling.textContent = 'Entrez un code de secours à 8 caractères';
        } else {
            input.maxLength = 6;
            input.placeholder = '000000';
            input.previousElementSibling.textContent = 'Code de vérification';
            input.nextElementSibling.textContent = 'Entrez le code de votre application d\'authentification';
        }
        input.value = '';
        input.focus();
    }

    document.querySelector('input[name="code"]').addEventListener('input', function(e) {
        this.value = this.value.replace(/[^0-9]/g, '');
    });
    </script>
</body>
</html>