<a class="btn btn-danger d-none" id="batch-delete-selected-btn">
    <svg class="icon">
        <use xlink:href="#delete"/>
    </svg>
    {{ 'Delete Selected'|trans }}</a>

<script>
    document.addEventListener("DOMContentLoaded", function() {
        const deleteBtn = document.getElementById('batch-delete-selected-btn');
        const masterCheckbox = document.querySelector('input.batch-delete-master-checkbox');
        const checkboxes = document.querySelectorAll('input.batch-delete-checkbox');

        masterCheckbox.addEventListener('change', toggleDeleteBtn);
        checkboxes.forEach((cb) => {
            cb.addEventListener('change', toggleDeleteBtn)
        });

        function toggleDeleteBtn() {
            const empty = [].filter.call(checkboxes, function (cb) {
                return !cb.checked
            });
            if (empty.length !== checkboxes.length) {
                deleteBtn.classList.remove('d-none');
                deleteBtn.classList.add('d-inline-flex');
                return;
            }
            deleteBtn.classList.remove('d-inline-flex');
            deleteBtn.classList.add('d-none');
        }

        deleteBtn.addEventListener('click', function() {
            const checkedBoxes = document.querySelectorAll('input.batch-delete-checkbox:checked');
            if (checkedBoxes.length) {
                Modals.create({
                    type: 'danger',
                    title: "{{ 'Are you sure?'|trans }}",
                    content: "{{ 'Are you sure you want to delete the selected items?'|trans }}",
                    confirmCallback: () => {
                        const ids = Array.from(checkedBoxes).map(function(checkbox) {
                            return checkbox.getAttribute("data-item-id");
                        });
                        FOSSBilling.api.admin.post('{{ action }}', { ids: ids },
                            (result) => {
                                window.location.reload();
                            });
                    }
                });
            } else {
                Modals.create({
                    type: 'small',
                    title: "{{ 'No items selected'|trans }}",
                    content: "{{ 'You need to select at least one item to delete'|trans }}",
                });
            }
        });

        masterCheckbox.addEventListener('click', function() {
            checkboxes.forEach(function(checkbox) {
                checkbox.checked = masterCheckbox.checked;
            });
        });
    });
</script>
