<?php
// Endpoint: obtener estados de lead disponibles para 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, status 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;
    }

    // Estados disponibles SOLO por desk (sin fallback a globales)
    $rows = $db->select("SELECT status FROM desk_allowed_statuses WHERE desk_id = ? ORDER BY position ASC, status ASC", [$desk_id]);
    $statuses = !empty($rows) ? array_map(function($r){ return $r['status']; }, $rows) : [];
    echo json_encode(['success' => true, 'desk' => $desk, 'statuses' => $statuses]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error del servidor', 'error' => $e->getMessage()]);
}
?>