<?php
require_once __DIR__ . '/../config/database.php';

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

$error = '';

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

    $stmt = $conn->prepare(
        'SELECT u.*, r.nombre AS rol_nombre
         FROM usuarios u
         LEFT JOIN roles r ON r.id = u.rol_id
         WHERE (u.usuario = ? OR u.email = ?) AND u.activo = 1
         LIMIT 1'
    );
    $stmt->bind_param('ss', $usuario, $usuario);
    $stmt->execute();
    $resultado = $stmt->get_result();
    $user = $resultado->fetch_assoc();
    $stmt->close();

    if ($user && password_verify($password, $user['password_hash'])) {
        session_regenerate_id(true);
        $_SESSION['user_id'] = $user['id'];
        $_SESSION['user_name'] = $user['nombre'];
        $_SESSION['rol_nombre'] = $user['rol_nombre'];
        $_SESSION['rol_id'] = $user['rol_id'];
        registrar_auditoria($conn, 'LOGIN', 'usuarios', $user['id'], 'Ingreso al sistema');
        header('Location: /HM/dashboard.php');
        exit;
    }

    $error = 'Usuario o contraseña incorrectos.';
}

include __DIR__ . '/../includes/header.php';
?>
<div class="login-page">
  <div class="login-card">
    <img class="login-logo" src="/HM/assets/img/logo_hm.png" alt="HM Servicios Informáticos">
    <h4 class="text-center mb-1">HM Servicios Informáticos</h4>
    <p class="text-center text-muted mb-4">Sistema de Recursos Humanos</p>
    <?php if ($error): ?>
      <div class="alert alert-danger"><?= e($error) ?></div>
    <?php endif; ?>
    <form method="post" autocomplete="on">
      <div class="mb-3">
        <label class="form-label" for="usuario">Usuario o correo electrónico</label>
        <input class="form-control" id="usuario" name="usuario" required autofocus autocomplete="username">
      </div>
      <div class="mb-3">
        <label class="form-label" for="password">Contraseña</label>
        <input class="form-control" id="password" type="password" name="password" required autocomplete="current-password">
      </div>
      <button class="btn btn-hm w-100" type="submit">Ingresar</button>
    </form>
    <div class="text-center text-muted mt-3 small">Usuario inicial: admin / admin</div>
  </div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
