(function () {
    'use strict';

    function init() {
        var checkbox = document.querySelector('[data-invoice-requested-toggle]');
        if (!checkbox || checkbox.dataset.bound === '1') {
            return;
        }
        checkbox.dataset.bound = '1';

        var orderId = checkbox.dataset.orderId || '';
        var token = checkbox.dataset.csrfToken || '';
        var buttonWrap = document.querySelector('[data-invoice-button-wrap]');

        checkbox.addEventListener('change', function () {
            var newValue = checkbox.checked ? 1 : 0;
            checkbox.disabled = true;

            var formData = new FormData();
            formData.append('_token', token);
            formData.append('invoice_requested', String(newValue));

            fetch('/orders/' + encodeURIComponent(orderId) + '/invoice-requested/toggle', {
                method: 'POST',
                headers: { 'X-Requested-With': 'XMLHttpRequest' },
                body: formData,
                credentials: 'same-origin'
            })
                .then(function (resp) {
                    if (!resp.ok) {
                        throw new Error('HTTP ' + resp.status);
                    }
                    return resp.json();
                })
                .then(function (data) {
                    if (!data || !data.success) {
                        throw new Error(data && data.error ? data.error : 'Blad serwera');
                    }
                    if (buttonWrap) {
                        buttonWrap.style.display = newValue ? '' : 'none';
                    }
                })
                .catch(function (err) {
                    checkbox.checked = !checkbox.checked;
                    if (window.OrderProAlerts && typeof window.OrderProAlerts.error === 'function') {
                        window.OrderProAlerts.error('Nie udalo sie zmienic flagi faktury: ' + (err && err.message ? err.message : ''));
                    } else {
                        console.error('invoice-requested toggle failed', err);
                    }
                })
                .finally(function () {
                    checkbox.disabled = false;
                });
        });
    }

    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', init);
    } else {
        init();
    }
})();
