/**
 * =============================================================================
 * @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
 * @File Description	WC related tools for the My Products page
 * 
 * =============================================================================
 * 
 * || INDEX:
 * ||   - HEAD
 * ||   - PRODUCT TAG 
 * ||   - PRODUCTS
 * ||   - POST FUNCTION
 * ||
 * =============================================================================
 */

jQuery(function ($) {
    $(document)
       
/*
============================================================
    HEAD
============================================================
*/

    /* =========== Return to My Products list =========== */
        
        .on('click', '#back-to-myproducts', function(e) {
            e.preventDefault();
            
            const url = new URL(window.location.href);
            url.searchParams.delete('product');
            window.history.replaceState({}, '', url);
            
            $('#my-products').click();
        })
        
/*
============================================================
    PRODUCT TAG 
============================================================
*/

    // ===========  Add a new tag, Typing into the input  =========== //
    
        .on('input focus', '#add-new-tag', function(e) {
            const context = $(this).val();
            
            $.ajax({
                url: blueRavenMyProducts.ajaxurl,
                type: 'POST',
                data: {
                    action: 'blue_raven_my_products',
                    subaction: 'get relavent tags',
                    context: context,
                    nonce: blueRavenMyProducts.my_product_nonce
                },
                success: function(response) {
                    const $textPad = $('#tag-text-pad');
                    $textPad.empty();
                    
                    if (response && response.length > 0) {
                        $textPad.show();
                        
                        $.each(response, function(index, item) {
                        
                            $('<p>')
                                .text(item.text)  
                                .attr('data-id', item.id)  
                                .attr('class', 'clickable-nomove textpad-object')  
                                .css({
                                    'margin': '0.25rem 0',
                                    'border' : '2px solid transparent'
                                })
                                .appendTo($textPad);
                            });
                    } else {
                        $textPad.hide();
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX Error:', status, error);
                }
            });
        })
        
/*
============================================================
    PRODUCTS 
============================================================
*/

    // ===========  Add a new tag, Typing into the input  =========== //
    
        .on('input focus', '#product-upsells, #product-cross-sells, #product-grouped-products', function(e) {
            const searchTerm = $(this).val();
            const inputId = $(this).attr('id');
                    
            let $textPad;
            switch(inputId) {
                case 'product-upsells':
                    $textPad = $('#upsells-text-pad');
                    break;
                case 'product-cross-sells':
                    $textPad = $('#cross-sell-text-pad');
                    break;
                case 'product-grouped-products':
                    $textPad = $('#grouped-products-text-pad');
                    break;
                default:
                    return;
            }
            
            $.ajax({
                url: blueRavenMyProducts.ajaxurl,
                type: 'POST',
                data: {
                    action: 'blue_raven_my_products',
                    subaction: 'search woocommerce products',
                    context: searchTerm,
                    nonce: blueRavenMyProducts.my_product_nonce
                },
                success: function(response) {
                    $textPad.empty();
                    
                    if (response && response.length > 0) {
                        $textPad.show();
                        
                        $.each(response, function(index, item) {
                            $('<p>')
                                .text(item.name)  
                                .attr('data-id', "id:" + item.id)  
                                .attr('class', 'clickable-nomove textpad-object')  
                                .css({
                                    'margin': '0.25rem 0',
                                    'border': '2px solid transparent'
                                })
                                .appendTo($textPad);
                        });
                    } else {
                        $textPad.hide();
                    }
                },
                error: function(xhr, status, error) {
                    console.error('AJAX Error:', status, error);
                }
            });
        })
});

/*
============================================================
    POST FUNCTION
============================================================
*/

function BlueRaven_postOperation(content, subaction, alertOption = true) {
    content = Array.isArray(content) ? content : [content];
    return fetch(blueRavenMyProducts.ajaxurl, {
        method: 'POST', 
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        },
        body: new URLSearchParams([
            ['action', 'blue_raven_my_products'],
            ['subaction', subaction],
            ...content.map((item, index) => [`content[${index}]`, typeof item === 'object' ? JSON.stringify(item) : item]),
            ['nonce', blueRavenMyProducts.my_product_nonce]
        ])
    })
    .then(response => response.ok ? response.text() : Promise.reject('Network error'))
    .then(data => {

        if (alertOption === true) {
            const response = typeof data === 'string' ? JSON.parse(data) : data;
            const rawMsg = typeof response?.data === 'string' ? response.data : response?.data?.message;

            if (typeof rawMsg === 'string' && rawMsg.includes('"errors"') && rawMsg.includes('"processed_count"') && rawMsg.includes('"error":') ) {
                try {
                    const jsonStart = rawMsg.indexOf('{');
                    const jsonString = rawMsg.slice(jsonStart);
                    const parsed = JSON.parse(jsonString);
                    const errorMessage = parsed?.errors?.[0]?.error || "Unknown error.";
                    alert(errorMessage);
                } catch (e) {
                    alert("Failed to parse the embedded JSON in response.data.message");
                }
            } else {
                if (typeof response.data === 'string') {
                    alert(response.data);
                } else if (typeof response.data === 'object' && response.data.message) {
                    alert(response.data.message);
                } else if (typeof response.data === 'object' && response.data.status) {
                    alert(response.data.status);
                } else if (typeof response === 'object' && response.success && response.data) {
                    alert(response.data); 
                } else {
                    alert("Unknown response format");
                }
            }
        } else {
            return data;          
        }
    })
    .catch(() => {
        alert("There was an error. Please contact Support.");
        return false;
    });
}
