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.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.amount,
                formatter: (_, row) => {
                    var amount = 'unset';
                    if(row.cells[4].data === 'Percentage') {
                        amount = numberFormat(_)+'%';
                    }
                    if(row.cells[4].data === 'Fixed'){
                        amount = '';
                        _.forEach(function(currency){
                            const splitRaw = currency.raw.split(':::');
                            const symbol = splitRaw[2] ? splitRaw[2] : splitRaw[0];
                            amount += `<span class="coupon-each-amount"><img src="${currency.flag}" width="18"><span class="amount-value">${symbol} ${currency.amount}</span></span>`;
                        })
                    }
                    return gridjs.html(amount);
                }
            },
            {
                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&search='+document.getElementById('keyword').value+'&_wpnonce='+formipay_coupons_page.nonce,
                then: data => data.results.map(
                    coupon => [coupon.ID, coupon.ID, coupon.code, coupon.value, coupon.type, coupon.usages, coupon.date_limit, coupon.status, coupon.case_sensitive]
                ),
                total: data => data.total
            }
        }).forceRender();
    }

    $('.form-tool, #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();
                    }
                });
            }
        });
    })
});