 /**
 * =============================================================================
 * @package         Blue Raven (Free Version)
 * @Plugin URI      https://enterrahost.com/plugins/blue-raven
 * 
 * @Author          EnterraHost
 * @Author URI      https://enterrahost.com
 * @License         GPL-2.0-or-later
 *  
 * @Copyright       (c) 2025 EnterraHost
 * @Contents        Product Table JS
 *
 * =============================================================================
 * 
 * || INDEX:
 * ||   - FILTER
 * ||   - DELETE
 * ||   - FAVORITES
 * ||   - BUTTONS
 * ||   - PRODUCT TABLE AJAX
 * || 
 * =============================================================================
 */
 
jQuery(function ($) {
    $(document).off('.product-table');
    $(document)
    
/*
============================================================
    FILTER
============================================================
*/
    
    /* =========== Pageination Search =========== */ 

    .on('click.product-table','#search-myproducts', function(e) {
        e.preventDefault(); 
        
        let search = $("#product-search").val();
        let nextPage = 1;
        
        let filters = {
            category: $("#filter-category").val(),
            status: $("#filter-Status").val(),
            stock: $("#filter-stock").is(":checked"),
            favorite: $("#filter-favorite").is(":checked")
        };
        
        let filtersJson = JSON.stringify(filters);
        let filter = filtersJson;
        
        const content = [filter, search, nextPage]
        
        BlueRaven_postOperationTable(content, 'reload', false)
            .then(html => {$('#ProductTable').html(html);})
            .catch(() => {console.error('Error updating product table'); });
    })

    /* =========== Pageination Forward =========== */ 

    .on('click.product-table','#forward-page', function(e) {
        e.preventDefault(); 
        
        let currentPage = parseInt($('#page-count').text()) || 1;
        let nextPage = currentPage + 1;
        let filter = $("#product-filter-val").val();
        let search = $("#product-search-val").val();
        
        const content = [filter, search, nextPage]
        
        BlueRaven_postOperationTable(content, 'reload', false)
            .then(html => {$('#ProductTable').html(html);})
            .catch(() => {console.error('Error updating product table');});
    })
    
    /* =========== Pageination Back =========== */ 

    .on('click.product-table','#back-page', function(e) {
        e.preventDefault(); 
        
        let currentPage = parseInt($('#page-count').text()) || 1;
        let nextPage = currentPage - 1;
        let filter = $("#product-filter-val").val();
        let search = $("#product-search-val").val();
        
        const content = [filter, search, nextPage]
        
        BlueRaven_postOperationTable(content, 'reload', false)
            .then(html => {$('#ProductTable').html(html);})
            .catch(() => {console.error('Error updating product table');});
    })
    
/*
============================================================
    DELETE
============================================================
*/

    .on('click.product-table', '.delete-check', function() {
        if ($(this).is(':checked')) {
            if (!$('#delete-button').is(':visible')) $('#delete-button').show();
        } else {
            if ($('.delete-check:checked').length === 0) $('#delete-button').hide();
        }
    })
    
    .on('click.product-table', '#delete-button', function() {
        const checkedProductIds = Array.from(document.querySelectorAll('.blue-raven-products-table input.delete-check:checked') ).map(el => el.value); 
        
        if (confirm("Are you sure you want to delete these products?")) {
            const content = checkedProductIds;
            BlueRaven_postOperationTable(content, 'delete', false)
                .then(html => {setTimeout(() => {$('#search-myproducts').click();$('#delete-button').hide();}, 100); });
        }        
    })
    
/*
============================================================
    FAVORITES
============================================================
*/

    .on('change.product-table','.favorite-star', function(e) {
        e.preventDefault(); 
        
        const dataIdAlt = $(this).attr('data-id');
        const isChecked = $(this).prop('checked'); 
        const content = [dataIdAlt, isChecked];
        
        BlueRaven_postOperationTable(content, 'favorite', true)
    })

/*
============================================================
    BUTTONS
============================================================
*/
    .on('click.product-table','#woo-import-button', function(e) {
        BlueRaven_postOperationTable([''], 'import', true)
            .then(html => { setTimeout(() => { $('#my-products').click();}, 100); });
    })
    
/*
============================================================
    WIP
============================================================
*/

    .on('click.product-table','#view-statistics', function(e) { alert('This feature is still under development. Thank you for your patience!');})
    .on('click.product-table','#view-versions', function(e) { alert('This feature is still under development. Thank you for your patience!');})
    
});
      
/*
============================================================
    PRODUCT TABLE AJAX
============================================================
*/
       
function BlueRaven_postOperationTable(content, subaction, alertOption = true) {
    content = Array.isArray(content) ? content : [content];
    
    return fetch(blueRavenMyTable.ajaxurl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        },
        body: new URLSearchParams([
            ['action', 'blue_raven_my_table'],
            ['subaction', subaction],
            ...content.map((item, index) => [`content[${index}]`, typeof item === 'object' ? JSON.stringify(item) : item]),
            ['nonce', blueRavenMyTable.my_table_nonce]
        ])
    })
    .then(response => response.ok ? response.text() : Promise.reject('Network error'))
    .then(data => {
        if(alertOption === true) alert(data);
        return data;
    })
    .catch(() => {
        alert("There was an error. Please contact Support.");
        return false;
    });
}

