<?php
// Endpoint: guardar 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;
}

$input = json_decode(file_get_contents('php://input'), true);
$desk_id = isset($input['desk_id']) ? intval($input['desk_id']) : 0;
$statuses = isset($input['statuses']) && is_array($input['statuses']) ? $input['statuses'] : [];
if ($desk_id <= 0) {
    http_response_code(400);
    echo json_encode(['success' => false, 'message' => 'Parámetros inválidos']);
    exit;
}

// Validar lista
$db = getDB();
// Intentar permitir estados dinámicos: si la columna es ENUM, convertir a VARCHAR
try {
    $pdo = $db->getConnection();
    $stmtCol = $pdo->prepare("SELECT DATA_TYPE, COLUMN_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = ? AND TABLE_NAME = 'desk_allowed_statuses' AND COLUMN_NAME = 'status' LIMIT 1");
    $stmtCol->execute([DB_NAME]);
    $col = $stmtCol->fetch(PDO::FETCH_ASSOC);
    if ($col && stripos($col['COLUMN_TYPE'] ?? '', 'enum(') === 0) {
        $pdo->exec("ALTER TABLE desk_allowed_statuses MODIFY status VARCHAR(50) NOT NULL");
    }
} catch (Exception $e) {
    // Continuar igualmente; si falla, las inserciones fuera del ENUM fallarán y se reportará
}
// Filtrar por formato seguro (clave) y normalizar
$statuses = array_values(array_unique(array_filter($statuses, function($s){ return is_string($s) && preg_match('/^[a-z0-9_\-]{2,50}$/', $s); })));

// $db ya obtenido arriba

try {
    // Asegurar existencia del desk
    $desk = $db->selectOne("SELECT id FROM desks WHERE id = ?", [$desk_id]);
    if (!$desk) {
        http_response_code(404);
        echo json_encode(['success' => false, 'message' => 'Desk no encontrado']);
        exit;
    }

    // Transacción: limpiar y reinsertar configuraciones
    $pdo = $db->getConnection();
    $pdo->beginTransaction();
    $db->execute("DELETE FROM desk_allowed_statuses WHERE desk_id = ?", [$desk_id]);
    $pos = 0;
    foreach ($statuses as $st) {
        $db->execute("INSERT INTO desk_allowed_statuses (desk_id, status, position, created_at) VALUES (?, ?, ?, NOW())", [$desk_id, $st, $pos++]);
    }
    $pdo->commit();

    echo json_encode(['success' => true, 'desk_id' => $desk_id, 'saved' => $statuses]);
} catch (Exception $e) {
    if (isset($pdo) && $pdo->inTransaction()) { $pdo->rollBack(); }
    http_response_code(500);
    echo json_encode(['success' => false, 'message' => 'Error del servidor', 'error' => $e->getMessage()]);
}
?>