<?php
require_once __DIR__ . '/../config/auth.php';
require_once __DIR__ . '/../config/conn.php';

// Si ya hay sesión: admin va al panel, empleado al sitio
if (av_is_logged()) {
    header('Location: ' . (av_is_admin() ? 'index.php' : '../index.php'));
    exit;
}

$error = '';

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

    if ($username !== '' && $password !== '') {
        try {
            if (av_login($username, $password)) {
                if (av_is_admin()) {
                    header('Location: index.php');
                } else {
                    // empleados no entran al panel
                    header('Location: ../index.php');
                }
                exit;
            }
        } catch (Exception $e) {
            $error = 'Error de conexión con la base de datos. Contacta al administrador.';
            error_log('Login av_usuarios error: ' . $e->getMessage());
        }
    }
    if (!$error) $error = 'Usuario o contraseña incorrectos.';
}
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Acceso · Panel de Avisos</title>
  <link rel="stylesheet" href="admin.css">
</head>
<body>
<div class="av-login-wrap">
  <div class="av-login-card">

    <div class="av-login-logo">
      <img src="../img/demoLogo_SinFondo.png" alt="DEMO"
           onerror="this.style.display='none'">
    </div>

    <div class="av-login-title">Panel de Avisos</div>
    <div class="av-login-sub">Servicios DEMO Seguridad Privada</div>

    <?php if ($error): ?>
      <div class="av-alert av-alert--danger"><?= h($error) ?></div>
    <?php endif; ?>

    <form method="post" autocomplete="off" novalidate>
      <div class="av-form-group">
        <label class="av-label" for="username">Usuario</label>
        <input class="av-input" type="text" id="username" name="username"
               value="<?= h($_POST['username'] ?? '') ?>"
               autofocus autocomplete="username" required>
      </div>
      <div class="av-form-group">
        <label class="av-label" for="password">Contraseña</label>
        <input class="av-input" type="password" id="password" name="password"
               autocomplete="current-password" required>
      </div>
      <button type="submit" class="av-btn av-btn--primary av-btn--lg" style="width:100%;justify-content:center">
        Ingresar al panel
      </button>
    </form>

    <p class="av-text-muted av-mt-2" style="text-align:center;font-size:.72rem">
      Acceso restringido — solo personal autorizado
    </p>
  </div>
</div>
</body>
</html>
