<script>
document.addEventListener('DOMContentLoaded', function () {
    document.getElementById('glPrintReport')?.addEventListener('click', function () {
        window.print();
    });

    initGlMultiFilterPickers();
    initGlDimensionPicker();
    initGlEmailModal();
});

function initGlMultiFilterPickers() {
    document.querySelectorAll('.pl-multi-filter-picker').forEach(function (picker) {
        var selected = new Set();
        var labelMap = {};

        try {
            JSON.parse(picker.dataset.selected || '[]').forEach(function (value) {
                selected.add(String(value));
            });
            labelMap = JSON.parse(picker.dataset.labels || '{}');
        } catch (error) {
            selected = new Set();
            labelMap = {};
        }

        var toggleBtn = picker.querySelector('[data-multi-filter-toggle]');
        var menu = picker.querySelector('[data-multi-filter-menu]');
        var searchInput = picker.querySelector('[data-multi-filter-search]');
        var emptyEl = picker.querySelector('[data-multi-filter-empty]');
        var labelEl = picker.querySelector('[data-multi-filter-label]');
        var inputsEl = picker.querySelector('[data-multi-filter-inputs]');
        var clearBtn = picker.querySelector('[data-multi-filter-clear]');
        var emptyLabel = picker.dataset.emptyLabel || 'All';

        function syncInputs() {
            if (!inputsEl) {
                return;
            }

            var inputName = picker.dataset.inputName || 'items[]';
            inputsEl.innerHTML = '';
            Array.from(selected).sort().forEach(function (value) {
                var input = document.createElement('input');
                input.type = 'hidden';
                input.name = inputName;
                input.value = value;
                inputsEl.appendChild(input);
            });
        }

        function syncLabel() {
            if (!labelEl) {
                return;
            }

            if (selected.size === 0) {
                labelEl.textContent = emptyLabel;
                return;
            }

            if (selected.size === 1) {
                var only = Array.from(selected)[0];
                labelEl.textContent = labelMap[only] || only;
                return;
            }

            labelEl.textContent = selected.size + ' selected';
        }

        function syncCheckboxes() {
            picker.querySelectorAll('[data-multi-filter-checkbox]').forEach(function (checkbox) {
                checkbox.checked = selected.has(checkbox.value);
            });
        }

        function filterOptions() {
            var term = (searchInput?.value || '').trim().toLowerCase();
            var visible = 0;

            picker.querySelectorAll('[data-multi-filter-option]').forEach(function (option) {
                var label = (option.dataset.label || option.textContent || '').toLowerCase();
                var show = !term || label.indexOf(term) !== -1;
                option.classList.toggle('d-none', !show);
                if (show) {
                    visible++;
                }
            });

            emptyEl?.classList.toggle('d-none', visible > 0);
        }

        function closeMenu() {
            menu?.classList.add('d-none');
            toggleBtn?.setAttribute('aria-expanded', 'false');
        }

        toggleBtn?.addEventListener('click', function () {
            var isOpen = !menu?.classList.contains('d-none');
            if (isOpen) {
                closeMenu();
                return;
            }

            menu?.classList.remove('d-none');
            toggleBtn.setAttribute('aria-expanded', 'true');
            searchInput?.focus();
            filterOptions();
        });

        document.addEventListener('click', function (event) {
            if (!picker.contains(event.target)) {
                closeMenu();
            }
        });

        picker.addEventListener('change', function (event) {
            var checkbox = event.target.closest('[data-multi-filter-checkbox]');
            if (!checkbox) {
                return;
            }

            if (checkbox.checked) {
                selected.add(checkbox.value);
            } else {
                selected.delete(checkbox.value);
            }

            syncInputs();
            syncLabel();
        });

        searchInput?.addEventListener('input', filterOptions);

        clearBtn?.addEventListener('click', function () {
            selected.clear();
            syncInputs();
            syncLabel();
            syncCheckboxes();
            if (searchInput) {
                searchInput.value = '';
            }
            filterOptions();
        });

        syncInputs();
        syncLabel();
        syncCheckboxes();
        filterOptions();
    });
}

