/**
 * admin.js
 *
 * @author     alfiopiccione <alfio.piccione@gmail.com>
 * @copyright  Copyright (c) 2018, alfiopiccione
 * @license    http://opensource.org/licenses/gpl-2.0.php GPL v2
 *
 * Copyright (C) 2018 alfiopiccione <alfio.piccione@gmail.com>
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

;(
    function (_, $, wc_el_inv_admin) {

        /**
         * createEditLink
         *
         * Edit Link
         *
         * @since 1.0.0
         *
         * @param id
         * @param appendTo
         * @param position
         */
        function createEditLink(id, appendTo, position)
        {
            var edit = document.createElement('a');
            edit.setAttribute('id', id);
            edit.setAttribute('href', 'javascript:;');
            edit.innerHTML = '<i class="dashicons dashicons-edit"></i>';
            appendTo.insertAdjacentElement(position, edit);
        }

        /**
         * Button Save
         *
         * @since 1.0.0
         *
         * @param id
         * @param appendTo
         * @param position
         */
        function createButtonSave(id, appendTo, position)
        {
            var button = document.createElement('button');
            button.setAttribute('id', id);
            button.setAttribute('name', id);
            button.setAttribute('type', 'submit');
            button.setAttribute('class', 'button');
            button.innerText = wc_el_inv_admin.text_save;
            appendTo.insertAdjacentElement(position, button);
        }

        function createManualResetToggle(input, checkboxId)
        {
            if (!input || document.getElementById(checkboxId)) {
                return document.getElementById(checkboxId);
            }

            var wrap = document.createElement('div');
            wrap.setAttribute('id', checkboxId + '_wrap');
            wrap.style.marginTop = '10px';

            var label = document.createElement('label');
            label.setAttribute('for', checkboxId);
            label.style.display = 'inline-flex';
            label.style.alignItems = 'center';
            label.style.gap = '8px';

            var checkbox = document.createElement('input');
            checkbox.setAttribute('type', 'checkbox');
            checkbox.setAttribute('id', checkboxId);
            checkbox.setAttribute('name', 'wc_el_inv_options[' + checkboxId.replace('wc_el_inv-', 'wc_el_inv-settings-') + ']');
            checkbox.setAttribute('value', 'on');

            var text = document.createElement('span');
            text.innerText = wc_el_inv_admin.manual_reset_checkbox;

            label.appendChild(checkbox);
            label.appendChild(text);
            wrap.appendChild(label);

            var help = document.createElement('small');
            help.style.display = 'block';
            help.style.marginTop = '6px';
            help.innerText = wc_el_inv_admin.manual_reset_help;
            wrap.appendChild(help);

            input.insertAdjacentElement('afterend', wrap);

            return checkbox;
        }

        function attachManualResetConfirmation(button, input, checkbox)
        {
            if (!button || button.hasAttribute('data-manual-reset-bound')) {
                return;
            }

            button.setAttribute('data-manual-reset-bound', '1');
            button.addEventListener('click', function (event) {
                if ('1' === button.getAttribute('data-manual-reset-confirmed')) {
                    button.removeAttribute('data-manual-reset-confirmed');
                    return;
                }

                if (!checkbox || !checkbox.checked) {
                    return;
                }

                var nextValue = parseInt(input.value, 10);
                if (!nextValue || nextValue < 1) {
                    return;
                }

                event.preventDefault();
                confirmDialog(wc_el_inv_admin.manual_reset_confirm).then(function (confirmed) {
                    if (!confirmed) {
                        return;
                    }

                    var form = button.closest('form');
                    if (form) {
                        button.setAttribute('data-manual-reset-confirmed', '1');
                        if ('function' === typeof form.requestSubmit) {
                            form.requestSubmit(button);
                        } else {
                            form.submit();
                        }
                    }
                });
            });
        }

        /**
         * createCloseLink
         *
         * Close Link
         *
         * @since 1.0.0
         *
         * @param id
         * @param appendTo
         * @param position
         */
        function createCloseLink(id, appendTo, position)
        {
            var close = document.createElement('a');
            close.setAttribute('id', id);
            close.setAttribute('href', 'javascript:;');
            close.innerHTML = '<i class="dashicons dashicons-no"></i>';
            appendTo.insertAdjacentElement('beforeend', close);
        }

        function confirmDialog(message, options)
        {
            options = options || {};

            if (!window.Swal || 'function' !== typeof window.Swal.fire) {
                return Promise.resolve(window.confirm(message));
            }

            return window.Swal.fire({
                title: options.title || '',
                text: message,
                icon: options.icon || 'warning',
                showCancelButton: true,
                confirmButtonText: options.confirmButtonText || 'OK',
                cancelButtonText: options.cancelButtonText || 'Cancel',
                reverseButtons: true,
            }).then(function (result) {
                return !!result.isConfirmed;
            });
        }

        function notifyDialog(message, options)
        {
            options = options || {};

            if (!window.Swal || 'function' !== typeof window.Swal.fire) {
                window.alert(message);
                return Promise.resolve();
            }

            return window.Swal.fire({
                title: options.title || '',
                text: message,
                icon: options.icon || 'info',
                timer: options.timer || 2200,
                timerProgressBar: true,
                showConfirmButton: false,
            }).then(function () {
                return true;
            });
        }

        /**
         * editInvoiceNumber
         *
         * Edit and Save invoice next number
         *
         * @since 1.0.0
         */
        function editInvoiceNumber()
        {
            var input = document.getElementById('wc_el_inv-settings-number_next_invoice');
            if (!input) {
                return;
            }

            if ('' !== input.value) {
                input.setAttribute('disabled', 'disabled');
            }

            createEditLink('edit_invoice_next_number', input, 'afterend');
            var edit = document.getElementById('edit_invoice_next_number');

            // Edit.
            edit.addEventListener('click', function () {
                if (edit.hasAttribute('readonly')) {
                    return;
                }
                // Hide edit
                edit.style.display = 'none';
                input.removeAttribute('disabled');
                createButtonSave('save_invoice_next_number', input, 'afterend');
                var saveButton = document.getElementById('save_invoice_next_number');
                var resetCheckbox = createManualResetToggle(input, 'wc_el_inv-manual_reset_number_next_invoice');
                attachManualResetConfirmation(saveButton, input, resetCheckbox);
            });
        }

        /**
         * editReceiptNumber
         *
         * Edit and Save receipt next number
         *
         * @since 1.0.0
         */
        function editReceiptNumber()
        {
            var input = document.getElementById('wc_el_inv-settings-number_next_receipt');
            if (!input) {
                return;
            }

            if ('' !== input.value) {
                input.setAttribute('disabled', 'disabled');
            }

            createEditLink('edit_receipt_next_number', input, 'afterend');
            var edit = document.getElementById('edit_receipt_next_number');

            // Edit.
            edit.addEventListener('click', function () {
                if (edit.hasAttribute('readonly')) {
                    return;
                }
                // Hide edit
                edit.style.display = 'none';
                input.removeAttribute('disabled');
                createButtonSave('save_receipt_next_number', input, 'afterend');
                var saveButton = document.getElementById('save_receipt_next_number');
                if (parseInt(input.value) > 0) {
                    var resetCheckbox = createManualResetToggle(input, 'wc_el_inv-manual_reset_number_next_receipt');
                    attachManualResetConfirmation(saveButton, input, resetCheckbox);
                }
            });
        }

        /**
         * editCreditNoteNumber
         *
         * Edit and Save credit note next number
         *
         * @since 1.0.0
         */
        function editCreditNoteNumber()
        {
            var input = document.getElementById('wc_el_inv-settings-number_next_credit_note');
            if (!input) {
                return;
            }

            if ('' !== input.value) {
                input.setAttribute('disabled', 'disabled');
            }

            createEditLink('edit_credit_note_next_number', input, 'afterend');
            var edit = document.getElementById('edit_credit_note_next_number');

            // Edit.
            edit.addEventListener('click', function () {
                if (edit.hasAttribute('readonly')) {
                    return;
                }
                // Hide edit
                edit.style.display = 'none';
                input.removeAttribute('disabled');
                input.removeAttribute('readonly');
                createButtonSave('save_credit_note_next_number', input, 'afterend');
            });

            var input2 = document.getElementById('wc_el_inv-settings-number_next_credit_note_receipt');
            if (!input2) {
                return;
            }

            if ('' !== input2.value) {
                input2.setAttribute('disabled', 'disabled');
            }

            createEditLink('edit_credit_note_receipt_next_number', input2, 'afterend');
            var edit2 = document.getElementById('edit_credit_note_receipt_next_number');

            // Edit.
            edit2.addEventListener('click', function () {
                if (edit2.hasAttribute('readonly')) {
                    return;
                }
                // Hide edit
                edit2.style.display = 'none';
                input2.removeAttribute('disabled');
                input2.removeAttribute('readonly');
                createButtonSave('save_credit_note_receipt_next_number', input2, 'afterend');
            });
        }

        /**
         * editOrderInvoiceNumber
         *
         * Edit order invoice number
         *
         * @since 1.0.0
         */
        function editOrderInvoiceNumber()
        {
            var inputs = document.querySelectorAll('.wc_el_inv-order_fields');
            if (0 === inputs.length) {
                return;
            }

            _.forEach(inputs, function (input) {
                if ('' !== input.value) {
                    input.setAttribute('disabled', 'disabled');
                }
            });

            var wrapTitle = document.querySelector('.wc_el_inv__general-order h3');
            var fields = document.querySelector('.wc_el_inv__general-order--hidden-fields');
            var textData = document.querySelector('.wc_el_inv__general-order--text-data');

            if (wrapTitle && fields && textData) {
                // Create edit action
                createEditLink('edit_invoice_next_number', wrapTitle, 'beforeend');
                var edit = document.getElementById('edit_invoice_next_number');
                // Create close action
                createCloseLink('close_invoice_next_number', wrapTitle, 'beforeend');
                var close = document.getElementById('close_invoice_next_number');

                // Close default hidden
                close.style.display = 'none';

                // Edit click event.
                edit.addEventListener('click', function () {
                    // Show fields and hide text data
                    fields.style.display = 'block';
                    textData.style.display = 'none';
                    // Hide edit
                    this.style.display = 'none';
                    // Show close
                    close.style.display = 'block';

                    _.forEach(inputs, function (input) {
                        input.removeAttribute('disabled');
                    });
                });

                // Close click event.
                close.addEventListener('click', function () {
                    // Show text data and hide fields
                    fields.style.display = 'none';
                    textData.style.display = 'block';

                    // Hide close
                    close.style.display = 'none';
                    edit.style.display = '';

                    _.forEach(inputs, function (input) {
                        input.setAttribute('disabled', 'disabled');
                    });

                });
            }
        }

        /**
         * editRefundInvoiceNumber
         *
         * Edit refund invoice number
         *
         * @since 1.0.0
         */
        function editRefundInvoiceNumber()
        {
            var refundLine = document.querySelectorAll('.wc_el_inv__refund-invoice[data-order_refund_id]');
            var inputs = document.querySelectorAll('.wc_el_inv-order_fields');
            if (0 === inputs.length) {
                return;
            }

            // Set disabled attr
            _.forEach(inputs, function (input) {
                if ('' !== input.value) {
                    input.setAttribute('disabled', 'disabled');
                }
            });

            // Refund line
            _.forEach(refundLine, function (item, index) {
                var wrapTitle = item.querySelector('.wc_el_inv__refund-invoice td h3');
                var fields = item.querySelector('.wc_el_inv__refund-invoice--hidden-fields');
                var textData = item.querySelector('.wc_el_inv__refund-invoice--text-data');

                if (wrapTitle && fields && textData) {
                    // Create edit action
                    createEditLink('edit_refund_invoice_next_number-' + index, wrapTitle, 'beforeend');
                    var edit = document.getElementById('edit_refund_invoice_next_number-' + index);
                    // Create close action
                    createCloseLink('close_refund_invoice_next_number-' + index, wrapTitle, 'beforeend');
                    var close = document.getElementById('close_refund_invoice_next_number-' + index);

                    // Close default hidden
                    close.style.display = 'none';

                    // Close click event.
                    close.addEventListener('click', function () {
                        // Show text data and hide fields
                        fields.style.display = 'none';
                        textData.style.display = 'block';

                        // Hide close
                        close.style.display = 'none';
                        edit.style.display = '';
                        _.forEach(inputs, function (input) {
                            input.setAttribute('disabled', 'disabled');
                        });

                    });

                    // Edit click event.
                    edit.addEventListener('click', function () {
                        // Show fields and hide text data
                        fields.style.display = 'block';
                        textData.style.display = 'none';
                        // Hide edit
                        this.style.display = 'none';
                        // Show close
                        close.style.display = 'block';

                        _.forEach(inputs, function (input) {
                            input.removeAttribute('disabled');
                        });
                    });
                }
            });

        }

        /**
         * filterByDate
         *
         * Filter by date
         *
         */
        function filterByDate()
        {
            var actions = [
                document.querySelector('.save-all-csv')
            ];

            if ([] === actions) {
                return;
            }

            // Filter in admin table
            var filter = document.querySelector('.filter');
            if (filter) {
                var filterHref = filter.getAttribute('href');
                filter.addEventListener('click', function (evt) {
                    evt.preventDefault();
                    evt.stopImmediatePropagation();
                    var targetHref = setUrlForFilter(filterHref);
                    if (targetHref) {
                        window.location = targetHref;
                    }
                })
            }

            // Endpoint filer
            if (actions) {
                _.forEach(actions, function (item) {

                    if (!item) {
                        return;
                    }

                    item.addEventListener('click', function (evt) {
                        evt.preventDefault();
                        evt.stopImmediatePropagation();
                        var href = setUrlForFilter(evt.target.href);
                        window.open(href, '_blank');
                    })
                });
            }
        }

        /**
         * parseDate
         *
         * Parse Date
         * @param date
         * @returns {number}
         */
        function parseDate(date)
        {
            var dateSplit = date.split(/[^0-9]/);
            var DateString = dateSplit[0] + '-' +
                             dateSplit[1] + '-' +
                             dateSplit[2] + 'T' +
                             dateSplit[3] + ':' +
                             dateSplit[4] + ':' +
                             dateSplit[5] + '+0000';
            var dateObj = new Date(DateString.toString());

            return dateObj.getTime() / 1000;
        }

        /**
         * setUrlForFilter
         *
         * Set url for filter
         *
         *
         * @param baseHref
         * @returns {string|null}
         */
        function setUrlForFilter(baseHref)
        {
            var href;
            var valType = null;
            var valState = null;
            var valProvider = null;

            var dateIN = document.getElementById('date_in');
            var dateOUT = document.getElementById('date_out');
            var filterType = document.getElementById('filter_type');
            var filterState = document.getElementById('filter_state');
            var filterProvider = document.getElementById('filter_provider');

            if (filterType) {
                valType = filterType.options[filterType.selectedIndex].value;
            }

            if (filterState) {
                valState = filterState.options[filterState.selectedIndex].value;
            }

            if (filterProvider) {
                valProvider = filterProvider.options[filterProvider.selectedIndex].value;
            }

            // Add date params
            if (dateIN.value || dateOUT.value) {
                var IN = dateIN.value + 'T00:00:00';
                var OUT = dateOUT.value + 'T23:59:59';

                IN = IN.split(" - ").map(function (date) {
                    return parseDate(date);
                }).join(" - ");

                OUT = OUT.split(" - ").map(function (date) {
                    return parseDate(date);
                }).join(" - ");

                if (dateIN.value && '' === dateOUT.value) {
                    href = baseHref + '&date_in=' + IN;
                }

                if ('' === dateIN.value && dateOUT.value) {
                    href = baseHref + '&date_out=' + OUT
                }

                if (dateIN.value && dateOUT.value) {
                    href = baseHref + '&date_in=' + IN + '&date_out=' + OUT;
                }
            } else {
                href = baseHref;
            }

            // add type param
            if (valType) {
                href = href + '&filter_type=' + valType;
            }

            // add state param
            if (valState) {
                href = href + '&filter_state=' + valState;
            }

            // add state param
            if (valProvider) {
                href = href + '&filter_provider=' + valProvider;
            }

            // Current invoice in table
            var filtered = null;
            if (baseHref && baseHref.indexOf('filtered') > -1) {
                var vars = {};
                baseHref.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
                    vars[key] = value;
                });
                filtered = vars['filtered'];
                if ('no' === filtered) {
                    return baseHref;
                }
            }

            return href;
        }

        /**
         * bulkMarkActions
         *
         * Bulk Mark actions
         */
        function bulkMarkActions()
        {
            var actionBulk = document.getElementById('action_bulk');
            if (!actionBulk) {
                return;
            }

            actionBulk.addEventListener('change', function (evt) {
                var value = evt.target.value;
                var cbs = document.querySelectorAll('input[name="pop-invoice[]"]');
                var cbChecked = false;
                _.forEach(cbs, function (cb) {
                    if (true === cb.checked) {
                        cbChecked = cb.checked;
                    }
                });

                if (!cbChecked && '' !== value) {
                    notifyDialog(wc_el_inv_admin.bulk_invoice_cb, {icon: 'warning'});
                    return;
                }

                var confirmMessage = '';
                if ('sent' === value) {
                    confirmMessage = wc_el_inv_admin.invoice_sent_confirm;
                } else if ('no_sent' === value) {
                    confirmMessage = wc_el_inv_admin.invoice_undo_confirm;
                }

                if (!confirmMessage) {
                    return;
                }

                confirmDialog(confirmMessage).then(function (confirmed) {
                    if (!confirmed) {
                        return;
                    }

                    var form = document.getElementById("wp-list-table-invoice-form");
                    if (form) {
                        var action = document.createElement("input");
                        action.setAttribute('type', 'hidden');
                        action.setAttribute('id', 'bulk-sent');
                        action.setAttribute('name', 'bulk-sent');
                        action.setAttribute('value', value);
                        form.appendChild(action);
                        form.submit();
                    }
                });
            });
        }

        /**
         * markInvoice
         *
         * Ajax mark invoice action
         */
        function markInvoice()
        {
            var triggers = document.querySelectorAll('.mark_trigger');
            if (!triggers) {
                return;
            }
            _.forEach(triggers, function (trigger) {

                trigger.addEventListener('click', function (evt) {
                    evt.preventDefault();
                    evt.stopImmediatePropagation();

                    var confirmMessage = '';

                    if (this.classList.contains('mark_as_sent')) {
                        confirmMessage = wc_el_inv_admin.invoice_sent_confirm;
                    } else if (this.classList.contains('mark_undo')) {
                        confirmMessage = wc_el_inv_admin.invoice_undo_confirm;
                    }

                    if (!confirmMessage) {
                        return;
                    }

                    confirmDialog(confirmMessage).then(function (confirmed) {
                        if (!confirmed) {
                            return;
                        }

                        $.ajax({
                            url: wc_el_inv_admin.ajax_url,
                            method: 'POST',
                            cache: false,
                            data: {
                                'action': 'markInvoice',
                                'action_url': trigger.href,
                                'nonce': wc_el_inv_admin.ajax_nonce
                            },
                            /**
                             * Before Send
                             */
                            beforeSend: function () {

                            },
                            /**
                             * Complete
                             */
                            complete: function (xhr, status) {
                                if ('dev' === wc_el_inv_admin.mode) {
                                    // Stop running.
                                    console.log(xhr, status)
                                }
                            },
                            /**
                             * Error
                             */
                            error: function (xhr, status, error) {
                                console.warn('markInvoice ' + error, status);
                            },
                            /**
                             * Success
                             */
                            success: function (response) {
                                console.log(response);
                                window.location.reload();
                            }
                        });
                    });

                })
            });
        }

        /**
         * refundItemControl
         *
         * Refund item control
         */
        function refundItemControl()
        {
            var buttonRefund = document.querySelector('#woocommerce-order-items .inside .refund-items');
            var marks = document.querySelectorAll('#order_refunds .actions .mark_trigger');

            if (!marks) {
                return
            }
            _.forEach(marks, function (mark) {
                if (mark.classList.contains('mark_as_sent')) {
                    if (buttonRefund) {
                        buttonRefund.setAttribute('disabled', true);
                        buttonRefund.innerText = wc_el_inv_admin.refund_item_disabled_text;
                    }
                }
            });

        }

        /**
         * invoiceItemControl
         *
         * invoice item control refund amount
         */
        function invoiceItemControl()
        {
            var refundAmount = document.querySelector('#woocommerce-order-items .inside input#refund_amount');
            var mark = document.querySelector('.wc_el_inv__general-order .actions .mark_trigger');

            if (!refundAmount || !mark) {
                return;
            }

            if (mark.classList.contains('mark_as_sent')) {
                refundAmount.setAttribute('readonly', true);
                refundAmount.insertAdjacentHTML(
                    'afterend',
                    '<p id="readonly-info">' + wc_el_inv_admin.refund_amount_read_only_info_text + '</p>'
                )
            }
        }

        /**
         * choiceType
         *
         * Choice type
         */
        function choiceType()
        {
            var docTypeInputs = document.querySelectorAll('.doc-type-input');
            if (!docTypeInputs) {
                return;
            }

            _.forEach(docTypeInputs, function (input) {
                input.addEventListener('change', function (evt) {
                    this.parentElement
                        .parentElement
                        .parentElement
                        .querySelectorAll('.choice_type--current')[0]
                        .setAttribute('value', this.value);
                })
            });

        }

        /**
         * endPointActions
         *
         * Set document type in query args
         */
        function endPointActions()
        {
            var actions = document.querySelectorAll('.action-endpoint');
            if (!actions) {
                return;
            }

            _.forEach(actions, function (action) {
                action.addEventListener('click', function (evt) {
                    evt.preventDefault();
                    evt.stopImmediatePropagation();

                    var type = this.parentElement.querySelector('.choice_type--current');
                    var href = this.href;
                    if (type) {
                        href = href + '&choice_type=' + type.value;
                    }
                    window.open(href);
                })
            });
        }

        /**
         * getUrlVars
         *
         * Get Url vars
         * @returns {{}}
         */
        function getUrlVars()
        {
            var vars = {};
            var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
                vars[key] = value;
            });
            return vars;
        }

        /**
         * getUrlParam
         *
         * Get url param
         * @param parameter
         * @param defaultvalue
         * @returns {*}
         */
        function getUrlParam(parameter, defaultvalue)
        {
            var urlparameter = defaultvalue;
            if (window.location.href.indexOf(parameter) > -1) {
                urlparameter = getUrlVars()[parameter];
            }
            return urlparameter;
        }

        /**
         * activeSubMenu
         *
         * Active sub menu item
         */
        function activeSubMenu()
        {
            var urlParam = getUrlParam('tab');

            var list = document.querySelectorAll('#toplevel_page_wc_el_inv-options-page ul.wp-submenu li a');
            if (list) {
                list.forEach(function (item) {
                    if (item.parentElement.classList.contains('wp-first-item')) {
                        item.parentElement.remove();
                    }
                    item.parentElement.classList.remove('current');
                    var href = item.getAttribute('href');
                    if (-1 !== href.indexOf(urlParam)) {
                        item.parentElement.classList.add('current');
                    }
                })
            }
        }

        /**
         * reverseChargeEdit
         *
         * Reverse charge quick edit
         */
        function reverseChargeEdit()
        {
            // Gift QuickEdit
            // we create a copy of the WP inline edit post function
            if (typeof inlineEditPost === "undefined") {
                return;
            }

            var wpInlineEdit = inlineEditPost.edit;
            // and then we overwrite the function with our own code

            inlineEditPost.edit = function (id) {
                // "call" the original WP edit function
                // we don't want to leave WordPress hanging
                wpInlineEdit.apply(this, arguments);

                // get the post ID
                var postID = 0;
                if ('object' === typeof (id)) {
                    postID = parseInt(this.getId(id));
                }

                if (postID > 0) {
                    // define the edit row
                    var editRow = $('#edit-' + postID);
                    var postRow = $('#post-' + postID);

                    // get the data
                    var reverseCharge = !!$('.column-reverse_charge > *', postRow).prop('checked');
                    $(':input[name="active_reverse_charge"]', editRow).prop('checked', reverseCharge);
                }
            };
        }

        /**
         * searchOrderByID
         */
        function searchOrderByID()
        {
            var searchInput = document.getElementById('wc_el_inv_order_search');
            var searchTrigger = document.querySelector('.wc_el_inv_order_search_trigger');
            if (searchInput && searchTrigger) {
                function runSearch(evt) {
                    var url = new URL(window.location.href);
                    var filterProvider = document.getElementById('filter_provider');
                    var searchValue = searchInput.value.trim();

                    evt.preventDefault();
                    evt.stopImmediatePropagation();

                    if ('dev' === wc_el_inv_admin.mode) {
                        console.log('search:', searchValue);
                    }

                    if ('' !== searchValue) {
                        url.searchParams.set('order_search', searchValue);
                    } else {
                        url.searchParams.delete('order_search');
                    }

                    if (filterProvider && filterProvider.value) {
                        url.searchParams.set('filter_provider', filterProvider.value);
                    }

                    window.location = url.toString();
                }

                searchInput.addEventListener('change', runSearch);
                searchTrigger.addEventListener('click', function (evt) {
                    if ('' === searchInput.value.trim()) {
                        evt.preventDefault();
                        evt.stopImmediatePropagation();
                        notifyDialog(wc_el_inv_admin.search_by_id, {icon: 'warning'});
                        return;
                    }

                    runSearch(evt);
                });
            }
        }

        /**
         * advancedNav
         */
        function advancedNav()
        {
            var navLinks = document.querySelectorAll('.nav_section_advanced#wc_output_fields_nav ul li a');

            if (navLinks) {
                if ('IT' !== wc_el_inv_admin.shop_country) {
                    activeSection('webhook');
                } else {
                    if (window.location.hash === '#reverse-charge' || !window.location.hash) {
                        activeSection('reverse-charge')
                    } else if (window.location.hash === '#import-export') {
                        activeSection('import-export')
                    } else if (window.location.hash === '#automatic-sending') {
                        activeSection('automatic-sending')
                    } else if (window.location.hash === '#webhook') {
                        activeSection('webhook')
                    }
                }

                navLinks.forEach(function (navLink) {
                    navLink.addEventListener('click', function (evt) {
                        navLinks.forEach(function (link) {
                            link.classList.remove('active')
                        });
                        navLink.classList.add('active');
                        var section = evt.target.hash.replace('#', '');
                        activeSection(section)

                    })
                })
            }

            function activeSection(section)
            {
                navLinks.forEach(function (navLink) {
                    if (navLink.getAttribute('href') === '#' + section) {
                        navLink.classList.add('active')
                    } else {
                        navLink.classList.remove('active')
                    }
                });

                var Import = document.querySelector('.wc_el_inv-form .form-table tr.import_collections');
                var Export = document.querySelector('.wc_el_inv-form .form-table tr.export_collections');
                var ReverseCharge = document.querySelector('.wc_el_inv-form .form-table tr.reverse_charge');
                var AutomaticSending = document.querySelector('.wc_el_inv-form .form-table tr.automatic_sending');
                var PopWebhook = document.querySelector('.wc_el_inv-form .form-table tr.pop_webhook');

                if ('reverse-charge' === section) {
                    if (Export) {
                        Export.style.display = 'none';
                    }
                    if (Import) {
                        Import.style.display = 'none';
                    }
                    if (ReverseCharge) {
                        ReverseCharge.style.display = 'table-row';
                    }
                    if (AutomaticSending) {
                        AutomaticSending.style.display = 'none';
                    }
                    if (PopWebhook) {
                        PopWebhook.style.display = 'none';
                    }
                }

                if ('import-export' === section) {
                    if (Export) {
                        Export.style.display = 'table-row';
                    }
                    if (Import) {
                        Import.style.display = 'table-row';
                    }
                    if (ReverseCharge) {
                        ReverseCharge.style.display = 'none';
                    }
                    if (AutomaticSending) {
                        AutomaticSending.style.display = 'none';
                    }
                    if (PopWebhook) {
                        PopWebhook.style.display = 'none';
                    }
                }

                if ('automatic-sending' === section) {
                    if (Export) {
                        Export.style.display = 'none';
                    }
                    if (Import) {
                        Import.style.display = 'none';
                    }
                    if (ReverseCharge) {
                        ReverseCharge.style.display = 'none';
                    }
                    if (AutomaticSending) {
                        AutomaticSending.style.display = 'table-row';
                    }
                    if (PopWebhook) {
                        PopWebhook.style.display = 'none';
                    }
                }

                if ('webhook' === section) {
                    if (Export) {
                        Export.style.display = 'none';
                    }
                    if (Import) {
                        Import.style.display = 'none';
                    }
                    if (ReverseCharge) {
                        ReverseCharge.style.display = 'none';
                    }
                    if (AutomaticSending) {
                        AutomaticSending.style.display = 'none';
                    }
                    if (PopWebhook) {
                        PopWebhook.style.display = 'table-row';
                    }
                }
            }
        }

        /**
         * rcNatureSelect
         */
        function rcNatureSelect()
        {
            var selects = document.querySelectorAll('.rc-nature-select');
            if (selects.length > 0) {
                selects.forEach(function (select) {
                    rcNatureSelectAction(select, false);
                    select.addEventListener('change', function (evt) {
                        rcNatureSelectAction(select, true);
                    });
                })
            }

            /**
             * rcNatureSelectAction
             * @param select
             * @param event
             */
            function rcNatureSelectAction(select, event)
            {
                var data = select.options[select.selectedIndex].text.split(" - ");
                var val = data.length === 2 ? data[0] : '';
                var text = data.length === 2 ? data[1] : '';
                var input = null;

                if ('N7' === val) {
                    text = "IVA assolta in altro stato UE (vendite a distanza ex art. 40 c. 3 e 4 e art. 41 c. 1 lett. b, DL 331/93; prestazione di servizi di telecomunicazioni, teleradiodiffusione ed elettronici ex art. 7-sexies lett. f, g, art. 74-sexies DPR 633/72)"
                }

                if ('wc_el_inv-ue_private_nature_code' === select.getAttribute('id')) {
                    input = document.getElementById('wc_el_inv-ue_private_normative_reference');
                    if (event) {
                        if ('Personalizzato' === text) {
                            input.setAttribute('value', '');
                            input.value = '';
                        } else {
                            input.setAttribute('value', text);
                            input.value = text;
                        }
                    }
                } else if ('wc_el_inv-ue_company_nature_code' === select.getAttribute('id')) {
                    input = document.getElementById('wc_el_inv-ue_company_normative_reference');
                    if (event) {
                        if ('Personalizzato' === text) {
                            input.setAttribute('value', '');
                            input.value = '';
                        } else {
                            input.setAttribute('value', text);
                            input.value = text;
                        }
                    }
                } else if ('wc_el_inv-ue_company_no_vies_nature_code' === select.getAttribute('id')) {
                    input = document.getElementById('wc_el_inv-ue_company_no_vies_normative_reference');
                    if (event) {
                        if ('Personalizzato' === text) {
                            input.setAttribute('value', '');
                            input.value = '';
                        } else {
                            input.setAttribute('value', text);
                            input.value = text;
                        }
                    }
                } else if ('wc_el_inv-extra_ue_private_nature_code' === select.getAttribute('id')) {
                    input = document.getElementById('wc_el_inv-extra_ue_private_normative_reference');
                    if (event) {
                        if ('Personalizzato' === text) {
                            input.setAttribute('value', '');
                            input.value = '';
                        } else {
                            input.setAttribute('value', text);
                            input.value = text;
                        }
                    }
                } else if ('wc_el_inv-extra_ue_company_nature_code' === select.getAttribute('id')) {
                    input = document.getElementById('wc_el_inv-extra_ue_company_normative_reference');
                    if (event) {
                        if ('Personalizzato' === text) {
                            input.setAttribute('value', '');
                            input.value = '';
                        } else {
                            input.setAttribute('value', text);
                            input.value = text;
                        }
                    }
                }

                if (input) {
                    var tr = input.closest('tr');
                    if ('Personalizzato' === text) {
                        tr.style.display = 'table-row';
                    } else {
                        tr.style.display = 'none';
                    }
                }

                if ('dev' === wc_el_inv_admin.mode) {
                    console.log('CODE:', val, 'REF:', text);
                }
            }
        }

        /**
         * showDialogAndMaybeReload
         *
         * @param message
         * @param raw
         * @param notice
         * @param timeout
         */
        function showDialogAndMaybeReload(message, raw, notice, timeout)
        {
            if (!timeout) {
                timeout = 4000;
            }

            if ('dev' === wc_el_inv_admin.mode) {
                console.log('message', message);
                console.log('raw', raw);
            }
            if (!window.Swal || 'function' !== typeof window.Swal.fire) {
                window.alert(message);
                if ('success' === notice || 'notify' === notice || 'error' === notice) {
                    setTimeout(function () {
                        location.reload();
                    }, 'error' === notice ? 0 : timeout);
                }
                return Promise.resolve(true);
            }

            let detailHtml = '';

            if (raw?.response?.data?.violations) {
                raw.response.data.violations.forEach(function (violation) {
                    detailHtml += '<hr><strong>';
                    detailHtml += _.escape('- ' + wc_el_inv_admin.sdi_notice_path + ': ' + (violation.propertyPath || ''));
                    detailHtml += '</strong><br>';
                    detailHtml += _.escape('- ' + wc_el_inv_admin.sdi_notice_content + ': ' + (violation.propertyContent || ''));
                    detailHtml += '<br>';
                    detailHtml += _.escape('- ' + wc_el_inv_admin.sdi_notice_message + ': ' + (violation.message || ''));
                });
            } else if (raw?.detail?.detail) {
                detailHtml += _.escape('- ' + raw.detail.detail);
            } else if (raw?.error) {
                detailHtml += _.escape('- ' + raw.error);
            }

            let html = '<div style="margin:0;font-size:15px;line-height:1.55;">' + _.escape(message || '') + '</div>';
            if (detailHtml) {
                html += '<div style="margin:14px 0 0 0;font-size:13px;line-height:1.5;opacity:0.9;">';
                html += '<strong>' + _.escape(wc_el_inv_admin.sdi_notice_details + ':') + '</strong><br>';
                html += detailHtml;
                html += '</div>';
            }

            const iconMap = {
                success: 'success',
                notify: 'info',
                preserve: 'info',
                error: 'error'
            };
            const shouldReload = 'success' === notice || 'notify' === notice || 'error' === notice;
            const autoClose = 'error' !== notice;

            return window.Swal.fire({
                title: '',
                html: html,
                icon: iconMap[notice] || 'info',
                timer: autoClose ? timeout : undefined,
                timerProgressBar: autoClose,
                showConfirmButton: !autoClose,
                confirmButtonText: 'OK',
                allowOutsideClick: autoClose,
                allowEscapeKey: true,
            }).then(function () {
                if (shouldReload) {
                    location.reload();
                }

                return true;
            });
        }

        /**
         * Parse AJAX response with non-JSON fallback.
         *
         * @param response
         * @returns {Promise<object>}
         */
        function parseAjaxJsonOrThrow(response)
        {
            return response.text().then(function (text) {
                var parsed = null;

                if (text && text.trim() !== '') {
                    try {
                        parsed = JSON.parse(text);
                    } catch (e) {
                        parsed = null;
                    }
                }

                if (!parsed || 'object' !== typeof parsed) {
                    var extractedOverquota = extractPopApiOverquotaPayload(text);
                    if (extractedOverquota) {
                        return extractedOverquota;
                    }

                    var fallbackMessage = text && text.trim() !== ''
                                          ? extractAjaxErrorMessage(text)
                                          : 'Unexpected response from server';
                    var err = new Error(fallbackMessage);
                    err.status = response.status;
                    err.raw = text;
                    throw err;
                }

                return parsed;
            });
        }

        function extractAjaxErrorMessage(raw)
        {
            if ('string' !== typeof raw || '' === raw.trim()) {
                return 'Unexpected response from server';
            }

            var errorMessageMatch = raw.match(/\[\s*error_message\s*\]\s*=>\s*(.+)/i);
            if (errorMessageMatch && errorMessageMatch[1]) {
                return errorMessageMatch[1].trim();
            }

            var jsonStringMatch = raw.match(/\[\s*xml_string\s*\]\s*=>\s*([\s\S]*?)\n\s*\[\s*errors\s*\]\s*=>/i);
            if (jsonStringMatch && jsonStringMatch[1]) {
                var overquotaPayload = extractPopApiOverquotaPayload(jsonStringMatch[1].trim());
                if (overquotaPayload && overquotaPayload.message) {
                    return overquotaPayload.message;
                }
            }

            return raw.trim();
        }

        /**
         * Normalize data payload from WordPress JSON response.
         *
         * @param data
         * @returns {object}
         */
        function getAjaxDataPayload(data)
        {
            if (!data || 'object' !== typeof data) {
                return {};
            }
            if (data.data && 'object' === typeof data.data) {
                return data.data;
            }

            return {};
        }

        /**
         * Extract user-facing message from mixed AJAX response shapes.
         *
         * @param data
         * @param payload
         * @returns {string}
         */
        function getAjaxMessage(data, payload)
        {
            if (payload && 'string' === typeof payload.message && payload.message.trim() !== '') {
                return payload.message;
            }
            if (data && 'string' === typeof data.message && data.message.trim() !== '') {
                return data.message;
            }
            if (data && 'string' === typeof data.data && data.data.trim() !== '') {
                return data.data;
            }

            return 'Unexpected response from server';
        }

        /**
         * Extract raw payload details for dialog rendering.
         *
         * @param data
         * @param payload
         * @returns {*|null}
         */
        function getAjaxRawPayload(data, payload)
        {
            if (payload && payload.raw) {
                return payload.raw;
            }
            if (data && data.raw) {
                return data.raw;
            }

            return null;
        }

        function extractPopApiOverquotaPayload(data)
        {
            var parsed = data;

            if (!parsed || 'object' !== typeof parsed) {
                return null;
            }

            if (parsed.type === 'pop_api_overquota') {
                return parsed;
            }

            if (parsed.data && 'object' === typeof parsed.data && parsed.data.type === 'pop_api_overquota') {
                return parsed.data;
            }

            if (parsed.responseJSON && 'object' === typeof parsed.responseJSON) {
                return extractPopApiOverquotaPayload(parsed.responseJSON);
            }

            var restErrorPayload = normalizeRestStylePopApiOverquotaPayload(parsed);
            if (restErrorPayload) {
                return restErrorPayload;
            }

            return null;
        }

        function normalizeRestStylePopApiOverquotaPayload(parsed)
        {
            if (!parsed || 'object' !== typeof parsed || !parsed.errors || !parsed.error_data) {
                return null;
            }

            var errorCode = '';
            Object.keys(parsed.errors).some(function (candidateCode) {
                if (parsed.error_data[candidateCode] && 'object' === typeof parsed.error_data[candidateCode]) {
                    errorCode = candidateCode;
                    return true;
                }

                return false;
            });

            if (!errorCode) {
                return null;
            }

            var errorData = parsed.error_data[errorCode];
            var reasonCode = errorData.reason_code || '';
            var suggestedAction = errorData.suggested_action || '';
            var messageKey = reasonCode;
            if ('overquota_disabled' === reasonCode && 'settle_now' === suggestedAction) {
                messageKey = 'pending_billing_settlement_required';
            }
            var businessMessages = {
                quota_limit_reached: {
                    title: wc_el_inv_admin.overquota_title_quota_limit || wc_el_inv_admin.overquota_title_default || 'POP API limit reached',
                    message: wc_el_inv_admin.overquota_message_quota_limit || wc_el_inv_admin.overquota_message_default || 'The request could not be completed.'
                },
                overquota_disabled: {
                    title: wc_el_inv_admin.overquota_title_disabled || wc_el_inv_admin.overquota_title_default || 'POP API limit reached',
                    message: wc_el_inv_admin.overquota_message_disabled || wc_el_inv_admin.overquota_message_default || 'The request could not be completed.'
                },
                pending_billing_settlement_required: {
                    title: wc_el_inv_admin.overquota_title_settlement_required || wc_el_inv_admin.overquota_title_default || 'POP API limit reached',
                    message: wc_el_inv_admin.overquota_message_settlement_required || wc_el_inv_admin.overquota_message_default || 'The request could not be completed.'
                },
                overquota_cap_reached: {
                    title: wc_el_inv_admin.overquota_title_cap_reached || wc_el_inv_admin.overquota_title_default || 'POP API limit reached',
                    message: wc_el_inv_admin.overquota_message_cap_reached || wc_el_inv_admin.overquota_message_default || 'The request could not be completed.'
                },
                overquota_no_payment_method: {
                    title: wc_el_inv_admin.overquota_title_payment_required || wc_el_inv_admin.overquota_title_default || 'POP API limit reached',
                    message: wc_el_inv_admin.overquota_message_payment_required || wc_el_inv_admin.overquota_message_default || 'The request could not be completed.'
                },
                overquota_unpaid_older_than_30d: {
                    title: wc_el_inv_admin.overquota_title_unpaid || wc_el_inv_admin.overquota_title_default || 'POP API limit reached',
                    message: wc_el_inv_admin.overquota_message_unpaid || wc_el_inv_admin.overquota_message_default || 'The request could not be completed.'
                },
                overquota_guardrail_unavailable: {
                    title: wc_el_inv_admin.overquota_title_guardrail || wc_el_inv_admin.overquota_title_default || 'POP API limit reached',
                    message: wc_el_inv_admin.overquota_message_guardrail || wc_el_inv_admin.overquota_message_default || 'The request could not be completed.'
                }
            };
            var ctaMap = {
                enable_overquota: {
                    label: wc_el_inv_admin.overquota_cta_open_pop || 'Open POP'
                },
                increase_cap: {
                    label: wc_el_inv_admin.overquota_cta_open_pop || 'Open POP'
                },
                update_payment_method: {
                    label: wc_el_inv_admin.overquota_cta_open_pop || 'Open POP'
                },
                settle_now: {
                    label: wc_el_inv_admin.overquota_cta_open_pop || 'Open POP'
                },
                open_billing: {
                    label: wc_el_inv_admin.overquota_cta_open_pop || 'Open POP'
                },
                retry_later: {
                    label: wc_el_inv_admin.overquota_cta_contact_support || 'Contact support'
                }
            };
            var firstMessage = '';
            if (Array.isArray(parsed.errors[errorCode]) && parsed.errors[errorCode].length) {
                firstMessage = parsed.errors[errorCode][0];
            }

            return {
                type: 'pop_api_overquota',
                status: errorData.status || 429,
                code: errorCode,
                reason_code: reasonCode,
                suggested_action: suggestedAction,
                retryable: 'overquota_guardrail_unavailable' === reasonCode || 'retry_later' === suggestedAction,
                title: (businessMessages[messageKey] && businessMessages[messageKey].title) || wc_el_inv_admin.overquota_title_default || 'POP API limit reached',
                message: (businessMessages[messageKey] && businessMessages[messageKey].message) || firstMessage || wc_el_inv_admin.overquota_message_default || 'The request could not be completed.',
                cta: {
                    label: (ctaMap[suggestedAction] && ctaMap[suggestedAction].label) || 'OK',
                    url: '',
                    step_label: wc_el_inv_admin.overquota_step_label || 'Next step',
                    breadcrumb: ''
                },
                details: errorData
            };
        }

        function showPopApiOverquotaDialog(payload)
        {
            var title = payload && payload.title ? payload.title : 'POP API limit reached';
            var message = payload && payload.message ? payload.message : 'The request could not be completed.';
            var cta = payload && payload.cta && 'object' === typeof payload.cta ? payload.cta : null;
            var confirmText = cta && cta.label ? cta.label : 'OK';
            var icon = payload && payload.retryable ? 'info' : 'warning';
            var stepLabel = cta && cta.step_label ? cta.step_label : 'Next step';
            var dialogHtml = '<div style="margin:0;font-size:15px;line-height:1.55;">' + _.escape(message) + '</div>';

            if (cta && cta.breadcrumb) {
                dialogHtml += '<div style="margin:14px 0 0 0;font-size:13px;line-height:1.45;opacity:0.8;">'
                              + '<strong>' + _.escape(stepLabel) + ':</strong><br>'
                              + _.escape(cta.breadcrumb)
                              + '</div>';
            }

            if (!window.Swal || 'function' !== typeof window.Swal.fire) {
                window.alert(
                    title + "\n\n" + message +
                    (cta && cta.breadcrumb ? "\n\n" + stepLabel + ":\n" + cta.breadcrumb : '')
                );
                if (cta && cta.url) {
                    window.open(cta.url, '_blank', 'noopener,noreferrer');
                }
                return Promise.resolve(true);
            }

            return window.Swal.fire({
                title: title,
                html: dialogHtml,
                icon: icon,
                showCancelButton: !!(cta && cta.url),
                confirmButtonText: confirmText,
                cancelButtonText: 'Close',
                reverseButtons: true,
            }).then(function (result) {
                if (result.isConfirmed && cta && cta.url) {
                    window.open(cta.url, '_blank', 'noopener,noreferrer');
                }

                return true;
            });
        }

        function handlePopApiOverquotaResponse(data)
        {
            var payload = extractPopApiOverquotaPayload(data);
            if (!payload) {
                return false;
            }

            showPopApiOverquotaDialog(payload);

            return true;
        }

        window.wcElInvExtractPopApiOverquotaPayload = extractPopApiOverquotaPayload;
        window.wcElInvShowPopApiOverquotaDialog = showPopApiOverquotaDialog;
        window.wcElInvHandlePopApiOverquotaResponse = handlePopApiOverquotaResponse;

        document.addEventListener('scroll', function () {
            const header = document.querySelector('.wc_el_inv__header');
            if (header) {
                if (window.scrollY > 20) {
                    header.classList.add('is-scrolled');
                } else {
                    header.classList.remove('is-scrolled');
                }
            }
        });

        window.addEventListener('load', function () {

            // Invoice xml data
            var contentInv = $('#store_invoice-description');
            if (contentInv) {
                var titleInv = $(contentInv).prev();
                titleInv.addClass('store_invoice_title');
            }

            var contentInvT = $('#store_invoice_transmitter-description');
            if (contentInvT) {
                var titleInvT = $(contentInvT).prev();
                titleInvT.addClass('store_invoice_transmitter_title');
            }

            // Hide the info by clicking on the edit link
            $('a.edit_address').on('click', function (evt) {
                $('.order_data_column > p').addClass('hide');
            });

            /**
             * Disabled Fields For Fic
             */
            function disabledFieldsForFic()
            {
                var fields = document.querySelectorAll('.wc_el_inv-fic-addon.current-setting_section_numeration .form-table .number_digits input,\n' +
                                                       '.wc_el_inv-fic-addon.current-setting_section_numeration .form-table .reset_numerations input,\n' +
                                                       '.wc_el_inv-fic-addon.current-setting_section_numeration .form-table .suffix_invoice input,\n' +
                                                       '.wc_el_inv-fic-addon.current-setting_section_numeration .form-table .suffix_year input,\n' +
                                                       '.wc_el_inv-fic-addon.current-setting_section_numeration .form-table .suffix_year_format input,\n' +
                                                       '.wc_el_inv-fic-addon.current-setting_section_numeration .form-table .number_next_invoice input,\n' +
                                                       '.wc_el_inv-fic-addon.current-setting_section_numeration .form-table .number_next_receipt input,\n' +
                                                       '.wc_el_inv-fic-addon.current-setting_section_numeration .form-table .numeration_credit_note input,\n' +
                                                       '.wc_el_inv-fic-addon.current-setting_section_numeration .form-table .number_next_credit_note input,\n' +
                                                       '.wc_el_inv-fic-addon.current-setting_section_numeration .form-table .numeration_credit_note_receipt input,\n' +
                                                       '.wc_el_inv-fic-addon.current-setting_section_numeration .form-table .number_next_credit_note_receipt input,\n' +
                                                       '.wc_el_inv-fic-addon.current-setting_section_numeration .form-table #edit_invoice_next_number,\n' +
                                                       '.wc_el_inv-fic-addon.current-setting_section_numeration .form-table #edit_receipt_next_number,\n' +
                                                       '.wc_el_inv-fic-addon.current-setting_section_numeration .form-table #edit_credit_note_next_number,\n' +
                                                       '.wc_el_inv-fic-addon.current-setting_section_numeration .form-table #edit_credit_note_receipt_next_number');
                if (fields) {
                    fields.forEach(function (field) {
                        field.setAttribute('disabled', 'disabled');
                        field.setAttribute('readonly', 'readonly');
                    })
                }
            }

            activeSubMenu();
            editInvoiceNumber();
            editReceiptNumber();
            editCreditNoteNumber();
            editOrderInvoiceNumber();
            editRefundInvoiceNumber();
            filterByDate();
            refundItemControl();
            invoiceItemControl();
            searchOrderByID();
            bulkMarkActions();
            choiceType();
            endPointActions();
            reverseChargeEdit();
            advancedNav();
            disabledFieldsForFic();
            rcNatureSelect();

            // Remove refund ajax complete action
            $(document).ajaxComplete(function () {
                var refundAmount = document.querySelector('#woocommerce-order-items .inside input#refund_amount');
                var mark = document.querySelector('.wc_el_inv__general-order .actions .mark_trigger');

                if (!refundAmount || !mark) {
                    return;
                }

                if (!refundAmount.hasAttribute('readonly') && mark.classList.contains('mark_as_sent')) {
                    refundAmount.setAttribute('readonly', true);
                    refundAmount.insertAdjacentHTML(
                        'afterend',
                        '<p id="readonly-info">' + wc_el_inv_admin.refund_amount_read_only_info_text + '</p>'
                    )
                } else if (refundAmount.hasAttribute('readonly') && !mark.classList.contains('mark_as_sent')) {
                    refundAmount.removeAttribute('readonly');
                }
            });
        });

        // Disable clicks
        document.body.classList.add('disable-clicks');
        document.addEventListener('DOMContentLoaded', function () {
            markInvoice();
            document.body.classList.remove('disable-clicks');
        });

        /**
         * Invoice API scrips
         *
         * 1. Create XML invoice
         * 2. Notifications invoice
         * 3. Preserve invoice
         * 4. Create UBL(XML) invoice
         */
        document.addEventListener('DOMContentLoaded', function () {
            /**
             * SDI via POP Actions - create
             */
            document.querySelectorAll('.sdi_pop_actions a.api-action.create').forEach(function (btn) {
                btn.addEventListener('click', function (e) {
                    e.preventDefault();
                    e.stopImmediatePropagation();

                    const apiAction = btn.closest('.sdi_pop_actions').querySelector('a.api-action');
                    if (!apiAction) {
                        return;
                    }

                    const provider = apiAction.dataset.provider;
                    const id = apiAction.dataset.id;
                    const uuid = apiAction.dataset.uuid;
                    const documentType = apiAction.dataset.documentType || 'shop_order';

                    this.setAttribute('disabled', 'disabled');

                    let loader = document.getElementById('loading-overlay');
                    if (!loader) {
                        loader = document.createElement('span');
                        loader.id = 'loading-overlay';
                        document.body.appendChild(loader);
                    }
                    loader.classList.remove('hidden');
                    loader.classList.add('loading');

                    fetch(ajaxurl, {
                        method: 'POST',
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        body: new URLSearchParams({
                            action: 'createAndSendInvoice',
                            nonce: wc_el_inv_admin.ajax_nonce,
                            method: 'ajax',
                            provider: provider,
                            id: id,
                            uuid: uuid,
                            document_type: documentType
                        })
                    })
                        .then(parseAjaxJsonOrThrow)
                        .then(data => {
                            if (handlePopApiOverquotaResponse(data)) {
                                return;
                            }
                            const payload = getAjaxDataPayload(data);
                            const message = getAjaxMessage(data, payload);
                            const raw = getAjaxRawPayload(data, payload);
                            if ('dev' === wc_el_inv_admin.mode) {
                                console.log('Response:', data);
                            }
                            showDialogAndMaybeReload(message, raw, data.success ? 'success' : 'error', 6000);
                        })
                        .catch(error => {
                            console.error('AJAX error:', error);
                            showDialogAndMaybeReload(error.message, null, 'error');
                        }).finally(() => {
                        this.removeAttribute('disabled')
                        loader.classList.remove('loading');
                        loader.classList.add('hidden');
                    });
                });
            });

            /**
             * SDI via POP Actions - notifications
             */
            document.querySelectorAll('.sdi_pop_actions a.api-action.notifications').forEach(function (btn) {
                btn.addEventListener('click', function (e) {
                    e.preventDefault();
                    e.stopImmediatePropagation();

                    const apiAction = btn.closest('.sdi_pop_actions').querySelector('a.api-action');
                    if (!apiAction) {
                        return;
                    }

                    const provider = apiAction.dataset.provider;
                    const id = apiAction.dataset.id;
                    const uuid = apiAction.dataset.uuid;
                    const documentType = apiAction.dataset.documentType || 'shop_order';

                    let loader = document.getElementById('loading-overlay');
                    if (!loader) {
                        loader = document.createElement('span');
                        loader.id = 'loading-overlay';
                        document.body.appendChild(loader);
                    }
                    loader.classList.remove('hidden');
                    loader.classList.add('loading');

                    fetch(ajaxurl, {
                        method: 'POST',
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        body: new URLSearchParams({
                            action: 'notificationsInvoice',
                            nonce: wc_el_inv_admin.ajax_nonce,
                            method: 'ajax',
                            provider: provider,
                            id: id,
                            uuid: uuid,
                            document_type: documentType
                        })
                    })
                        .then(parseAjaxJsonOrThrow)
                        .then(data => {
                            if (handlePopApiOverquotaResponse(data)) {
                                return;
                            }
                            const payload = getAjaxDataPayload(data);
                            const message = getAjaxMessage(data, payload);
                            if ('dev' === wc_el_inv_admin.mode) {
                                console.log('Response:', data);
                            }
                            showDialogAndMaybeReload(message, null, data.success ? 'notify' : 'error');
                        })
                        .catch(error => {
                            console.error('AJAX error:', error);
                            showDialogAndMaybeReload(error.message, null, 'error');
                        }).finally(() => {
                        loader.classList.remove('loading');
                        loader.classList.add('hidden');
                    });
                });
            });

            /**
             * SDI via POP Actions - preserve
             */
            document.querySelectorAll('.sdi_pop_actions a.api-action.preserve').forEach(function (btn) {
                btn.addEventListener('click', function (e) {
                    e.preventDefault();
                    e.stopImmediatePropagation();

                    const apiAction = btn.closest('.sdi_pop_actions').querySelector('a.api-action');
                    if (!apiAction) {
                        return;
                    }

                    const provider = apiAction.dataset.provider;
                    const id = apiAction.dataset.id;
                    const uuid = apiAction.dataset.uuid;
                    const documentType = apiAction.dataset.documentType || 'shop_order';

                    let loader = document.getElementById('loading-overlay');
                    if (!loader) {
                        loader = document.createElement('span');
                        loader.id = 'loading-overlay';
                        document.body.appendChild(loader);
                    }
                    loader.classList.remove('hidden');
                    loader.classList.add('loading');

                    fetch(ajaxurl, {
                        method: 'POST',
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        body: new URLSearchParams({
                            action: 'preserveInvoice',
                            nonce: wc_el_inv_admin.ajax_nonce,
                            method: 'ajax',
                            provider: provider,
                            id: id,
                            uuid: uuid,
                            document_type: documentType
                        })
                    })
                        .then(parseAjaxJsonOrThrow)
                        .then(data => {
                            if (handlePopApiOverquotaResponse(data)) {
                                return;
                            }
                            const payload = getAjaxDataPayload(data);
                            const message = getAjaxMessage(data, payload);
                            if ('dev' === wc_el_inv_admin.mode) {
                                console.log('Response:', data);
                            }
                            showDialogAndMaybeReload(message, null, data.success ? 'preserve' : 'error');
                        })
                        .catch(error => {
                            console.error('AJAX error:', error);
                            showDialogAndMaybeReload(error.message, null, 'error');
                        }).finally(() => {
                        loader.classList.remove('loading');
                        loader.classList.add('hidden');
                    });
                });
            });

            /**
             * PEPPOL via POP Actions - create
             */
            document.querySelectorAll('.peppol_pop_actions a.api-action.create').forEach(function (btn) {
                btn.addEventListener('click', function (e) {
                    e.preventDefault();
                    e.stopImmediatePropagation();

                    const apiAction = btn.closest('.peppol_pop_actions').querySelector('a.api-action');
                    if (!apiAction) {
                        return;
                    }

                    const provider = apiAction.dataset.provider;
                    const id = apiAction.dataset.id;
                    const uuid = apiAction.dataset.uuid;
                    const documentType = apiAction.dataset.documentType || 'shop_order';

                    this.setAttribute('disabled', 'disabled');

                    let loader = document.getElementById('loading-overlay');
                    if (!loader) {
                        loader = document.createElement('span');
                        loader.id = 'loading-overlay';
                        document.body.appendChild(loader);
                    }
                    loader.classList.remove('hidden');
                    loader.classList.add('loading');

                    fetch(ajaxurl, {
                        method: 'POST',
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        body: new URLSearchParams({
                            action: 'createAndSendUblInvoice',
                            nonce: wc_el_inv_admin.ajax_nonce,
                            method: 'ajax',
                            provider: provider,
                            id: id,
                            uuid: uuid,
                            document_type: documentType
                        })
                    })
                        .then(parseAjaxJsonOrThrow)
                        .then(data => {
                            if (handlePopApiOverquotaResponse(data)) {
                                return;
                            }
                            const payload = getAjaxDataPayload(data);
                            const message = getAjaxMessage(data, payload);
                            const raw = getAjaxRawPayload(data, payload);
                            if ('dev' === wc_el_inv_admin.mode) {
                                console.log('Response:', data);
                            }
                            showDialogAndMaybeReload(message, raw, data.success ? 'success' : 'error', 6000);
                        })
                        .catch(error => {
                            console.error('AJAX error:', error);
                            showDialogAndMaybeReload(error.message, null, 'error');
                        }).finally(() => {
                        this.removeAttribute('disabled')
                        loader.classList.remove('loading');
                        loader.classList.add('hidden');
                    });
                });
            });

            /**
             * PEPPOL via POP Actions - state
             */
            document.querySelectorAll('.peppol_pop_actions a.api-action.state').forEach(function (btn) {
                btn.addEventListener('click', function (e) {
                    e.preventDefault();
                    e.stopImmediatePropagation();

                    const apiAction = btn.closest('.peppol_pop_actions').querySelector('a.api-action');
                    if (!apiAction) {
                        return;
                    }

                    const provider = apiAction.dataset.provider;
                    const id = apiAction.dataset.id;
                    const uuid = apiAction.dataset.uuid;
                    const type = apiAction.dataset.type || 'invoice';

                    let loader = document.getElementById('loading-overlay');
                    if (!loader) {
                        loader = document.createElement('span');
                        loader.id = 'loading-overlay';
                        document.body.appendChild(loader);
                    }
                    loader.classList.remove('hidden');
                    loader.classList.add('loading');

                    fetch(ajaxurl, {
                        method: 'POST',
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        body: new URLSearchParams({
                            action: 'stateInvoice',
                            nonce: wc_el_inv_admin.ajax_nonce,
                            method: 'ajax',
                            provider: provider,
                            id: id,
                            uuid: uuid,
                            type: type
                        })
                    })
                        .then(parseAjaxJsonOrThrow)
                        .then(data => {
                            if (handlePopApiOverquotaResponse(data)) {
                                return;
                            }
                            const payload = getAjaxDataPayload(data);
                            const message = getAjaxMessage(data, payload);
                            if ('dev' === wc_el_inv_admin.mode) {
                                console.log('Response:', data);
                            }
                            showDialogAndMaybeReload(message, null, data.success ? 'success' : 'notify');
                        })
                        .catch(error => {
                            console.error('AJAX error:', error);
                            showDialogAndMaybeReload(error.message, null, 'error');
                        }).finally(() => {
                        loader.classList.remove('loading');
                        loader.classList.add('hidden');
                    });
                });
            });

            /**
             * KSeF via POP Actions - create
             */
            document.querySelectorAll('.ksef_pop_actions a.api-action.create').forEach(function (btn) {
                btn.addEventListener('click', function (e) {
                    e.preventDefault();
                    e.stopImmediatePropagation();

                    const apiAction = btn.closest('.ksef_pop_actions').querySelector('a.api-action');
                    if (!apiAction) {
                        return;
                    }

                    const provider = apiAction.dataset.provider;
                    const id = apiAction.dataset.id;
                    const uuid = apiAction.dataset.uuid;
                    const documentType = apiAction.dataset.documentType || 'shop_order';

                    this.setAttribute('disabled', 'disabled');

                    let loader = document.getElementById('loading-overlay');
                    if (!loader) {
                        loader = document.createElement('span');
                        loader.id = 'loading-overlay';
                        document.body.appendChild(loader);
                    }
                    loader.classList.remove('hidden');
                    loader.classList.add('loading');

                    fetch(ajaxurl, {
                        method: 'POST',
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        body: new URLSearchParams({
                            action: 'createAndSendKsefInvoice',
                            nonce: wc_el_inv_admin.ajax_nonce,
                            method: 'ajax',
                            provider: provider,
                            id: id,
                            uuid: uuid,
                            document_type: documentType
                        })
                    })
                        .then(parseAjaxJsonOrThrow)
                        .then(data => {
                            if (handlePopApiOverquotaResponse(data)) {
                                return;
                            }
                            const payload = getAjaxDataPayload(data);
                            const message = getAjaxMessage(data, payload);
                            const raw = getAjaxRawPayload(data, payload);
                            if ('dev' === wc_el_inv_admin.mode) {
                                console.log('Response:', data);
                            }
                            showDialogAndMaybeReload(message, raw, data.success ? 'success' : 'error', 6000);
                        })
                        .catch(error => {
                            console.error('AJAX error:', error);
                            showDialogAndMaybeReload(error.message, null, 'error');
                        }).finally(() => {
                        this.removeAttribute('disabled')
                        loader.classList.remove('loading');
                        loader.classList.add('hidden');
                    });
                });
            });

            /**
             * KSeF via POP Actions - state
             */
            document.querySelectorAll('.ksef_pop_actions a.api-action.state').forEach(function (btn) {
                btn.addEventListener('click', function (e) {
                    e.preventDefault();
                    e.stopImmediatePropagation();

                    const apiAction = btn.closest('.ksef_pop_actions').querySelector('a.api-action');
                    if (!apiAction) {
                        return;
                    }

                    const provider = apiAction.dataset.provider;
                    const id = apiAction.dataset.id;
                    const uuid = apiAction.dataset.uuid;
                    const type = apiAction.dataset.type || 'invoice';

                    let loader = document.getElementById('loading-overlay');
                    if (!loader) {
                        loader = document.createElement('span');
                        loader.id = 'loading-overlay';
                        document.body.appendChild(loader);
                    }
                    loader.classList.remove('hidden');
                    loader.classList.add('loading');

                    fetch(ajaxurl, {
                        method: 'POST',
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        body: new URLSearchParams({
                            action: 'ksefStateInvoice',
                            nonce: wc_el_inv_admin.ajax_nonce,
                            method: 'ajax',
                            provider: provider,
                            id: id,
                            uuid: uuid,
                            type: type
                        })
                    })
                        .then(parseAjaxJsonOrThrow)
                        .then(data => {
                            if (handlePopApiOverquotaResponse(data)) {
                                return;
                            }
                            const payload = getAjaxDataPayload(data);
                            const message = getAjaxMessage(data, payload);
                            if ('dev' === wc_el_inv_admin.mode) {
                                console.log('Response:', data);
                            }
                            showDialogAndMaybeReload(message, null, data.success ? 'success' : 'notify');
                        })
                        .catch(error => {
                            console.error('AJAX error:', error);
                            showDialogAndMaybeReload(error.message, null, 'error');
                        }).finally(() => {
                        loader.classList.remove('loading');
                        loader.classList.add('hidden');
                    });
                });
            });

            /**
             * Zoho via POP Actions - create
             */
            document.querySelectorAll('.zoho_pop_actions a.api-action.create').forEach(function (btn) {
                btn.addEventListener('click', function (e) {
                    e.preventDefault();
                    e.stopImmediatePropagation();

                    if (this.hasAttribute('disabled') || this.classList.contains('disabled')) {
                        return;
                    }

                    const apiAction = btn.closest('.zoho_pop_actions').querySelector('a.api-action');
                    if (!apiAction) {
                        return;
                    }

                    const provider = apiAction.dataset.provider;
                    const id = apiAction.dataset.id;
                    const documentType = apiAction.dataset.documentType || 'shop_order';

                    this.setAttribute('disabled', 'disabled');

                    let loader = document.getElementById('loading-overlay');
                    if (!loader) {
                        loader = document.createElement('span');
                        loader.id = 'loading-overlay';
                        document.body.appendChild(loader);
                    }
                    loader.classList.remove('hidden');
                    loader.classList.add('loading');

                    fetch(ajaxurl, {
                        method: 'POST',
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        body: new URLSearchParams({
                            action: 'createAndSendZohoInvoice',
                            nonce: wc_el_inv_admin.ajax_nonce,
                            method: 'ajax',
                            provider: provider,
                            id: id,
                            document_type: documentType
                        })
                    })
                        .then(parseAjaxJsonOrThrow)
                        .then(data => {
                            if (handlePopApiOverquotaResponse(data)) {
                                return;
                            }
                            const payload = getAjaxDataPayload(data);
                            const message = getAjaxMessage(data, payload);
                            const raw = getAjaxRawPayload(data, payload);
                            if ('dev' === wc_el_inv_admin.mode) {
                                console.log('Response:', data);
                            }
                            showDialogAndMaybeReload(message, raw, data.success ? 'success' : 'error', 6000);
                        })
                        .catch(error => {
                            console.error('AJAX error:', error);
                            showDialogAndMaybeReload(error.message, null, 'error');
                        }).finally(() => {
                        this.removeAttribute('disabled')
                        loader.classList.remove('loading');
                        loader.classList.add('hidden');
                    });
                });
            });

            /**
             * Native timeout pending actions - confirm UUID
             */
            document.querySelectorAll('.sdi_pop_actions a.api-action.confirm-timeout-uuid, .peppol_pop_actions a.api-action.confirm-timeout-uuid, .ksef_pop_actions a.api-action.confirm-timeout-uuid').forEach(function (btn) {
                btn.addEventListener('click', function (e) {
                    e.preventDefault();
                    e.stopImmediatePropagation();

                    const provider = btn.dataset.provider;
                    const id = btn.dataset.id;
                    const channel = btn.dataset.channel;
                    const documentType = btn.dataset.documentType || 'shop_order';
                    const wrapper = btn.closest('.sdi_pop_actions, .peppol_pop_actions, .ksef_pop_actions');
                    const uuidInput = wrapper ? wrapper.querySelector('.native-timeout-uuid-input') : null;
                    const uuid = uuidInput ? uuidInput.value.trim() : '';

                    if (!uuid) {
                        showDialogAndMaybeReload(wc_el_inv_admin.timeout_uuid_required, null, 'error');
                        return;
                    }

                    this.setAttribute('disabled', 'disabled');

                    let loader = document.getElementById('loading-overlay');
                    if (!loader) {
                        loader = document.createElement('span');
                        loader.id = 'loading-overlay';
                        document.body.appendChild(loader);
                    }
                    loader.classList.remove('hidden');
                    loader.classList.add('loading');

                    fetch(ajaxurl, {
                        method: 'POST',
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        body: new URLSearchParams({
                            action: 'confirmNativeSendWithUuid',
                            nonce: wc_el_inv_admin.ajax_nonce,
                            provider: provider,
                            id: id,
                            channel: channel,
                            document_type: documentType,
                            uuid: uuid
                        })
                    })
                        .then(parseAjaxJsonOrThrow)
                        .then(data => {
                            if (handlePopApiOverquotaResponse(data)) {
                                return;
                            }
                            const payload = getAjaxDataPayload(data);
                            const message = getAjaxMessage(data, payload);
                            const raw = getAjaxRawPayload(data, payload);
                            if ('dev' === wc_el_inv_admin.mode) {
                                console.log('Response:', data);
                            }
                            showDialogAndMaybeReload(message, raw, data.success ? 'success' : 'error', 6000);
                        })
                        .catch(error => {
                            console.error('AJAX error:', error);
                            showDialogAndMaybeReload(error.message, null, 'error');
                        }).finally(() => {
                        this.removeAttribute('disabled');
                        loader.classList.remove('loading');
                        loader.classList.add('hidden');
                    });
                });
            });

            /**
             * Native timeout pending actions - cancel timeout
             */
            document.querySelectorAll('.sdi_pop_actions a.api-action.cancel-timeout-pending, .peppol_pop_actions a.api-action.cancel-timeout-pending, .ksef_pop_actions a.api-action.cancel-timeout-pending, .zoho_pop_actions a.api-action.cancel-timeout-pending').forEach(function (btn) {
                btn.addEventListener('click', function (e) {
                    e.preventDefault();
                    e.stopImmediatePropagation();

                    confirmDialog(wc_el_inv_admin.timeout_cancel_confirm).then(function (confirmed) {
                        if (!confirmed) {
                            return;
                        }

                        const provider = btn.dataset.provider;
                        const id = btn.dataset.id;
                        const channel = btn.dataset.channel;
                        const documentType = btn.dataset.documentType || 'shop_order';

                        btn.setAttribute('disabled', 'disabled');

                        let loader = document.getElementById('loading-overlay');
                        if (!loader) {
                            loader = document.createElement('span');
                            loader.id = 'loading-overlay';
                            document.body.appendChild(loader);
                        }
                        loader.classList.remove('hidden');
                        loader.classList.add('loading');

                        fetch(ajaxurl, {
                            method: 'POST',
                            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                            body: new URLSearchParams({
                                action: 'cancelNativeTimeoutPending',
                                nonce: wc_el_inv_admin.ajax_nonce,
                                provider: provider,
                                id: id,
                                channel: channel,
                                document_type: documentType
                            })
                        })
                            .then(parseAjaxJsonOrThrow)
                            .then(data => {
                                if (handlePopApiOverquotaResponse(data)) {
                                    return;
                                }
                                const payload = getAjaxDataPayload(data);
                                const message = getAjaxMessage(data, payload);
                                const raw = getAjaxRawPayload(data, payload);
                                if ('dev' === wc_el_inv_admin.mode) {
                                    console.log('Response:', data);
                                }
                                showDialogAndMaybeReload(message, raw, data.success ? 'success' : 'error', 6000);
                            })
                            .catch(error => {
                                console.error('AJAX error:', error);
                                showDialogAndMaybeReload(error.message, null, 'error');
                            }).finally(() => {
                            btn.removeAttribute('disabled');
                            loader.classList.remove('loading');
                            loader.classList.add('hidden');
                        });
                    });
                });
            });

        });

        /**
         * Webhook
         */
        document.addEventListener('DOMContentLoaded', function () {
            document.querySelectorAll('.pop_to_webhook_actions a.api-action.send-webhook').forEach(function (btn) {
                btn.addEventListener('click', function (e) {
                    e.preventDefault();
                    e.stopImmediatePropagation();

                    const apiAction = btn.closest('.pop_to_webhook_actions').querySelector('a.api-action');
                    if (!apiAction) {
                        return;
                    }

                    const provider = apiAction.dataset.provider;
                    const id = apiAction.dataset.id;

                    this.setAttribute('disabled', 'disabled');

                    let loader = document.getElementById('loading-overlay');
                    if (!loader) {
                        loader = document.createElement('span');
                        loader.id = 'loading-overlay';
                        document.body.appendChild(loader);
                    }
                    loader.classList.remove('hidden');
                    loader.classList.add('loading');

                    fetch(ajaxurl, {
                        method: 'POST',
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'},
                        body: new URLSearchParams({
                            action: 'sendWebhook',
                            nonce: wc_el_inv_admin.ajax_nonce,
                            method: 'ajax',
                            provider: provider,
                            id: id,
                        })
                    })
                        .then(parseAjaxJsonOrThrow)
                        .then(data => {
                            if (handlePopApiOverquotaResponse(data)) {
                                return;
                            }
                            const payload = getAjaxDataPayload(data);
                            const message = getAjaxMessage(data, payload);
                            const raw = getAjaxRawPayload(data, payload);
                            if ('dev' === wc_el_inv_admin.mode) {
                                console.log('Response:', data);
                            }
                            showDialogAndMaybeReload(message, raw, data.success ? 'success' : 'error', 6000);
                        })
                        .catch(error => {
                            console.error('AJAX error:', error);
                            showDialogAndMaybeReload(error.message, null, 'error');
                        }).finally(() => {
                        this.removeAttribute('disabled');
                        loader.classList.remove('loading');
                        loader.classList.add('hidden');
                    });
                });
            });
        });

        /**
         * Ajax Download
         *
         * - saveDownloadState
         * - getDownloadState
         * - clearDownloadState
         * - processBatch
         */
        const batchSize = 5;
        let currentOffset = 0;
        let totalFiles = wc_el_inv_admin.count_filtered;

        function saveDownloadState(offset)
        {
            localStorage.setItem('downloadOffset', offset);
            localStorage.setItem('downloadStarted', '1');
        }

        function getDownloadState()
        {
            return {
                offset: parseInt(localStorage.getItem('downloadOffset') || '0'),
                started: localStorage.getItem('downloadStarted') === '1'
            };
        }

        function clearDownloadState()
        {
            localStorage.removeItem('downloadOffset');
            localStorage.removeItem('downloadStarted');
        }

        function processBatch()
        {
            if (currentOffset >= totalFiles) {
                clearDownloadState();
                return;
            }

            $.ajax({
                url: wc_el_inv_admin.ajax_url,
                method: 'POST',
                data: {
                    action: 'processFileBatch',
                    nonce: wc_el_inv_admin.ajax_nonce,
                    offset: currentOffset,
                    limit: batchSize,
                },
                success: function (response) {
                    if (response.success) {
                        if (response.data.total) {
                            totalFiles = response.data.total;
                        }

                        currentOffset += batchSize;
                        if (currentOffset > totalFiles) {
                            currentOffset = totalFiles;
                        }

                        saveDownloadState(currentOffset);

                        $('.pop-progress span').remove();

                        let percent = Math.min((currentOffset / totalFiles) * 100, 100);
                        $('#progress-bar').css('width', percent + '%').text(Math.round(percent) + '%');

                        if (!response.data.done) {
                            processBatch();
                        } else {
                            clearDownloadState();
                            $(this).removeClass('disabled');
                            $('#progress-bar').css('width', '100%').text('100%');
                            window.location.href = response.data.zip_url;
                        }
                    } else {
                        notifyDialog("Errore: " + response.data.message, {icon: 'error', timer: 2600});
                    }
                }
            });
        }

        $(document).ready(function () {
            const state = getDownloadState();

            if (state.started) {
                currentOffset = state.offset;
                processBatch();
            }

            $('#start-download-btn').on('click', function (evt) {
                $(this).addClass('disabled');
                evt.preventDefault();
                evt.stopImmediatePropagation();
                $('.pop-progress span').text(wc_el_inv_admin.start_download);

                currentOffset = 0;
                saveDownloadState(currentOffset);
                $('#progress-bar').css('width', '0%');
                processBatch();
            });
        });

        /**
         * Change api key
         */
        let triggerChange = document.getElementById('change_api_key');
        if (triggerChange) {
            triggerChange.addEventListener('click', () => {
                let inputKeyWrap = document.querySelector('.wc_el_inv-form table.form-table .license_key');
                if (!inputKeyWrap) {
                    return;
                }

                // Toggle classe 'hidden'
                let isHidden = inputKeyWrap.classList.contains('hidden');
                inputKeyWrap.classList.toggle('hidden');

                // Recupera l'input
                let input = inputKeyWrap.querySelector('td label[for="wc_el_inv-settings-license_key"] input[type="text"]');
                if (!input) {
                    return;
                }

                // Toggle readonly
                if (isHidden) {
                    input.removeAttribute('readonly');
                } else {
                    input.setAttribute('readonly', 'readonly');
                }

                // Aggiungi bottone se non esiste già
                if (!document.getElementById('save_license_key')) {
                    createButtonSave('save_license_key', input, 'afterend');
                }
            });
        }

    }(window._, window.jQuery, window.wc_el_inv_admin)
);
