<?php
// Endpoint: obtener estados permitidos 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 {
    $desk = $db->selectOne("SELECT id, name, status FROM desks WHERE id = ?", [$desk_id]);
    if (!$desk) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Desk no encontrado']);
        exit;
    }
    // Lista global de estados disponibles
$all_statuses = ['new','contacted','qualified','demo_scheduled','demo_completed','deposit_pending','deposited','active_trader','inactive','closed_lost'];
// Intentar cargar estados dinámicos si existe la tabla lead_statuses
try {
    $pdo = $db->getConnection();
    $pdo->exec("CREATE TABLE IF NOT EXISTS lead_statuses (
        id INT AUTO_INCREMENT PRIMARY KEY,
        `key` VARCHAR(50) NOT NULL UNIQUE,
        display_name VARCHAR(100) NOT NULL,
        color VARCHAR(7) DEFAULT '#64748b',
        is_active TINYINT(1) DEFAULT 1,
        is_system TINYINT(1) DEFAULT 0,
        created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
        updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci");
    $rowsAll = $db->select("SELECT `key` FROM lead_statuses WHERE is_active = 1 ORDER BY display_name ASC");
    if (!empty($rowsAll)) {
        $all_statuses = array_map(function($r){ return $r['key']; }, $rowsAll);
    }
} catch (Exception $e) {
    // Mantener lista global por defecto
}
    $rows = $db->select("SELECT status, position FROM desk_allowed_statuses WHERE desk_id = ? ORDER BY position ASC, status ASC", [$desk_id]);
    $allowed = array_map(function($r){ return $r['status']; }, $rows);
    echo json_encode(['success' => true, 'desk' => $desk, 'allowed' => $allowed, 'all' => $all_statuses]);
} catch (Exception $e) {
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error del servidor', 'error' => $e->getMessage()]);
}
?>