document.addEventListener('DOMContentLoaded', function () {
    const formChoices = new Choices('#products', {
        searchEnabled: true,
        searchChoices: false, // Prevent Choices.js from filtering the local list
        searchResultLimit: 10, // Optional: Limit visible results
        placeholder: true,
        placeholderValue: formipay_orders_page.filter_form.products.placeholder,
        noResultsText: formipay_orders_page.filter_form.products.noresult_text,
        itemSelectText: '',
    });

    const currencyChoices = new Choices('#currencies', {
        searchEnabled: true,
        searchChoices: false, // Prevent Choices.js from filtering the local list
        searchResultLimit: 10, // Optional: Limit visible results
        placeholder: true,
        placeholderValue: formipay_orders_page.filter_form.currencies.placeholder,
        noResultsText: formipay_orders_page.filter_form.currencies.noresult_text,
        itemSelectText: '',
        allowHTML: true
    });

    const searchInputs = document.querySelectorAll('.choices__input--cloned');
    let typingTimer;

    searchInputs.forEach((searchInput) => {
        searchInput.addEventListener('input', function () {
            const query = searchInput.value;
    
            if (query.length >= 3) {
                clearTimeout(typingTimer);
                typingTimer = setTimeout(() => {
                    // Find the wrapper (e.g., .product or .currency)
                    const parentWrapper = searchInput.closest('.product, .currency');
                    let searchType = ''; // Initialize search type
    
                    // Determine the type based on the parent wrapper's class
                    if (parentWrapper) {
                        if (parentWrapper.classList.contains('product')) {
                            searchType = 'form';
                        } else if (parentWrapper.classList.contains('currency')) {
                            searchType = 'currency';
                        }
                    }
    
                    // Fetch choices with the determined type
                    fetchChoices(query, searchType);
                }, 300); // Add a debounce delay
            }
        });
    });    

    function fetchChoices(query, type) {
        fetch(formipay_orders_page.ajax_url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            },
            body: new URLSearchParams({
                action: 'formipay_orders_get_choices',
                search: query,
                type: type, // Pass the type to the server,
                _wpnonce: formipay_orders_page.nonce
            }),
        })
        .then((response) => response.json())
        .then((data) => {
            const currentChoices = type === 'form' ? formChoices : currencyChoices;

            currentChoices.clearChoices();
            currentChoices.setChoices(data, 'value', 'label', true);
        })
        .catch((error) => console.error('Error:', error));
    }

    document.getElementById('reset-filter').addEventListener('click', function(){
        formChoices.removeActiveItems();
        currencyChoices.removeActiveItems();
        
        const input = document.getElementById('order_id');
        const event = new Event('change', { bubbles: true });

        input.value = '';
        input.dispatchEvent(event);
    });
});


