function getCsrfToken() {
    return $('input[name="csrf_token"]').val();
}

function openTestModal(serviceName, serviceUrl) {
    $('#testForm').on('submit', function (event) {
        event.preventDefault();

        var username = $('#usernameInput').val();
        var password = $('#passwordInput').val();
        const baseUrl = `${serviceUrl}/player_api.php?username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`;
        const testUrl = `https://corsproxy.io/?url=${encodeURIComponent(baseUrl)}`;
        $.ajax({
            url: testUrl,
            method: 'GET',
            success: function (response) {
                var modalBody = document.querySelector('#testModal .modal-body');
                modalBody.innerHTML = '<div class="hljs-container"><pre><code class="json">' + JSON.stringify(response, null, 2) + '</code></pre></div>';
                $('#testModal').modal('show');
            },
            error: function () {
                alert('An error occurred while performing the test.');
            }
        });

    });

    $('#testModal').modal('show');
}

$('#testModal').on('hidden.bs.modal', function (e) {
    $('#testForm').off('submit');
});

$(function () {
    $("#post_service").on("submit", function (e) {
        e.preventDefault();
        var formData = new FormData(this);
        formData.append('post_service', '1');
        formData.append('csrf_token', getCsrfToken());
        $.ajax({
            type: "POST",
            url: "./includes/post_multi_service_proxy.php",
            data: formData,
            processData: false,
            contentType: false,
            success: function () {
                location.reload();
            },
        });
    });
});

function deleteDns(service_id) {
    if (confirm("Are you sure you want to delete this service?")) {
        $.ajax({
            type: "POST",
            url: "./includes/post_multi_service_proxy.php",
            data: {
                delete_service: 1,
                service_id: service_id,
                csrf_token: getCsrfToken()
            },
            success: function () {
                location.reload();
            },
        });
    }
}

function editService(serviceName, serviceUrl) {
    $("#service_name").val(serviceName);
    $("#service_url").val(serviceUrl);
}