<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/helpers.php';

if (session_status() !== PHP_SESSION_ACTIVE) {
    session_start();
}
csrf_check();
$error = null;

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

  if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $error = "Correo inválido.";
  } elseif (strlen($pass) < 6) {
    $error = "Contraseña inválida.";
  } else {
    if (login($email, $pass)) {
      session_regenerate_id(true);

      // Aseguramos que el rol esté guardado con la clave 'role'
      $_SESSION['role'] = $_SESSION['user_role'] ?? null;

      $role = $_SESSION['role'];
      if ($role === 'superadmin') {
          header('Location: ../superadmin/dashboard.php');
      } elseif ($role === 'admin') {
          header('Location: ../admin/dashboard.php');
      } elseif ($role === 'client') {
          header('Location: ../client/dashboard.php');
      } else {
          session_destroy();
          header('Location: login.php?error=rol');
      }
      exit;
    } else {
      $error = "Credenciales incorrectas. Por favor, intente de nuevo.";
    }
  }
}
?>
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Iniciar sesión</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<style>
  body {
    background: url('../assets/fd.jpg') no-repeat center center fixed;
    background-size: cover;
  }
</style>
</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-md-5">
      <div class="card shadow-lg border-0">
        <div class="card-body p-4">
          <h3 class="mb-3 text-center">Bienvenido</h3>
          <?php if (!empty($error)): ?>
            <div class="alert alert-danger py-2"><?= e($error); ?></div>
          <?php endif; ?>
          <form method="post" autocomplete="off">
            <input type="hidden" name="csrf" value="<?= e(csrf_token()); ?>">
            <div class="mb-3">
              <label class="form-label">Correo</label>
              <input type="email" name="email" class="form-control" required>
            </div>
            <div class="mb-3">
              <label class="form-label">Contraseña</label>
              <input type="password" name="password" class="form-control" required minlength="6">
            </div>
            <button class="btn btn-primary w-100">Ingresar</button>
          </form>
        </div>
      </div>
      <p class="text-center text-muted small mt-3">© <?= date('Y'); ?> MiPortal</p>
    </div>
  </div>
</div>
</body>
</html>
