document.addEventListener('DOMContentLoaded', function () {
    document.querySelectorAll('.checkbox').forEach(function (checkbox) {
        checkbox.addEventListener('change', async function (e) {
            const input = e.target;
            const apiUrl = input.getAttribute('data-api-url');
            const changeKey = input.getAttribute('data-api-changevalue');
            const dataRaw = input.getAttribute('data-api-data');

            let dataObj;
            try {
                dataObj = JSON.parse(dataRaw);
            } catch (err) {
                console.error('Invalid JSON in data-api-data:', err);
                return;
            }

            // Toggle value FIRST
            if (changeKey in dataObj) {
                const currentValue = dataObj[changeKey];
                dataObj[changeKey] = currentValue === '1' || currentValue === 1 ? 0 : 1;
            }

            // Add method override
            dataObj['X-HTTP-Method-Override'] = 'PUT';

            // Convert to URL-encoded string
            const formBody = new URLSearchParams(dataObj).toString();

            try {
                const response = await fetch(apiUrl, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    body: formBody
                });

                if (response.ok) {
                    // Remove X-HTTP-Method-Override before saving back
                    delete dataObj['X-HTTP-Method-Override']
                    input.setAttribute('data-api-data', JSON.stringify(dataObj));
                } else {
                    input.checked = !input.checked; // revert toggle
                    console.error('Request failed:', await response.text());
                }
            } catch (err) {
                input.checked = !input.checked;
                console.error('Request error:', err);
            }

        });
    });
});