jQuery(function ($) {
    if ($('.app-content.orders').length < 1) return;
    $(document).on('change', '#ipp', function (e) {
        const value = $(this).val();
        $('input[name="ipp"]').val(value);
        $('.filter-form-wrapper form').trigger('submit');
    });

    $(document).on('click', '.pagination a', function (e) {
        e.preventDefault();
        const value = $(this).text();
        $('input[name="page"]').val(value);
        $('.filter-form-wrapper form').trigger('submit');
    })

    function loadProvinces(country, selectedState) {
        var stateSelect = document.getElementById('billing_state');
        if (!stateSelect) return;

        stateSelect.innerHTML = '<option value="">' + anbarak.i18n.select_province + '</option>';

        if (!country) {
            return;
        }

        fetch(anbarak.ajax_url + '?action=anbarak_get_provinces&country=' + encodeURIComponent(country) + '&security=' + encodeURIComponent(anbarak.nonce))
            .then(response => response.json())
            .then(data => {
                if (data.success && data.data.provinces) {
                    Object.entries(data.data.provinces).forEach(function ([code, name]) {
                        var opt = document.createElement('option');
                        opt.value = code;
                        opt.textContent = name;
                        if (code === selectedState) {
                            opt.selected = true;
                        }
                        stateSelect.appendChild(opt);
                    });
                }
            });
    }

    $(document).on('click', '.anbarak-order-details', function () {
        const button = this;
        const orderId = $(button).data('order-id');

        button.classList.add('loading');

        fetch(anbarak.ajax_url + '?action=anbarak_get_order_details&order_id=' + encodeURIComponent(orderId) + '&security=' + encodeURIComponent(anbarak.nonce))
            .then(response => response.json())
            .then(data => {
                document.getElementById('order-details-content').innerHTML = data.data.html;
                MicroModal.show('order-details-modal');
            })
            .catch(function () {
                alert(anbarak.i18n.error);
            })
            .finally(function () {
                button.classList.remove('loading');
            });
    });

    $(document).on('click', '.anbarak-edit-customer', function () {
        const button = this;
        const orderId = $(button).data('order-id');

        button.classList.add('loading');

        fetch(anbarak.ajax_url + '?action=anbarak_get_customer_data&order_id=' + encodeURIComponent(orderId) + '&security=' + encodeURIComponent(anbarak.nonce))
            .then(response => response.json())
            .then(response => {
                var data = response.data;
                document.getElementById('edit-order-id').value = orderId;
                document.getElementById('billing_first_name').value = data.billing_first_name || '';
                document.getElementById('billing_last_name').value = data.billing_last_name || '';
                document.getElementById('billing_email').value = data.billing_email || '';
                document.getElementById('billing_phone').value = data.billing_phone || '';

                var countrySelect = document.getElementById('billing_country');
                if (countrySelect) {
                    countrySelect.value = data.billing_country || anbarak.default_country || '';
                    loadProvinces(countrySelect.value, data.billing_state || '');
                } else {
                    document.getElementById('billing_state').value = data.billing_state || '';
                }

                document.getElementById('billing_city').value = data.billing_city || '';
                document.getElementById('billing_address_1').value = data.billing_address_1 || '';
                document.getElementById('billing_address_2').value = data.billing_address_2 || '';
                document.getElementById('billing_postcode').value = data.billing_postcode || '';
                MicroModal.show('edit-customer-modal');
            })
            .catch(function () {
                alert(anbarak.i18n.error);
            })
            .finally(function () {
                button.classList.remove('loading');
            });
    });

    $(document).on('change', '#billing_country', function () {
        loadProvinces(this.value, '');
    });

    $(document).on('click', '.anbarak-cancel-order', function () {
        const orderId = $(this).data('order-id');

        anbarakConfirmAsync({
            message: anbarak.i18n.are_you_sure,
            type: 'ok-cancel',
        }).then(function (confirmed) {
            if (!confirmed) return;

            fetch(anbarak.ajax_url + '?action=anbarak_cancel_order&order_id=' + encodeURIComponent(orderId) + '&security=' + encodeURIComponent(anbarak.nonce))
                .then(response => response.json())
                .then(data => {
                    if (data.success) {
                        location.reload();
                    } else {
                        alert(anbarak.i18n.error);
                    }
                });
        });
    });

    $(document).on('submit', '#edit-customer-form', function (e) {
        e.preventDefault();

        const formData = new FormData(this);
        formData.append('security', anbarak.nonce);

        fetch(anbarak.ajax_url + '?action=anbarak_update_customer_info', {
            method: 'POST',
            body: formData
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    MicroModal.close('edit-customer-modal');
                } else {
                    alert(anbarak.i18n.error);
                }
            });
    });

})
