<?php
ob_start();
session_start();
header('Content-Type: application/json; charset=utf-8');

if (!isset($_SESSION['username'])) {
    http_response_code(401);
    echo json_encode(['success' => false, 'msg' => 'Unauthorized']);
    exit;
}

require_once __DIR__ . '/../../wizwizxui-timebot/services/PanelBridge.php';

$data = [
    'XUI_AUTH_MODE' => $_POST['XUI_AUTH_MODE'] ?? 'auto',
    'XUI_BASE_URL' => trim($_POST['XUI_BASE_URL'] ?? ''),
    'XUI_API_TOKEN' => trim($_POST['XUI_API_TOKEN'] ?? ''),
    'XUI_USERNAME' => trim($_POST['XUI_USERNAME'] ?? ''),
    'XUI_PASSWORD' => trim($_POST['XUI_PASSWORD'] ?? ''),
    'XUI_SUBSCRIPTION_BASE_URL' => trim($_POST['XUI_SUBSCRIPTION_BASE_URL'] ?? ''),
    'XUI_SUB_PATH' => trim($_POST['XUI_SUB_PATH'] ?? '/sub/') ?: '/sub/',
    'XUI_HTTP_TIMEOUT_SECONDS' => (string) (int) ($_POST['XUI_HTTP_TIMEOUT_SECONDS'] ?? 15),
];

echo json_encode(PanelBridge::saveXuiEnv($data), JSON_UNESCAPED_UNICODE);
