<?php
session_start();
require_once __DIR__ . '/db.php';

if (!empty($_SESSION['admin_id'])) {
  header('Location: dashboard.php');
  exit;
}

$err = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
  $email = trim($_POST['email'] ?? '');
  $password = $_POST['password'] ?? '';

  $stmt = $conn->prepare(
    "SELECT id, email, nombre, password_hash
     FROM admin_users
     WHERE email = ?
     LIMIT 1"
  );
  $stmt->bind_param("s", $email);
  $stmt->execute();
  $stmt->store_result();

  if ($stmt->num_rows === 1) {
    $stmt->bind_result($id, $email_db, $nombre, $password_hash);
    $stmt->fetch();

    $ok = false;
    $pareceHash = (strlen((string)$password_hash) >= 20 && substr((string)$password_hash,0,1) === '$');

    if ($pareceHash) {
      $ok = password_verify($password, $password_hash);
    } else {
      $ok = hash_equals((string)$password_hash, (string)$password);
      if ($ok) {
        $nuevoHash = password_hash($password, PASSWORD_DEFAULT);
        $up = $conn->prepare("UPDATE admin_users SET password_hash=? WHERE id=?");
        $up->bind_param("si", $nuevoHash, $id);
        $up->execute();
        $up->close();
      }
    }

    if ($ok) {
      $_SESSION['admin_id'] = (int)$id;
      $_SESSION['admin_email'] = $email_db;
      $_SESSION['admin_nombre'] = $nombre;
      header('Location: dashboard.php');
      exit;
    }
  }

  $stmt->close();
  $err = 'Credenciales inválidas';
}
?>
<!doctype html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <title>Login | Admin</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light d-flex align-items-center" style="min-height:100vh;">
  <div class="container">
    <div class="row justify-content-center">
      <div class="col-sm-10 col-md-6 col-lg-4">
        <div class="card shadow-sm">
          <div class="card-body p-4">
            <h1 class="h4 mb-3 text-center">Admin Promo Hub</h1>
            <?php if ($err): ?>
              <div class="alert alert-danger py-2"><?= htmlspecialchars($err) ?></div>
            <?php endif; ?>
            <form method="post" autocomplete="off">
              <div class="mb-3">
                <label class="form-label">Correo</label>
                <input type="email" name="email" class="form-control" required autofocus>
              </div>
              <div class="mb-3">
                <label class="form-label">Contraseña</label>
                <input type="password" name="password" class="form-control" required>
              </div>
              <button class="btn btn-primary w-100">Ingresar</button>
            </form>
          </div>
        </div>
        <p class="text-center mt-3 text-muted small">© <?= date('Y') ?> GLM</p>
      </div>
    </div>
  </div>
</body>
</html>
