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

// Vérification de la session en attente
if (!isset($_SESSION['pending_user_id'])) {
    header('Location: login.php');
    exit;
}

// Vérification du nombre maximal de tentatives
if (!isset($_SESSION['2fa_attempts'])) {
    $_SESSION['2fa_attempts'] = 0;
}

if ($_SESSION['2fa_attempts'] >= 5) {
    if (!isset($_SESSION['2fa_timeout']) || time() >= $_SESSION['2fa_timeout']) {
        // Réinitialisation après 15 minutes
        $_SESSION['2fa_attempts'] = 0;
        unset($_SESSION['2fa_timeout']);
    } else {
        $remainingTime = ceil(($_SESSION['2fa_timeout'] - time()) / 60);
        $error = "Trop de tentatives. Veuillez réessayer dans {$remainingTime} minutes.";
    }
}

$db = new Database();
$conn = $db->connect();
$twoFA = new TwoFactorAuth($db);
$error = '';
$success = '';

// Récupération des informations de l'utilisateur pour l'affichage
try {
    $stmt = $conn->prepare("SELECT username, email, `profile-picture` FROM utilisateurs WHERE id = ?");
    $stmt->execute([$_SESSION['pending_user_id']]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
    error_log("Error fetching user data: " . $e->getMessage());
    $user = ['username' => 'User', 'profile-picture' => 'default-avatar.png'];
}

// Traitement de la soumission du code
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_SESSION['2fa_timeout']) && time() < $_SESSION['2fa_timeout']) {
        $error = "Compte temporairement bloqué. Veuillez réessayer plus tard.";
    } else {
        $code = preg_replace('/[^0-9]/', '', $_POST['code']); // Nettoyage du code

        if (strlen($code) !== 6 && strlen($code) !== 8) {
            $error = "Le code doit contenir 6 chiffres ou 8 caractères pour un code de secours.";
        } else {
            if ($twoFA->verifyCode($_SESSION['pending_user_id'], $code)) {
                // Mise à jour des informations de connexion
                try {
                    $stmt = $conn->prepare("
                        UPDATE `connection-watchguard` 
                        SET `2fa_verified` = TRUE,
                            `2fa_verified_at` = NOW() 
                        WHERE user_id = ? 
                        ORDER BY `date-of-connect` DESC 
                        LIMIT 1
                    ");
                    $stmt->execute([$_SESSION['pending_user_id']]);
                    
                    // Configuration de la session
                    $_SESSION['user_id'] = $_SESSION['pending_user_id'];
                    $_SESSION['2fa_verified'] = true;
                    unset($_SESSION['pending_user_id']);
                    unset($_SESSION['2fa_attempts']);
                    unset($_SESSION['2fa_timeout']);
                    
                    // Redirection avec animation
                    $success = "Vérification réussie. Redirection...";
                    header("refresh:1;url=profile.php");
                } catch(PDOException $e) {
                    error_log("Error updating 2FA verification: " . $e->getMessage());
                    $error = "Une erreur est survenue. Veuillez réessayer.";
                }
            } else {
                $_SESSION['2fa_attempts']++;
                
                if ($_SESSION['2fa_attempts'] >= 5) {
                    $_SESSION['2fa_timeout'] = time() + (15 * 60); // 15 minutes
                    $error = "Trop de tentatives. Compte temporairement bloqué pour 15 minutes.";
                } else {
                    $remainingAttempts = 5 - $_SESSION['2fa_attempts'];
                    $error = "Code invalide. Il vous reste {$remainingAttempts} tentative(s).";
                }
            }
        }
    }
}
?>
<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vérification A2F - Imators</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);
            background-attachment: fixed;
        }
        
        .glass-effect {
            backdrop-filter: blur(16px);
            background: rgba(255, 255, 255, 0.02);
            border: 1px solid rgba(255, 255, 255, 0.05);
        }
        
        .gradient-border {
            position: relative;
            border-radius: 1.25rem;
            background: linear-gradient(145deg, rgba(26, 26, 26, 0.8), rgba(45, 45, 45, 0.4));
            padding: 1px;
        }
        
        .gradient-border::before {
            content: '';
            position: absolute;
            inset: -1px;
            border-radius: 1.25rem;
            padding: 1px;
            background: linear-gradient(145deg, rgba(255, 255, 255, 0.12), rgba(255, 255, 255, 0.03));
            -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
            mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0);
            -webkit-mask-composite: xor;
            mask-composite: exclude;
        }

        .code-input {
            letter-spacing: 0.5em;
            text-align: center;
        }

        @keyframes pulse {
            0%, 100% { transform: scale(1); }
            50% { transform: scale(1.05); }
        }

        .success-animation {
            animation: pulse 1s infinite;
        }

        .hover-scale {
            transition: all 0.3s ease;
        }

        .hover-scale:hover {
            transform: scale(1.02);
        }

        input:focus {
            outline: none;
            border-color: rgba(255, 255, 255, 0.2);
            box-shadow: 0 0 0 2px 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">
        <!-- Logo -->
        <div class="text-center mb-8">
            <img src="https://cdn.imators.com/logo.png" alt="Imators" 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">
                <!-- Profil utilisateur -->
                <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>
                        <p class="text-sm text-gray-400">
                            <?php echo htmlspecialchars($user['email']); ?>
                        </p>
                    </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; ?>

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

                <?php if (!$success): ?>
                <form method="POST" class="space-y-6" id="verifyForm">
                    <div>
                        <label class="block text-sm font-medium text-gray-300 mb-2">
                            Code de vérification
                        </label>
                        <input type="text" 
                               name="code" 
                               id="codeInput"
                               required 
                               maxlength="8"
                               pattern="[0-9]*"
                               inputmode="numeric"
                               autocomplete="one-time-code"
                               class="w-full px-4 py-3 rounded-lg bg-black/50 border border-white/10 focus:border-white/30 text-center text-xl tracking-widest text-white"
                               placeholder="000000">
                        <p class="mt-2 text-sm text-gray-400">
                            Entrez le code à 6 chiffres 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 hover-scale">
                        Vérifier
                    </button>

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

        <?php if (!$success): ?>
        <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>
        <?php endif; ?>
    </div>

    <script>
        // Focus automatique sur l'input
        document.addEventListener('DOMContentLoaded', function() {
            const codeInput = document.getElementById('codeInput');
            if (codeInput) {
                codeInput.focus();
            }
        });

        // Formatage automatique du code
        document.getElementById('codeInput')?.addEventListener('input', function(e) {
            let value = e.target.value.replace(/[^0-9]/g, '');
            e.target.value = value;
        });

        // Animation du formulaire
        document.getElementById('verifyForm')?.addEventListener('submit', function(e) {
            const submitButton = this.querySelector('button[type="submit"]');
            submitButton.disabled = true;
            submitButton.innerHTML = `
                <svg class="animate-spin -ml-1 mr-3 h-5 w-5 inline-block" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                    <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
                Vérification...
            `;
        });

        function showBackupCodeForm() {
            const codeInput = document.getElementById('codeInput');
            const label = codeInput.previousElementSibling;
            const helpText = codeInput.nextElementSibling;
            
            label.textContent = 'Code de secours';
            codeInput.placeholder = '12345678';
            codeInput.maxLength = 8;
            helpText.textContent = 'Entrez un code de secours à 8 caractères';
            
            codeInput.focus();
        }
    </script>
</body>
</html>