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_access_page.filter_form.products.placeholder,
        noResultsText: formipay_access_page.filter_form.products.noresult_text,
        itemSelectText: '',
    });

    const searchInput = document.querySelector('.choices__input--cloned');
    let typingTimer;

    searchInput.addEventListener('input', function () {
        const query = searchInput.value;

        if (query.length >= 3) {
            clearTimeout(typingTimer);
            typingTimer = setTimeout(() => {
                fetchChoices(query);
            }, 300); // Add a debounce delay
        }
    });

    function fetchChoices(query) {
        fetch(formipay_access_page.ajax_url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            },
            body: new URLSearchParams({
                action: 'formipay_access_items_get_products',
                search: query,
                nonce: formipay_access_page.nonce
            }),
        })
            .then((response) => response.json())
            .then((data) => {
                formChoices.clearChoices();
                formChoices.setChoices( data, 'value', 'label', true);
            })
            .catch((error) => console.error('Error:', error));
    }

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

        document.getElementById('orderby').value = 'ID';
        document.getElementById('sort_by').value = 'desc';
        document.getElementById('keyword').value = '';
        document.getElementById('keyword').dispatchEvent(event);
    });
});

jQuery(function($){

    let formipay_table_grid = new gridjs.Grid({
        server: {
            url: formipay_access_page.ajax_url+'?action=formipay-tabledata-access-items&post_status='+document.getElementById('post_status').value+'&product='+document.getElementById('products').value+'&orderby='+document.getElementById('orderby').value+'&sort='+document.getElementById('sort_by').value+'&search='+document.getElementById('keyword').value+'&_wpnonce='+formipay_access_page.nonce,
            then: data => {
                
                if(data.posts_report){
                    processPostsReport(data.posts_report);
                }

                return data.results.map(
                    access => [access.ID, access.ID, access.title, access.type, access.products, access.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_access_page.columns.id,
                width: '75px'
            },
            {
                name: formipay_access_page.columns.title,
                formatter: (_, row) => {
                    var html = `
                        <b>${_}</b><br>
                        <span class="post-action" style="visibility: hidden;">
                        <a href="${formipay_access_page.site_url}/wp-admin/post.php?post=${row.cells[0].data}&action=edit">edit</a> | <a href="#" class="delete-access" data-id="${row.cells[0].data}">delete</a> | <a href="#" class="duplicate-access" data-id="${row.cells[0].data}">duplicate</a>
                        </span>
                    `;
                    return gridjs.html(html)
                }
            },
            {
                name: formipay_access_page.columns.type, 
                formatter: (type, row) => {
                    var html;
                    if(type == 'Redirect'){
                        html = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24">
                                    <path fill="#277aff" d="M11 17H7q-2.075 0-3.537-1.463T2 12t1.463-3.537T7 7h4v2H7q-1.25 0-2.125.875T4 12t.875 2.125T7 15h4zm-3-4v-2h8v2zm5 4v-2h4q1.25 0 2.125-.875T20 12t-.875-2.125T17 9h-4V7h4q2.075 0 3.538 1.463T22 12t-1.463 3.538T17 17z" />
                                </svg>${type}`;
                    }else if(type == 'Download') {
                        html = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24">
                                    <path fill="#277aff" d="M11 12.15V6.1q-1.9.35-2.95 1.838T7 11h-.5q-1.45 0-2.475 1.025T3 14.5t1.025 2.475T6.5 18h12q1.05 0 1.775-.725T21 15.5t-.725-1.775T18.5 13H17v-2q0-1.2-.55-2.238T15 7V4.675q1.85.875 2.925 2.588T19 11q1.725.2 2.863 1.488T23 15.5q0 1.875-1.312 3.188T18.5 20h-12q-2.275 0-3.887-1.575T1 14.575q0-1.95 1.175-3.475T5.25 9.15q.425-1.8 2.125-3.425T11 4.1q.825 0 1.413.588T13 6.1v6.05l.9-.875q.275-.275.688-.275t.712.3q.275.275.275.7t-.275.7l-2.6 2.6q-.3.3-.7.3t-.7-.3l-2.6-2.6q-.275-.275-.287-.687T8.7 11.3q.275-.275.688-.288t.712.263zm1-1.1" />
                                </svg>${type}`;
                    }else if(type == 'Document') {
                        html = `<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24">
                                    <path fill="#277aff" d="M8 13h8v-2H8zm0 3h8v-2H8zm0 3h5v-2H8zm-2 3q-.825 0-1.412-.587T4 20V4q0-.825.588-1.412T6 2h8l6 6v12q0 .825-.587 1.413T18 22zm7-13V4H6v16h12V9zM6 4v5zv16z" />
                                </svg>${type}`;
                    }
                    return gridjs.html(html)
                }
            },
            {
                name: formipay_access_page.columns.products,
                formatter: (products, row) => {

                    let html = '';

                    // Loop through each product in the products array
                    if(products.length > 0){
                        products.forEach(product => {
                            if (product) {
                                html += `
                                    <span class="product_related">
                                        ${product}
                                        </span>
                                    </span>
                                `;
                            }
                        });
                    }

                    return gridjs.html(html);

                }
            },
            {
                name: formipay_access_page.columns.status,
                formatter: (_, row) => gridjs.html(`
                    <span class="status-label ${_}">${_}</span>
                `)
            }  
        ],
        pagination: {
            limit: 10,
            server: {
                url: (prev, page, limit) => `${prev}&limit=${limit}&offset=${page * limit}`
            },
            summary: false
        },
        className: {
            table: 'formipay-grid-table'
        }
    }).render(document.getElementById('formipay-access-items'));

    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_access_page.modal.bulk_delete.question,
                showCancelButton: true,
                confirmButtonText: formipay_access_page.modal.bulk_delete.confirmButton,
                cancelButtonText: formipay_access_page.modal.bulk_delete.cancelButton
            }).then((result) => {
                /* Read more about isConfirmed, isDenied below */
                if (result.isConfirmed) {
                    $.ajax({
                        type: 'post',
                        url: formipay_access_page.ajax_url,
                        data: {
                            action: 'formipay-bulk-delete-access-item',
                            ids: selectedIds,
                            _wpnonce: formipay_access_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_access_page.ajax_url+'?action=formipay-tabledata-access-items&post_status='+document.getElementById('post_status').value+'&product='+document.getElementById('products').value+'&orderby='+document.getElementById('orderby').value+'&sort='+document.getElementById('sort_by').value+'&search='+document.getElementById('keyword').value,
                then: data => data.results.map(
                    access => [access.ID, access.ID, access.title, access.type, access.products, access.status]
                ),
                total: data => data.total
            }
        }).forceRender();
    }

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

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

    $(document).on('click', '#add-new-item', async function(e){
        e.preventDefault();
        const { value: coupon_code } = await Swal.fire({
            input: "text",
            inputLabel: formipay_access_page.modal.add.title,
            showCancelButton: true,
            confirmButtonText: formipay_access_page.modal.add.confirmButton,
            cancelButtonText: formipay_access_page.modal.add.cancelButton,
            reverseButtons: true,
            inputValidator: (value) => {
                if (!value) {
                    return formipay_access_page.modal.add.validation;
                }
            }
        }).then((result) => {
            /* Read more about isConfirmed, isDenied below, input value is ${coupon_code} */ 
            if (result.isConfirmed && result.value) {
                $.ajax({
                    type: 'post',
                    url: formipay_access_page.ajax_url,
                    data: {
                        action: 'formipay-create-access-item-post',
                        title: result.value,
                        nonce: formipay_access_page.nonce
                    },
                    success: function (res) {
                        if(res.success){
                            window.location.href = res.data.edit_post_url;
                        }else{
                            Swal.fire({
                                html: res.data.message,
                                icon: 'error'
                            });
                        }
                    }
                });
            }
        });
    });

    $(document).on('click', '.delete-access', function(e){
        e.preventDefault();
        var data_id = $(this).attr('data-id');
        Swal.fire({
            icon: 'info',
            html: formipay_access_page.modal.delete.question,
            showCancelButton: true,
            confirmButtonText: formipay_access_page.modal.delete.confirmButton,
            cancelButtonText: formipay_access_page.modal.delete.cancelButton,
        }).then((result) => {
            /* Read more about isConfirmed, isDenied below */
            if (result.isConfirmed) {
                $.ajax({
                    type: 'post',
                    url: formipay_access_page.ajax_url,
                    data: {
                        action: 'formipay-delete-access-item',
                        id: data_id,
                        nonce: formipay_access_page.nonce
                    },
                    success: function (res) {
                        Swal.fire({
                            title: res.data.title,
                            html: res.data.message,
                            icon: res.data.icon
                        });
                        formipay_table_grid.forceRender();
                    }
                });
            }
        });
    });

    $(document).on('click', '.duplicate-access', function(e){
        e.preventDefault();
        var data_id = $(this).attr('data-id');
        Swal.fire({
            icon: 'info',
            html: formipay_access_page.modal.duplicate.question,
            showCancelButton: true,
            confirmButtonText: formipay_access_page.modal.duplicate.confirmButton,
            cancelButtonText: formipay_access_page.modal.duplicate.cancelButton,
        }).then((result) => {
            /* Read more about isConfirmed, isDenied below */
            if (result.isConfirmed) {
                $.ajax({
                    type: 'post',
                    url: formipay_access_page.ajax_url,
                    data: {
                        action: 'formipay-duplicate-access-item',
                        id: data_id,
                        nonce: formipay_access_page.nonce
                    },
                    success: function (res) {
                        Swal.fire({
                            title: res.data.title,
                            html: res.data.message,
                            icon: res.data.icon
                        });
                        formipay_table_grid.forceRender();
                    }
                });
            }
        });
    });
});