<?php
/**
 * GET /api/lab/get_lab_users.php
 * Devuelve todos los usuarios del sistema con información de rol.
 * Solo admins.
 */
require_once __DIR__ . '/_helpers.php';
requireAdmin();

$db = Database::getInstance();

$users = $db->fetchAll("
    SELECT
        u.id,
        u.username,
        u.full_name,
        u.email,
        u.is_active,
        u.role,
        u.role_id,
        u.enfermera_id,
        u.last_login,
        u.created_at,
        (u.firma_svg IS NOT NULL) AS tiene_firma,
        r.name  AS role_name,
        r.color AS role_color,
        r.slug  AS role_slug,
        e.nombre_completo AS enfermera_nombre
    FROM admin_users u
    LEFT JOIN roles r ON r.id = u.role_id
    LEFT JOIN lab_enfermeras e ON e.id = u.enfermera_id
    ORDER BY u.id ASC
");

foreach ($users as &$u) {
    $u['is_active']   = (bool)$u['is_active'];
    $u['tiene_firma'] = (bool)$u['tiene_firma'];
    $u['role_name']   = $u['role_name']  ?? ucfirst($u['role'] ?? 'admin');
    $u['role_color']  = $u['role_color'] ?? '#0d6efd';
}
unset($u);

jsonOk(['users' => $users]);
