document.addEventListener('DOMContentLoaded', function () {
    const choices = 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_coupons_page.filter_form.products.placeholder,
        noResultsText: formipay_coupons_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_coupons_page.ajax_url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            },
            body: new URLSearchParams({
                action: 'formipay_coupon_get_products',
                search: query,
                _wpnonce: formipay_coupons_page.nonce
            }),
        })
            .then((response) => response.json())
            .then((data) => {
                choices.clearChoices();
                choices.setChoices(data, 'value', 'label', false);
            })
            .catch((error) => console.error('Error:', error));
    }
});

jQuery(function($){

    let formipay_coupon_table_grid = new gridjs.Grid({
        server: {
            url: formipay_coupons_page.ajax_url+'?action=formipay-tabledata-coupons&search='+document.getElementById('keyword').value+'&_wpnonce='+formipay_coupons_page.nonce,
            then: data => {

                if(data.posts_report){
                    processPostsReport(data.posts_report);
                }
                
                return data.results.map(
                    coupon => [coupon.ID, coupon.ID, coupon.code, coupon.products, coupon.value, coupon.type, coupon.usages, coupon.date_limit, coupon.status, coupon.case_sensitive]
                );
            },
            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_coupons_page.columns.id,
                width: '75px'
            },
            {
                name: formipay_coupons_page.columns.code,
                formatter: (_, row) => gridjs.html(`
                    <b>${_}</b><br>
                    <span class="post-action" style="visibility: hidden;">
                    <a href="${formipay_coupons_page.site_url}/wp-admin/post.php?post=${row.cells[0].data}&action=edit">edit</a> | <a href="#" class="delete-coupon" data-id="${row.cells[0].data}">delete</a> | <a href="#" class="duplicate-coupon" data-id="${row.cells[0].data}">duplicate</a>
                    </span>
                `)
            },
            {
                name: formipay_coupons_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) {
                                const currencyDetails = product.currency.split(':::');
                                const currencyCode = currencyDetails[0];
                                const currencySymbol = currencyDetails[2];
    
                                html += `
                                    <span class="product_related">
                                        ${product.title}<hr>
                                        <span class="country-currency">
                                        ${product.flag ? `<img src="${product.flag}" height="18">` : ''}
                                        <span class="currency-in-use">${currencyCode} (${currencySymbol})</span>
                                        </span>
                                    </span>
                                `;
                            }
                        });
                    }

                    return gridjs.html(html);

                }
            },
            {
                name: formipay_coupons_page.columns.amount,
                formatter: (_, row) => numberFormat(_)
            },
            {
                name: formipay_coupons_page.columns.type,
                formatter: (_, row) => gridjs.html(`
                    <span class="type-capsule the-type">${_}</span>
                `)
            },
            {
                name: formipay_coupons_page.columns.usages, // { used: 1, limit: 5 }
                formatter: (_, row) => gridjs.html(`<span class="coupon-used">${_.used}</span>/<span class="coupon-limit">${_.limit}</span>`) // 1/∞
            },
            formipay_coupons_page.columns.date_limit,
            {
                name: formipay_coupons_page.columns.status,
                formatter: (_, row) => gridjs.html(`
                    <span class="status-label ${_.toLowerCase()}">${_}</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-coupons'));

    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_coupons_page.modal.bulk_delete.question,
                showCancelButton: true,
                confirmButtonText: formipay_coupons_page.modal.bulk_delete.confirmButton,
                cancelButtonText: formipay_coupons_page.modal.bulk_delete.cancelButton
            }).then((result) => {
                /* Read more about isConfirmed, isDenied below */
                if (result.isConfirmed) {
                    $.ajax({
                        type: 'post',
                        url: formipay_coupons_page.ajax_url,
                        data: {
                            action: 'formipay-bulk-delete-coupon',
                            ids: selectedIds,
                            _wpnonce: formipay_coupons_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_coupon_table_grid.updateConfig({
            server: {
                url: formipay_coupons_page.ajax_url+'?action=formipay-tabledata-coupons&product='+document.getElementById('products').value+'&search='+document.getElementById('keyword').value+'&_wpnonce='+formipay_coupons_page.nonce,
                then: data => data.results.map(
                    coupon => [coupon.ID, coupon.ID, coupon.code, coupon.products, coupon.value, coupon.type, coupon.usages, coupon.date_limit, coupon.status, coupon.case_sensitive]
                ),
                total: data => data.total
            }
        }).forceRender();
    }

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

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

    $(document).on('input', 'input#swal2-input', function(){
        const value = $(this).val();
        $(this).val(value.replace(' ', ''));
    });

    $(document).on('click', '#add-new-coupon', async function(e){
        e.preventDefault();
        const { value: coupon_code } = await Swal.fire({
            input: "text",
            inputLabel: formipay_coupons_page.modal.add.title,
            showCancelButton: true,
            confirmButtonText: formipay_coupons_page.modal.add.confirmButton,
            cancelButtonText: formipay_coupons_page.modal.add.cancelButton,
            reverseButtons: true,
            inputValidator: (value) => {
                if (!value) {
                    return formipay_coupons_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_coupons_page.ajax_url,
                    data: {
                        action: 'formipay-create-coupon-post',
                        title: result.value,
                        _wpnonce: formipay_coupons_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-coupon', function(e){
        e.preventDefault();
        var data_id = $(this).attr('data-id');
        Swal.fire({
            icon: 'info',
            html: "Do you want to delete the coupon?",
            showCancelButton: true,
            confirmButtonText: "Delete Permanently",
        }).then((result) => {
            /* Read more about isConfirmed, isDenied below */
            if (result.isConfirmed) {
                $.ajax({
                    type: 'post',
                    url: formipay_coupons_page.ajax_url,
                    data: {
                        action: 'formipay-delete-coupon',
                        id: data_id,
                        _wpnonce: formipay_coupons_page.nonce
                    },
                    success: function (res) {
                        Swal.fire({
                            title: res.data.title,
                            html: res.data.message,
                            icon: res.data.icon
                        });
                        formipay_coupon_table_grid.forceRender();
                    }
                });
            }
        });
    });

    $(document).on('click', '.duplicate-coupon', function(e){
        e.preventDefault();
        var data_id = $(this).attr('data-id');
        Swal.fire({
            icon: 'info',
            html: "Do you want to duplicate the coupon?",
            showCancelButton: true,
            confirmButtonText: "Confirm",
        }).then((result) => {
            /* Read more about isConfirmed, isDenied below */
            if (result.isConfirmed) {
                $.ajax({
                    type: 'post',
                    url: formipay_coupons_page.ajax_url,
                    data: {
                        action: 'formipay-duplicate-coupon',
                        id: data_id,
                        _wpnonce: formipay_coupons_page.nonce
                    },
                    success: function (res) {
                        Swal.fire({
                            title: res.data.title,
                            html: res.data.message,
                            icon: res.data.icon
                        });
                        formipay_coupon_table_grid.forceRender();
                    }
                });
            }
        });
    })
});