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

$error = '';
$aviso = '';

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

    $stmt = $conn->prepare("SELECT * FROM usuarios WHERE email = ?");
    $stmt->bind_param('s', $email);
    $stmt->execute();
    $result = $stmt->get_result();

    if ($result->num_rows === 1) {
        $user = $result->fetch_assoc();

        if ($user['estado'] === 'bloqueado') {
            $error = 'Tu cuenta está bloqueada. Contacta al administrador.';
        } elseif (password_verify($password, $user['password'])) {
            session_regenerate_id(true);
            $_SESSION['id_usuario']    = $user['id_usuario'];
            $_SESSION['rol']           = $user['rol'];
            $_SESSION['nombre']        = $user['nombre'];
            $_SESSION['ultimo_acceso'] = time();

            $destino = [
                'admin'       => 'admin_dashboard.php',
                'propietario' => 'propietario_dashboard.php',
                'conserje'    => 'conserje_dashboard.php',
            ][$user['rol']] ?? null;

            if ($destino) {
                header("Location: $destino");
                exit;
            }
            $error = 'Rol desconocido.';
        } else {
            $error = 'Contraseña incorrecta.';
        }
    } else {
        $error = 'Usuario no encontrado.';
    }
}

if (isset($_GET['mensaje'])) {
    $aviso = [
        'inactividad'   => 'Tu sesión se cerró por inactividad.',
        'no_autorizado' => 'Debes iniciar sesión para continuar.',
        'sesion_cerrada'=> 'Sesión cerrada correctamente.',
    ][$_GET['mensaje']] ?? '';
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Iniciar Sesión · <?= APP_NOMBRE ?></title>
<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🏖️</text></svg>">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700;800&display=swap" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css" rel="stylesheet">
<link href="assets/css/app.css" rel="stylesheet">
</head>
<body class="login-body">

<div class="login-card">
  <div class="login-logo"><i class="bi bi-buildings"></i></div>
  <h1 class="text-center fs-4 fw-bold mb-1"><?= APP_NOMBRE ?></h1>
  <p class="text-center text-secondary mb-4" style="font-size:14px"><?= CONDOMINIO_NOMBRE ?></p>

  <?php if ($aviso): ?>
    <div class="alert alert-warning py-2" style="font-size:14px"><i class="bi bi-info-circle me-1"></i><?= e($aviso) ?></div>
  <?php endif; ?>
  <?php if ($error): ?>
    <div class="alert alert-danger py-2" style="font-size:14px"><i class="bi bi-x-circle me-1"></i><?= e($error) ?></div>
  <?php endif; ?>

  <form method="POST" action="login.php">
    <div class="mb-3">
      <label class="form-label">Correo electrónico</label>
      <div class="input-group">
        <span class="input-group-text bg-white"><i class="bi bi-envelope"></i></span>
        <input type="email" class="form-control" name="email" placeholder="tu@correo.cl" required autofocus>
      </div>
    </div>
    <div class="mb-4">
      <label class="form-label">Contraseña</label>
      <div class="input-group">
        <span class="input-group-text bg-white"><i class="bi bi-lock"></i></span>
        <input type="password" class="form-control" name="password" id="password" placeholder="••••••••" required>
        <button class="btn btn-outline-secondary" type="button" id="verPass" tabindex="-1"><i class="bi bi-eye"></i></button>
      </div>
    </div>
    <button type="submit" class="btn btn-primary w-100 py-2">
      <i class="bi bi-box-arrow-in-right me-1"></i> Iniciar Sesión
    </button>
  </form>
</div>

<script>
document.getElementById('verPass').addEventListener('click', function () {
  const input = document.getElementById('password');
  const icono = this.querySelector('i');
  const esPass = input.type === 'password';
  input.type = esPass ? 'text' : 'password';
  icono.className = esPass ? 'bi bi-eye-slash' : 'bi bi-eye';
});
</script>
</body>
</html>
