<?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 DISTINCT status FROM desk_allowed_statuses WHERE desk_id = ? ORDER BY status');
    $st->execute([$desk_id]);
    $rows = $st->fetchAll(PDO::FETCH_COLUMN);
    echo json_encode(['success'=>true,'statuses'=>array_values($rows ?: [])]);
  } else {
    // Todos los estados del sistema
    $rows1 = $pdo->query("SELECT DISTINCT das.status FROM desk_allowed_statuses das INNER JOIN desks d ON das.desk_id = d.id WHERE d.status='active' ORDER BY das.status")->fetchAll(PDO::FETCH_COLUMN) ?: [];
    $rows2 = $pdo->query("SELECT DISTINCT desk_status FROM clients WHERE desk_status IS NOT NULL AND desk_status <> '' ORDER BY desk_status")->fetchAll(PDO::FETCH_COLUMN) ?: [];
    $rows3 = $pdo->query("SELECT DISTINCT status FROM leads WHERE status IS NOT NULL AND status <> '' ORDER BY status")->fetchAll(PDO::FETCH_COLUMN) ?: [];
    $set = [];
    foreach (array_merge($rows1, $rows2, $rows3) as $s) { if (!empty($s)) { $set[$s] = true; } }
    $statuses = array_keys($set);
    sort($statuses);
    echo json_encode(['success'=>true,'statuses'=>$statuses]);
  }
} catch (Throwable $e) {
  echo json_encode(['success'=>false,'statuses'=>[]]);
}
?>
