<?php
require_once __DIR__ . '/../includes/config.php';
if (isLoggedIn()) { redirect(SITE_URL . '/admin/index'); }
$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCSRF($_POST['csrf_token'] ?? '')) {
        $error = "Session expirée. Veuillez réessayer.";
    } else {
        $username = sanitize($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';

        if ($username && $password) {
            if (!checkLoginAttempts($username)) {
                $error = "Compte temporairement verrouillé suite à trop de tentatives. Veuillez réanalyser dans 15 minutes.";
            } else {
                $db = getDB();
                $stmt = $db->prepare("SELECT id, username, password_hash, role FROM admins WHERE username = ?");
                $stmt->execute([$username]);
                $admin = $stmt->fetch();

                if ($admin && password_verify($password, $admin['password_hash'])) {
                    resetLoginAttempts($username);
                    $_SESSION['admin_id'] = $admin['id'];
                    $_SESSION['admin_username'] = $admin['username'];
                    $_SESSION['admin_role'] = $admin['role'] ?? 'super_admin';
                    redirect(SITE_URL . '/admin/index');
                } else {
                    incrementLoginAttempts($username);
                    $error = "Identifiants incorrects.";
                }
            }
        } else {
            $error = "Veuillez remplir tous les champs.";
        }
    }
}
?>
<!DOCTYPE html>
<html lang="fr" class="h-full bg-slate-950">
<head>
  <meta charset="UTF-8"/>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Connexion Administration | AJOUAMAI IMMO-BUSINESS</title>
  
  <link rel="icon" type="image/png" href="<?= SITE_URL ?>/assets/img/logo.png"/>
  
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Sansation:ital,wght@0,300;0,400;0,700;1,300;1,400&family=McLaren&display=swap" rel="stylesheet">
  <script src="https://cdn.tailwindcss.com"></script>
  <script>
    tailwind.config = {
      theme: {
        extend: {
          fontFamily: {
            sans: ['McLaren', 'cursive', 'sans-serif'],
            serif: ['Sansation', 'sans-serif'],
          },
          colors: {
            brand: {
              500: '#D4C7A3',
              600: '#B8A882',
              700: '#8E7E5A',
            }
          }
        }
      }
    }
  </script>
</head>
<body class="h-full bg-gradient-to-br from-slate-950 via-slate-900 to-indigo-950 flex items-center justify-center p-6 font-sans">

  <div class="w-full max-w-md">
    <div class="bg-white/95 backdrop-blur-xl p-8 sm:p-10 rounded-2xl shadow-2xl border border-white/20">
      
      <!-- Brand Logo Header -->
      <div class="flex flex-col items-center text-center mb-8">
        <div class="w-16 h-16 rounded-2xl bg-gradient-to-tr from-brand-600 to-brand-500 flex items-center justify-center p-3 shadow-lg shadow-brand-600/30 mb-4">
          <img src="<?= SITE_URL ?>/assets/img/logo.png" class="h-full w-auto object-contain filter brightness-0 invert" alt="AJOUAMAI IMMO-BUSINESS Logo"/>
        </div>
        <h1 class="font-serif text-2xl font-bold text-slate-900">Espace Administration</h1>
        <p class="text-xs text-slate-500 font-sans mt-1">Plateforme de Gestion immobilière AJOUAMAI IMMO-BUSINESS</p>
      </div>

      <?php if ($error): ?>
        <div class="bg-rose-50 border border-rose-200 p-4 rounded-xl mb-6 flex items-center gap-3">
          <span class="text-rose-500 font-bold">⚠️</span>
          <p class="text-xs text-rose-700 font-sans font-semibold"><?= htmlspecialchars($error) ?></p>
        </div>
      <?php endif; ?>

      <form method="POST" class="space-y-5">
        <input type="hidden" name="csrf_token" value="<?= htmlspecialchars(generateCSRF()) ?>"/>
        
        <div>
          <label class="block text-xs font-bold uppercase tracking-wider text-slate-700 mb-2 font-sans">Nom d'utilisateur</label>
          <input type="text" name="username" required class="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm font-sans focus:outline-none focus:ring-2 focus:ring-brand-600 focus:bg-white transition-all" placeholder="admin"/>
        </div>

        <div>
          <label class="block text-xs font-bold uppercase tracking-wider text-slate-700 mb-2 font-sans">Mot de passe</label>
          <input type="password" name="password" required class="w-full px-4 py-3 bg-slate-50 border border-slate-200 rounded-xl text-sm font-sans focus:outline-none focus:ring-2 focus:ring-brand-600 focus:bg-white transition-all" placeholder="••••••••"/>
        </div>

        <button type="submit" class="w-full bg-gradient-to-r from-brand-600 to-brand-700 hover:from-brand-700 hover:to-brand-800 text-white text-xs font-bold tracking-widest uppercase py-4 rounded-xl shadow-lg shadow-brand-600/30 transition-all transform hover:-translate-y-0.5">
          Se connecter à la console
        </button>
      </form>

      <div class="mt-8 text-center pt-6 border-t border-slate-100">
        <a href="<?= SITE_URL ?>/" class="text-xs font-semibold text-slate-500 hover:text-slate-900 transition-colors font-sans tracking-wider uppercase flex items-center justify-center gap-2">
          <span>←</span> Retour au site public
        </a>
      </div>

    </div>
  </div>

</body>
</html>
