<?php
// Charger la configuration et démarrer la session
require_once '../../src/includes/config.php';

$error_message = '';

// Traitement du formulaire
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = trim($_POST['email'] ?? '');
    $mot_de_passe = $_POST['mot_de_passe'] ?? '';

    if (empty($email) || empty($mot_de_passe)) {
        $error_message = "Veuillez remplir tous les champs.";
    } else {
        try {
            $stmt = $pdo->prepare("SELECT * FROM gestionnaires WHERE email = ? AND actif = 1");
            $stmt->execute([$email]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);

            if ($user && password_verify($mot_de_passe, $user['mot_de_passe'])) {
                $_SESSION['gestionnaire_id'] = $user['id'];
                $_SESSION['nom_complet'] = $user['nom_complet'];
                $_SESSION['role'] = $user['role'];
                $_SESSION['service_id'] = $user['service_id'];

                header('Location: dashboard.php');
                exit;
            } else {
                $error_message = "Email ou mot de passe incorrect.";
            }
        } catch (Exception $e) {
            $error_message = "Erreur serveur : " . $e->getMessage();
        }
    }

    $_SESSION['flash_error'] = $error_message;
    header('Location: login.php');
    exit;
}

$error_message = $_SESSION['flash_error'] ?? '';
unset($_SESSION['flash_error']);

$base = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/');
?>

<!DOCTYPE html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Administration — Connexion | CI-ÉNERGIES</title>

  <!-- Bootstrap -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <!-- Icônes -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.css" rel="stylesheet">
  <!-- Google Fonts -->
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;600;700&display=swap" rel="stylesheet">
  <!-- Feuille de style personnalisée -->
  <link href="<?= $base ?>/../../admin/assets/css/auth.css?v=<?= time() ?>" rel="stylesheet">
</head>
<body>

  <div class="auth-wrapper container">
    <div class="row g-4 align-items-center justify-content-center">

      <!-- Partie gauche -->
      <div class="col-lg-6">
        <div class="brand-card p-5 text-center">
          <img src="<?= $base ?>/../../admin/assets/img/logo-ci-energies.png" alt="CI-ÉNERGIES" class="logo mb-4">
          <h2 class="fw-bold mb-2">Espace Administrateur</h2>
          <p class="small-muted mb-4">Accédez à votre espace sécurisé de gestion.</p>
          <a href="../index.php" class="btn btn-light btn-sm px-3 py-2">
            <i class="bi bi-arrow-left-circle me-1"></i> Retour à l'accueil
          </a>
        </div>
      </div>

      <!-- Partie droite -->
      <div class="col-lg-6">
        <div class="form-card p-5">
          <div class="text-center mb-4">
            <h3 class="fw-semibold text-gradient">Connexion</h3>
            <p class="small-muted mb-0">Veuillez entrer vos identifiants</p>
          </div>

          <?php if (!empty($error_message)): ?>
            <div class="alert alert-danger d-flex align-items-center" role="alert">
              <i class="bi bi-exclamation-triangle-fill me-2"></i>
              <div><?= htmlspecialchars($error_message) ?></div>
            </div>
          <?php endif; ?>

          <form method="post" novalidate>
            <div class="mb-3">
              <label for="loginField" class="form-label">Adresse e-mail</label>
              <div class="input-group">
                <span class="input-group-text"><i class="bi bi-envelope"></i></span>
                <input type="email" class="form-control" id="loginField" name="email" placeholder="ex. j.doe@cienergies.ci" required>
              </div>
            </div>

            <div class="mb-3">
              <div class="d-flex justify-content-between align-items-center">
                <label for="passwordField" class="form-label mb-0">Mot de passe</label>
                <button type="button" class="btn btn-link p-0 small" id="togglePwd">
                  <i class="bi bi-eye" id="togglePwdIcon"></i> Afficher
                </button>
              </div>
              <div class="input-group">
                <span class="input-group-text"><i class="bi bi-lock"></i></span>
                <input type="password" class="form-control" id="passwordField" name="mot_de_passe" placeholder="Votre mot de passe" required>
              </div>
            </div>

            <div class="d-flex justify-content-between align-items-center mb-4">
              <div class="form-check">
                <input class="form-check-input" type="checkbox" id="rememberMe">
                <label class="form-check-label" for="rememberMe">Se souvenir de moi</label>
              </div>
              <a href="#" class="text-decoration-none small">Mot de passe oublié ?</a>
            </div>

            <div class="d-grid">
              <button type="submit" class="btn text-white fw-semibold"
                style="background: linear-gradient(90deg, var(--ci-orange), var(--ci-green));">
                <i class="bi bi-box-arrow-in-right me-1"></i> Se connecter
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>

    <div class="text-center mt-3 footer-note">
      © <?= date('Y') ?> CI-ÉNERGIES — Tous droits réservés.
    </div>
  </div>

  <!-- JS Bootstrap -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    // Toggle mot de passe
    const pwdField = document.getElementById('passwordField');
    const toggle = document.getElementById('togglePwd');
    const icon = document.getElementById('togglePwdIcon');

    if (toggle && pwdField) {
      toggle.addEventListener('click', function() {
        const isText = pwdField.type === 'text';
        pwdField.type = isText ? 'password' : 'text';
        icon.classList.toggle('bi-eye');
        icon.classList.toggle('bi-eye-slash');
        this.innerHTML = isText 
          ? '<i class="bi bi-eye"></i> Afficher'
          : '<i class="bi bi-eye-slash"></i> Masquer';
      });
    }
  </script>
</body>
</html>
