<?php
// On démarre la session pour pouvoir stocker et vérifier les données de l'utilisateur
session_start();

// Si l'admin est déjà connecté, on l'envoie directement vers le tableau de bord
if (isset($_SESSION['admin_logged_in']) && $_SESSION['admin_logged_in'] === true) {
    header('Location: admin_dashboard.php');
    exit;
}

// Tableau pour stocker les messages d'erreur
$errors = [];

// Vérifie si le formulaire a été envoyé en POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // On récupère le nom d'utilisateur et le mot de passe en supprimant les espaces inutiles
    $user = trim($_POST['username'] ?? '');
    $pass = trim($_POST['password'] ?? '');

    // Vérifie si les champs sont remplis
    if ($user === '' || $pass === '') {
        $errors[] = 'Veuillez remplir tous les champs.';
    } else {
        // Connexion à la base de données avec PDO (plus sécurisé)
        try {
            $pdo = new PDO(
                "mysql:host=localhost;dbname=tostrlgj_mariage_db;charset=utf8mb4", // paramètres de connexion
                'tostrlgj_voldy', // utilisateur MySQL
                'Voldy25@Ilus',     // mot de passe MySQL
                [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION] // mode pour afficher les erreurs
            );
        } catch (Exception $e) {
            // Si la connexion échoue, on arrête tout et on affiche l'erreur
            die("Erreur DB : " . $e->getMessage());
        }

        // Prépare une requête SQL sécurisée pour éviter les injections
        $stmt = $pdo->prepare("SELECT * FROM users WHERE username = ?");
        $stmt->execute([$user]);
        $userRow = $stmt->fetch(PDO::FETCH_ASSOC);

        // Vérifie si l'utilisateur existe et si le mot de passe est correct
        if ($userRow && password_verify($pass, $userRow['password_hash'])) {
            
            // ✅ L'authentification est réussie → on enregistre des infos en session
            $_SESSION['admin_logged_in'] = true;           // Indique que l'admin est connecté
            $_SESSION['admin_id'] = $userRow['id'];        // ID de l'admin dans la base
            $_SESSION['admin_username'] = $user;           // Nom d'utilisateur

            // ✅ Protection supplémentaire : stocke l'IP et l'User Agent
            $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'] ?? ''; // navigateur utilisé
            $_SESSION['ip'] = $_SERVER['REMOTE_ADDR'] ?? '';             // adresse IP

            // Redirection vers le tableau de bord admin
            header('Location: admin_dashboard.php');
            exit;
        } else {
            // Si identifiants incorrects → on ajoute un message d'erreur
            $errors[] = 'Identifiants incorrects.';
        }
    }
}
?>

