// source --> https://ultra-fab.com/wp-content/plugins/integration-with-quickbooks/public/js/integration-with-quickbooks-public.js?ver=3.2.0 

jQuery(document).ready(function($) {

	const ajax_url = ajax_data_public.ajax_url;
    const nonce = ajax_data_public.ajax_nonce;
    const downloaded_successfully = ajax_data_public.downloaded_successfully;

    jQuery(document).on('click', '.download_invoice', function (e) {
        e.preventDefault();

        var qb_invoice_id = jQuery(this).attr('data-qb-order-id');
        var woo_order_id = jQuery(this).attr('data-order-id');

        var button = jQuery(this);
        button.addClass('wps-btn__loader'); // Add loader class

        if (qb_invoice_id) {
            var data = {
                action: 'download_invoices_from_quickbooks',
                qb_invoice_id: qb_invoice_id,
                woo_order_id: woo_order_id,
                nonce: nonce,
            };

            jQuery.post(ajax_url, data, function (response) {
                button.removeClass('wps-btn__loader');

                if (response.success) {
                    const link = document.createElement('a');
                    link.href = response.data.download_url;
                    link.download = '';
                    document.body.appendChild(link);
                    link.click();
                    button.next('.download_invoice_message').show().text(downloaded_successfully);
                    setTimeout(function () {
                        button.next('.download_invoice_message').fadeOut();
                    }, 3000);
                } else {
                    alert(response.data?.message || 'Failed to download the invoice. Please try again.');
                }
            }).fail(function (xhr, status, error) {
                button.removeClass('wps-btn__loader');
                alert('AJAX error: ' + error);
            });
        } else {
            button.removeClass('wps-btn__loader');
            alert('No QuickBooks invoice ID found.');
        }
    });
});