function initGlDimensionPicker() {
    var picker = document.getElementById('glDimensionPicker');
    if (!picker) {
        return;
    }

    var tree = [];
    var selected = new Set();

    try {
        tree = JSON.parse(picker.dataset.tree || '[]');
        JSON.parse(picker.dataset.selected || '[]').forEach(function (id) {
            selected.add(String(id));
        });
    } catch (error) {
        tree = [];
    }

    var toggleBtn = document.getElementById('glDimensionPickerToggle');
    var menu = document.getElementById('glDimensionPickerMenu');
    var treeEl = document.getElementById('glDimensionPickerTree');
    var searchInput = document.getElementById('glDimensionPickerSearch');
    var emptyEl = document.getElementById('glDimensionPickerEmpty');
    var labelEl = document.getElementById('glDimensionPickerLabel');
    var inputsEl = document.getElementById('glDimensionPickerInputs');
    var clearBtn = document.getElementById('glDimensionPickerClear');
    var expanded = new Set();
    var nameMap = {};

    function walk(nodes, fn) {
        nodes.forEach(function (node) {
            fn(node);
            if (node.children && node.children.length) {
                walk(node.children, fn);
            }
        });
    }

    walk(tree, function (node) {
        if (node.selectable) {
            nameMap[String(node.id)] = node.name;
        } else if (node.children && node.children.length) {
            expanded.add(String(node.id));
        }
    });

    function syncInputs() {
        if (!inputsEl) {
            return;
        }

        inputsEl.innerHTML = '';
        Array.from(selected).sort(function (a, b) {
            return Number(a) - Number(b);
        }).forEach(function (id) {
            var input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'dimension_value_ids[]';
            input.value = id;
            inputsEl.appendChild(input);
        });
    }

    function syncLabel() {
        if (!labelEl) {
            return;
        }

        if (selected.size === 0) {
            labelEl.textContent = 'All dimensions';
            return;
        }

        if (selected.size === 1) {
            labelEl.textContent = nameMap[Array.from(selected)[0]] || '1 dimension selected';
            return;
        }

        labelEl.textContent = selected.size + ' dimensions selected';
    }

    function nodeMatches(node, term) {
        if (!term) {
            return true;
        }

        var haystack = ((node.name || '') + ' ' + (node.code || '')).toLowerCase();
        return haystack.indexOf(term) !== -1;
    }

    function subtreeMatches(node, term) {
        if (!term) {
            return true;
        }

        if (nodeMatches(node, term)) {
            return true;
        }

        return (node.children || []).some(function (child) {
            return subtreeMatches(child, term);
        });
    }

    function renderNodes(nodes, depth) {
        return nodes.map(function (node) {
            var id = String(node.id);
            var term = (searchInput?.value || '').trim().toLowerCase();
            var hasChildren = !!(node.children && node.children.length);

            if (term && !subtreeMatches(node, term)) {
                return '';
            }

            if (!node.selectable) {
                var groupChildren = renderNodes(node.children || [], depth + 1);
                if (!groupChildren) {
                    return '';
                }

                return `
                    <div class="pl-dimension-picker-item" style="padding-left:${depth * 16}px">
                        <button type="button" class="pl-dimension-picker-toggle-btn ${hasChildren ? '' : 'is-hidden'}" data-dimension-expand="${id}" aria-label="Expand">
                            <i class="bi ${expanded.has(id) ? 'bi-chevron-down' : 'bi-chevron-right'}" style="font-size:11px"></i>
                        </button>
                        <div class="pl-dimension-picker-group">${node.name}</div>
                    </div>
                    <div class="${expanded.has(id) ? '' : 'd-none'}" data-dimension-children="${id}">
                        ${groupChildren}
                    </div>
                `;
            }

            var childHtml = hasChildren && expanded.has(id) ? renderNodes(node.children, depth + 1) : '';
            var code = node.code ? `<span class="pl-dimension-picker-option-code">${node.code}</span>` : '';

            return `
                <div class="pl-dimension-picker-item" style="padding-left:${depth * 16}px">
                    <button type="button" class="pl-dimension-picker-toggle-btn ${hasChildren ? '' : 'is-hidden'}" data-dimension-expand="${id}" aria-label="Expand">
                        <i class="bi ${expanded.has(id) ? 'bi-chevron-down' : 'bi-chevron-right'}" style="font-size:11px"></i>
                    </button>
                    <label class="pl-dimension-picker-option">
                        <input type="checkbox" value="${id}" data-dimension-checkbox ${selected.has(id) ? 'checked' : ''}>
                        <span class="pl-dimension-picker-option-label">${node.name}</span>
                        ${code}
                    </label>
                </div>
                ${hasChildren ? `<div class="${expanded.has(id) ? '' : 'd-none'}" data-dimension-children="${id}">${childHtml}</div>` : ''}
            `;
        }).join('');
    }

    function renderTree() {
        if (!treeEl) {
            return;
        }

        var html = renderNodes(tree, 0);
        treeEl.innerHTML = html;
        emptyEl?.classList.toggle('d-none', html.trim() !== '');
    }

    function closeMenu() {
        menu?.classList.add('d-none');
        toggleBtn?.setAttribute('aria-expanded', 'false');
    }

    toggleBtn?.addEventListener('click', function () {
        var isOpen = !menu?.classList.contains('d-none');
        if (isOpen) {
            closeMenu();
            return;
        }

        menu?.classList.remove('d-none');
        toggleBtn.setAttribute('aria-expanded', 'true');
        searchInput?.focus();
    });

    document.addEventListener('click', function (event) {
        if (!picker.contains(event.target)) {
            closeMenu();
        }
    });

    treeEl?.addEventListener('click', function (event) {
        var expandBtn = event.target.closest('[data-dimension-expand]');
        if (expandBtn) {
            event.preventDefault();
            var nodeId = expandBtn.getAttribute('data-dimension-expand');
            if (expanded.has(nodeId)) {
                expanded.delete(nodeId);
            } else {
                expanded.add(nodeId);
            }
            renderTree();
        }
    });

    treeEl?.addEventListener('change', function (event) {
        var checkbox = event.target.closest('[data-dimension-checkbox]');
        if (!checkbox) {
            return;
        }

        if (checkbox.checked) {
            selected.add(checkbox.value);
        } else {
            selected.delete(checkbox.value);
        }

        syncInputs();
        syncLabel();
    });

    searchInput?.addEventListener('input', function () {
        if (searchInput.value.trim()) {
            walk(tree, function (node) {
                if (node.children && node.children.length) {
                    expanded.add(String(node.id));
                }
            });
        }
        renderTree();
    });

    clearBtn?.addEventListener('click', function () {
        selected.clear();
        syncInputs();
        syncLabel();
        renderTree();
    });

    syncInputs();
    syncLabel();
    renderTree();
}

function initGlEmailModal() {
    var modalEl = document.getElementById('glEmailModal');
    if (!modalEl) {
        return;
    }

    function syncGlEmailPdfOptions() {
        var pdfSelected = modalEl.querySelector('#glEmailFormatPdf')?.checked;
        var pdfOptions = document.getElementById('glEmailPdfOptions');

        if (!pdfOptions) {
            return;
        }

        pdfOptions.style.display = pdfSelected ? '' : 'none';
        pdfOptions.querySelectorAll('select').forEach(function (field) {
            field.disabled = !pdfSelected;
        });
    }

    modalEl.querySelectorAll('input[name="format"]').forEach(function (input) {
        input.addEventListener('change', syncGlEmailPdfOptions);
    });

    syncGlEmailPdfOptions();

    <?php if(old('recipient')): ?>
    if (typeof bootstrap !== 'undefined') {
        bootstrap.Modal.getOrCreateInstance(modalEl).show();
    }
    <?php endif; ?>
}
</script>
<?php /**PATH /home/duiclick/public_html/test.duiclick.com/resources/views/reports/general-ledger/_filter-scripts.blade.php ENDPATH**/ ?>