<!DOCTYPE html>
<html lang="fr">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Connexion Admin - Aaron & Princillia</title>
    <link href="https://fonts.googleapis.com/css2?family=Playfair+Display:wght@400;700;900&family=Montserrat:wght@300;400;500;600&display=swap" rel="stylesheet">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Montserrat', sans-serif;
            background: linear-gradient(135deg, #1a1a1a 0%, #2c2c2c 100%);
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
            color: #2c2c2c;
        }

        body::before {
            content: '';
            position: fixed;
            top: -200px;
            right: -200px;
            width: 600px;
            height: 600px;
            background: radial-gradient(circle, rgba(212, 165, 116, 0.15) 0%, transparent 70%);
            animation: float 8s ease-in-out infinite;
            z-index: -1;
        }

        body::after {
            content: '';
            position: fixed;
            bottom: -150px;
            left: -150px;
            width: 400px;
            height: 400px;
            background: radial-gradient(circle, rgba(212, 165, 116, 0.1) 0%, transparent 70%);
            animation: float 10s ease-in-out infinite reverse;
            z-index: -1;
        }

        @keyframes float {
            0%, 100% { transform: translateY(0px); }
            50% { transform: translateY(30px); }
        }

        .container-login {
            max-width: 450px;
            width: 90%;
        }

        .login-card {
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
            overflow: hidden;
            animation: slideDown 0.5s ease;
        }

        @keyframes slideDown {
            from {
                opacity: 0;
                transform: translateY(-50px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .login-header {
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            padding: 3rem 2rem;
            text-align: center;
            color: white;
        }

        .login-logo {
            font-family: 'Playfair Display', serif;
            font-size: 2.5rem;
            font-weight: 900;
            margin-bottom: 0.5rem;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
        }

        .login-subtitle {
            font-size: 0.95rem;
            opacity: 0.9;
            letter-spacing: 1px;
        }

        .login-body {
            padding: 3rem 2rem;
        }

        .error-message {
            background: #f8d7da;
            color: #721c24;
            border: 2px solid #f5c6cb;
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 2rem;
            display: flex;
            align-items: flex-start;
            gap: 1rem;
            animation: slideIn 0.3s ease;
        }

        .error-icon {
            font-size: 1.2rem;
            flex-shrink: 0;
            margin-top: 0.2rem;
        }

        .error-content {
            flex: 1;
        }

        .error-item {
            margin-bottom: 0.5rem;
        }

        .error-item:last-child {
            margin-bottom: 0;
        }

        @keyframes slideIn {
            from {
                opacity: 0;
                transform: translateX(-20px);
            }
            to {
                opacity: 1;
                transform: translateX(0);
            }
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-label {
            display: block;
            font-weight: 600;
            color: #2c2c2c;
            margin-bottom: 0.7rem;
            font-size: 0.95rem;
        }

        .form-input {
            width: 100%;
            padding: 0.875rem 1.2rem;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-family: 'Montserrat', sans-serif;
            font-size: 1rem;
            transition: all 0.3s ease;
            background: #f9f9f7;
        }

        .form-input:focus {
            outline: none;
            border-color: #d4a574;
            background: white;
            box-shadow: 0 0 0 3px rgba(212, 165, 116, 0.1);
        }

        .form-input::placeholder {
            color: #ccc;
        }

        .submit-button {
            width: 100%;
            padding: 1rem;
            background: linear-gradient(135deg, #d4a574 0%, #8b6f47 100%);
            color: white;
            border: none;
            border-radius: 8px;
            font-weight: 600;
            font-size: 1rem;
            cursor: pointer;
            transition: all 0.3s ease;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.5rem;
            font-family: 'Montserrat', sans-serif;
        }

        .submit-button:hover {
            transform: translateY(-3px);
            box-shadow: 0 10px 30px rgba(212, 165, 116, 0.3);
        }

        .submit-button:active {
            transform: translateY(-1px);
        }

        .divider {
            display: flex;
            align-items: center;
            gap: 1rem;
            margin: 2rem 0;
            color: #ccc;
        }

        .divider::before,
        .divider::after {
            content: '';
            flex: 1;
            height: 1px;
            background: #e0e0e0;
        }

        .divider-text {
            font-size: 0.85rem;
            color: #999;
        }

        .home-link {
            display: block;
            text-align: center;
            padding: 1rem;
            color: #d4a574;
            text-decoration: none;
            font-weight: 600;
            transition: all 0.3s ease;
            font-size: 0.95rem;
        }

        .home-link:hover {
            color: #8b6f47;
            transform: translateY(-2px);
        }

        .home-link i {
            margin-right: 0.5rem;
        }

        .login-footer {
            background: #f9f9f7;
            padding: 1rem 2rem;
            text-align: center;
            border-top: 1px solid #e0e0e0;
        }

        .password-toggle {
            position: absolute;
            right: 12px;
            top: 50%;
            transform: translateY(-50%);
            background: none;
            border: none;
            color: #d4a574;
            cursor: pointer;
            font-size: 1.1rem;
            transition: color 0.2s ease;
        }

        .password-toggle:hover {
            color: #8b6f47;
        }

        .input-wrapper {
            position: relative;
        }

        @media (max-width: 768px) {
            .login-header {
                padding: 2rem 1.5rem;
            }

            .login-body {
                padding: 2rem 1.5rem;
            }

            .login-logo {
                font-size: 2rem;
            }
        }
    </style>
</head>
<body>
    <div class="container-login">
        <div class="login-card">
            <div class="login-header">
                <div class="login-logo">
                    <i class="fas fa-heart"></i> Aaron & Princillia
                </div>
                <div class="login-subtitle">Espace Administrateur</div>
            </div>

            <div class="login-body">
                <?php if (!empty($errors)): ?>
                    <div class="error-message">
                        <div class="error-icon">
                            <i class="fas fa-exclamation-circle"></i>
                        </div>
                        <div class="error-content">
                            <?php foreach ($errors as $e): ?>
                                <div class="error-item"><?= htmlspecialchars($e) ?></div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                <?php endif; ?>

                <form method="POST" novalidate>
                    <div class="form-group">
                        <label for="username" class="form-label">
                            <i class="fas fa-user"></i> Nom d'utilisateur
                        </label>
                        <input 
                            type="text" 
                            name="username" 
                            id="username" 
                            class="form-input" 
                            placeholder="Entrez votre identifiant"
                            autocomplete="username"
                            required 
                        />
                    </div>

                    <div class="form-group">
                        <label for="password" class="form-label">
                            <i class="fas fa-lock"></i> Mot de passe
                        </label>
                        <div class="input-wrapper">
                            <input 
                                type="password" 
                                name="password" 
                                id="password" 
                                class="form-input" 
                                placeholder="Entrez votre mot de passe"
                                autocomplete="current-password"
                                required 
                            />
                            <button 
                                type="button" 
                                class="password-toggle" 
                                onclick="togglePassword()"
                                title="Afficher/Masquer"
                            >
                                <i class="fas fa-eye"></i>
                            </button>
                        </div>
                    </div>

                    <button type="submit" class="submit-button">
                        <i class="fas fa-sign-in-alt"></i> Se connecter
                    </button>
                </form>

                <div class="divider">
                    <span class="divider-text">ou</span>
                </div>

                <a href="../index.php" class="home-link">
                    <i class="fas fa-home"></i> Retour à l'accueil
                </a>
            </div>

            <div class="login-footer">
                <small style="color: #999;">
                    <i class="fas fa-lock-alt"></i> Connexion sécurisée
                </small>
            </div>
        </div>
    </div>

    <script>
        function togglePassword() {
            const passwordInput = document.getElementById('password');
            const toggleButton = document.querySelector('.password-toggle i');

            if (passwordInput.type === 'password') {
                passwordInput.type = 'text';
                toggleButton.classList.remove('fa-eye');
                toggleButton.classList.add('fa-eye-slash');
            } else {
                passwordInput.type = 'password';
                toggleButton.classList.remove('fa-eye-slash');
                toggleButton.classList.add('fa-eye');
            }
        }

        // Focus sur le premier champ
        document.getElementById('username').focus();
    </script>
</body>
</html>