jQuery(function($){

    let formipay_table_grid = new gridjs.Grid({
        server: {
            url: formipay_orders_page.ajax_url+'?action=formipay-tabledata-orders&order_status='+document.getElementById('post_status').value+'&product='+document.getElementById('products').value+'&currency='+document.getElementById('currencies').value+'&order_id='+document.getElementById('order_id').value+'&_wpnonce='+formipay_orders_page.nonce,
            then: data => {
                
                if(data.posts_report){
                    processPostsReport(data.posts_report);
                }

                return data.results.map(
                    order => [order.ID, order.ID, order.date, order.form, order.total, order.payment_gateway, order.status]
                );
            },
            total: data => data.total
        },
        columns: [
            {
                id: 'checkbox',
                name: gridjs.html(`<input type="checkbox" id="select-all-rows">`),
                width: '50px',
                formatter: (_, row) => gridjs.html(
                    `<input type="checkbox" class="formipay-row-checkbox" data-id="${row.cells[0].data}">`
                )
            },
            {
                name: formipay_orders_page.columns.id,
                width: '75px'
            },
            {
                name: formipay_orders_page.columns.date,
                formatter: (_, row) => gridjs.html('<span>' + _.split(' ').join('</span><br><span style="font-size: smaller;">') + '</span>')
            },
            {
                name: formipay_orders_page.columns.form,
                formatter: (_, row) => gridjs.html(`
                    <b>${_}</b><br>
                    <span class="post-action" style="visibility: hidden;">
                    <a href="${formipay_orders_page.site_url}/wp-admin/admin.php?page=formipay-orders&order_id=${row.cells[0].data}">details</a> | <a href="#" class="delete-order" data-id="${row.cells[0].data}">delete</a>
                    </span>
                `)
            },
            {
                name: formipay_orders_page.columns.total,
                formatter: (_, row) => gridjs.html(`
                    <span class="grand_total">
                        <span class="currency">
                            <img src="${_.flag}" height="18">
                            ${_.name}
                        </span>
                        <span class="the-total">${_.value}</span>
                    </span>
                `)
            },
            formipay_orders_page.columns.payment_gateway,
            {
                name: formipay_orders_page.columns.status,
                formatter: (status, row) => gridjs.html(`<span class="status-label ${status}">${status}</span>`)
            }
        ],
        pagination: {
            limit: document.getElementById('limit').value,
            server: {
                url: (prev, page, limit) => `${prev}&limit=${limit}&offset=${page * limit}`
            },
            summary: false
        },
        className: {
            table: 'formipay-grid-table'
        }
    }).render(document.getElementById('formipay-orders'));

    var $tableContainer = $('.formipay-grid-table');
    var $deleteBtn = $('#formipay-delete-selected');

    function updateDeleteButtonVisibility() {
        if ($tableContainer.find('.formipay-row-checkbox:checked').length > 0) {
            $deleteBtn.show();
        } else {
            $deleteBtn.hide();
        }
    }

    // Handle row and "select all" checkbox changes
    $tableContainer.on('change', '.formipay-row-checkbox', function() {
        updateDeleteButtonVisibility();
    });

    // Handle row and "select all" checkbox changes
    $tableContainer.on('change', '#select-all-rows', function() {
        const is_checked = $(this).is(':checked');
        $tableContainer.find('.formipay-row-checkbox').prop('checked', is_checked);
        updateDeleteButtonVisibility();
    });

    // Handle delete button click
    $deleteBtn.on('click', function() {
        var selectedIds = $tableContainer.find('.formipay-row-checkbox:checked').map(function() {
            return $(this).data('id');
        }).get();

        if (selectedIds.length > 0) {
            Swal.fire({
                icon: 'info',
                html: formipay_orders_page.modal.bulk_delete.question,
                showCancelButton: true,
                confirmButtonText: formipay_orders_page.modal.bulk_delete.confirmButton,
                cancelButtonText: formipay_orders_page.modal.bulk_delete.cancelButton
            }).then((result) => {
                /* Read more about isConfirmed, isDenied below */
                if (result.isConfirmed) {
                    $.ajax({
                        type: 'post',
                        url: formipay_orders_page.ajax_url,
                        data: {
                            action: 'formipay-bulk-delete-access-item',
                            ids: selectedIds,
                            _wpnonce: formipay_orders_page.nonce
                        },
                        success: function (res) {
                            Swal.fire({
                                title: res.data.title,
                                html: res.data.message,
                                icon: res.data.icon
                            });
                            formipay_table_grid.forceRender();
                            $tableContainer.find('.formipay-row-checkbox').prop('checked', false);
                            updateDeleteButtonVisibility();
                            refresh_table_with_filter();
                        }
                    });
                }
            });
        }
    });

    function refresh_table_with_filter() {
        formipay_table_grid.updateConfig({
            server: {
                url: formipay_orders_page.ajax_url+'?action=formipay-tabledata-orders&order_status='+document.getElementById('post_status').value+'&product='+document.getElementById('products').value+'&currency='+document.getElementById('currencies').value+'&order_id='+document.getElementById('order_id').value+'&_wpnonce='+formipay_orders_page.nonce,
                then: data => data.results.map(
                    order => [order.ID, order.ID, order.date, order.form, order.total, order.payment_gateway, order.status]
                ),
                total: data => data.total
            },
            pagination: {
                limit: document.getElementById('limit').value,
                server: {
                    url: (prev, page, limit) => `${prev}&limit=${limit}&offset=${page * limit}`
                },
                summary: false
            },
        }).forceRender();
    }

    $('.form-tool, #post_status, #products, #currencies, #order_id').on('change', function(){
        refresh_table_with_filter();
    });

    $(document).on('mouseover', 'td[data-column-id=form]', function(){
        $(this).find('.post-action').css('visibility', 'visible');
    });
    $(document).on('mouseleave', 'td[data-column-id=form]', function(){
        $(this).find('.post-action').css('visibility', 'hidden');
    });

});