function loadConfig() {
    fetch(`/api/config?username=${username}`)
        .then(response => response.json())
        .then(data => {
            const cfg = data.config;
            document.getElementById("server-type").value = data.type;
            document.getElementById("server-version").value = data.version;
            document.getElementById("max-players").value = cfg["max-players"];
            document.getElementById("pvp").checked = cfg["pvp"];
            document.getElementById("difficulty").value = cfg["difficulty"];
            document.getElementById("online-mode").checked = cfg["online-mode"];
            document.getElementById("spawn-monsters").checked = cfg["spawn-monsters"];
            document.getElementById("spawn-animals").checked = cfg["spawn-animals"];
            document.getElementById("allow-nether").checked = cfg["allow-nether"];
            document.getElementById("max-build-height").value = cfg["max-build-height"];
            document.getElementById("view-distance").value = cfg["view-distance"];
            document.getElementById("andus-drasl").value = cfg["andus-drasl"]
        })
        .catch(err => {
            console.error("Błąd wczytywania konfiguracji: ", err);
            alert("Nie udało się załadować konfiguracji serwera.");
        });
}

document.querySelector('[onclick="showTab(\'config\')"]').addEventListener('click', loadConfig);

function saveConfig() {
    const config = {
        type: document.getElementById("server-type").value,
        version: document.getElementById("server-version").value,
        max_players: document.getElementById("max-players").value,
        pvp: document.getElementById("pvp").checked,
        difficulty: document.getElementById("difficulty").value,
        online_mode: document.getElementById("online-mode").checked,
        spawn_monsters: document.getElementById("spawn-monsters").checked,
        spawn_animals: document.getElementById("spawn-animals").checked,
        allow_nether: document.getElementById("allow-nether").checked,
        max_build_height: document.getElementById("max-build-height").value,
        view_distance: document.getElementById("view-distance").value,
        andus_drasl: document.getElementById("andus-drasl").value
    };

    fetch('/api/config', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ username, config })
    }).then(res => res.json()).then(data => {
        if (data.success) {
            alert("Konfiguracja została zapisana!");
        } else {
            alert("Błąd zapisywania konfiguracji.");
        }
    });
}