<?php
if (session_status() === PHP_SESSION_NONE) { session_start(); }
if (!defined('BASE_PATH')) { define('BASE_PATH', dirname(dirname(dirname(__DIR__)))); }
require_once BASE_PATH . '/database/config.php';
require_once BASE_PATH . '/database/connection.php';
header('Content-Type: application/json; charset=utf-8');

$desk_id = (int)($_GET['desk_id'] ?? 0);
try {
  $db = Database::getInstance();
  $pdo = $db->getConnection();
  if ($desk_id > 0) {
    $st = $pdo->prepare('SELECT u.id, CONCAT(u.first_name, " ", u.last_name) AS full_name FROM desk_users du INNER JOIN users u ON du.user_id = u.id WHERE du.desk_id = ? AND u.status = "active" ORDER BY u.first_name, u.last_name');
    $st->execute([$desk_id]);
    $rows = $st->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode(['success'=>true,'users'=>$rows ?: []]);
  } else {
    $rows = $pdo->query('SELECT id, CONCAT(first_name, " ", last_name) AS full_name FROM users WHERE status = "active" ORDER BY first_name, last_name')->fetchAll(PDO::FETCH_ASSOC) ?: [];
    echo json_encode(['success'=>true,'users'=>$rows]);
  }
} catch (Throwable $e) {
  echo json_encode(['success'=>false,'users'=>[]]);
}
?>
