<?php
// Endpoint: obtener usuarios vinculados a un desk
session_start();
define('BASE_PATH', dirname(__DIR__, 2));
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';

function isLoggedIn() {
    return isset($_SESSION['user_id']) && !empty($_SESSION['user_id']);
}

header('Content-Type: application/json; charset=utf-8');

if (!isLoggedIn()) {
    http_response_code(401);
    echo json_encode(['success' => false, 'message' => 'No autorizado']);
    exit;
}

$desk_id = isset($_GET['desk_id']) ? intval($_GET['desk_id']) : 0;
if ($desk_id <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Parámetro desk_id inválido']);
    exit;
}

$db = getDB();

try {
    // Validar que el desk existe y está activo
    $desk = $db->selectOne("SELECT id, name FROM desks WHERE id = ? AND status = 'active'", [$desk_id]);
    if (!$desk) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Desk no encontrado o inactivo']);
        exit;
    }

    // Obtener usuarios vinculados al desk (activos)
    $users = $db->select(
        "SELECT u.id, u.username, CONCAT(u.first_name, ' ', u.last_name) AS full_name
         FROM users u
         INNER JOIN desk_users du ON du.user_id = u.id
         WHERE du.desk_id = ? AND u.status = 'active'
         ORDER BY full_name",
        [$desk_id]
    );

    echo json_encode(['success' => true, 'desk' => $desk, 'users' => $users]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error del servidor', 'error' => $e->getMessage()]);
}
?>