
 /**
 * =============================================================================
 * @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 Create A Products page
 * 
 * =============================================================================
 * 
 * || INDEX:
 * ||   - CREATE A NEW PRODUCT PRIMARY FUNCTIONS
 * ||   - BRANDABILITY
 * ||   - PRODUCT OPERATIONS
 * ||   - CHECK PRODUCT
 * || 
 * =============================================================================
 */

jQuery(function ($) {
    
/*
============================================================
    CREATE A NEW PRODUCT PRIMARY FUNCTIONS
============================================================
*/

    $(document)
       
    // =========== View Brandability =========== //
    
        .on('click', '#view-brand-option', function (e) {
            
            $(document).off('.brandability');
            let pageName = 'brand-options-page';
            
            $.ajax({
                url: blueRavenProducts.ajaxurl,
                type: 'POST',
                data: {
                    action: 'blue_raven_products',
                    subaction: pageName,
                    nonce: blueRavenProducts.product_nonce
                },
                beforeSend: function() {
                    $('#view-brand-option').prop('disabled', true);
                },
                success: function(response) {
                    $('#product-block').html(response);
                    $('#view-brand-option').hide(); 
                    $('#view-new-product').show();
                },
                complete: function() {
                    $('#view-brand-option').prop('disabled', false);
                },
                error: function(xhr, status, error) {
                    console.error('AJAX Error:', status, error);
                }
            });
        })
        
/*
============================================================
    BRANDABILITY
============================================================
*/  
    // =========== Return to New product  =========== //
    
        .on('click', '#view-new-product', function (e) { $('#create-product').click(); });
});

/*
============================================================
    PRODUCT OPERATIONS
============================================================
*/ 
    
function BlueRaven_ProductOperation(content, subaction, button) {
    currentTool = button;
    
    return fetch(blueRavenProducts.ajaxurl, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        },
        body: new URLSearchParams({
            action: 'blue_raven_products',
            subaction: subaction,
            content: content,
            nonce: blueRavenProducts.product_nonce
        })
    })
    .then(response => {
        if (!response.ok) { throw new Error('Network response was not ok');  }
        const contentType = response.headers.get('content-type'); if (contentType && contentType.includes('application/json')) { return response.json(); } else { return response.text(); }
    })
    .then(data => {
        if (subaction == 'new product') {
            const id = data.data.product_id;
            window.location.href = `?page=blue-raven&product=${id}`;
            return true;
        } else {
            if (typeof data === 'string') { alert(data); } else { alert(data.message || "Operation completed successfully"); }
            return true;
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert("There was an error. Please contact Support.");
        return false;
    });
}

/*
============================================================
    CHECK PRODUCT
============================================================
*/ 

function BlueRaven_checkInterval(pid) {
    var BlueRaven_checkInterval = setInterval(function() {
        if (!document.querySelector('[data-interval-active="true"]')) {
            clearInterval(BlueRaven_checkInterval);
            return;  
        }

    /* =========== Debug: Verify nonce exists before sending =========== */
        
        if (!blueRavenProducts?.product_nonce) {
            console.error("Nonce is missing!");
            clearInterval(BlueRaven_checkInterval);
            return;  
        }
        
    /* =========== PROPER POST request with form data =========== */
        
        fetch(blueRavenProducts.ajaxurl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            },
            body: new URLSearchParams({
                action: 'blue_raven_products',
                subaction: 'check_product_status',
                product_id: pid,
                nonce: blueRavenProducts.product_nonce
            })
        })
        .then(response => {
            if (!response.ok) throw new Error('Network error');
            return response.json();
        })
        .then(data => {
            if (!data || typeof data !== 'object') {
                console.error("Invalid response structure:", data);
                clearInterval(BlueRaven_checkInterval);
                return;
            }

            if (!data.success) {
                console.warn("Request failed:", data.data?.message || "Unknown error");
                clearInterval(BlueRaven_checkInterval);
                return;
            }

            if (document.querySelector('.loading-container')) {
                if (data.data.status === false) {
                    clearInterval(BlueRaven_checkInterval);  
                    location.reload();
                }
            }
        })
        .catch(error => {
            console.error("Fetch error:", error);
            clearInterval(BlueRaven_checkInterval);
        });
    }, 10000);
    
    return BlueRaven_checkInterval;
}

jQuery(function ($) {
    $(document)
                
    /* =========== Save branding =========== */
        
        .on('click', '#save-brand-settings', function (e) {
            
            e.preventDefault();
            const content = $('#brandability-form').serialize();
            const $error = $('#brandability-form-error-message');
            BlueRaven_ProductOperation(content, 'save brandability', '');
        })
                    
    /* =========== Adding Blocks  =========== */
    
        .on('click', '.template-title-block, .template-description-block', function (e) {
            const isTitle = $(this).hasClass('template-title-block');
            const $input = isTitle ? $('#brand-title-style') : $('#brand-description-style');
            const $parent = $(this).closest('.br-tag-item');
            const clickedText = $(this).text().trim();
            const escapedText = clickedText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
            let current = $input.val();
        
            /// -- Clean Text 
            
            const regex = new RegExp(`\\s*,?\\s*${escapedText}\\s*,?\\s*`, 'gi');
        
            if ($parent.hasClass('active')) {
                let updated = current.replace(regex, ' ')
                                        .replace(/\s*,\s*/g, ', ')
                                        .replace(/,+/g, ',')
                                        .replace(/(^,|,$)/g, '')
                                        .replace(/\s+/g, ' ')
                                        .trim();
                $input.val(updated);
                $parent.removeClass('active');
            } else {
                let updated = current.trim();
                if (updated.length > 0 && !updated.endsWith(',')) updated += ', ';

                updated += clickedText;
                $input.val(updated);
                $parent.addClass('active');
            }
        })
                    
    /* =========== Change in Input Blocks  =========== */
                    
        .on('input','#brand-title-style', BlueRaven_updateTitleActives)
        .on('input','#brand-description-style', BlueRaven_updateDescriptionActives)
        
        function BlueRaven_normalize(str) { return $.trim(str.toLowerCase().replace(/\s+/g, ' ')); }
        
        function BlueRaven_updateTitleActives() {
            const inputVal = BlueRaven_normalize($('#brand-title-style').val());
        
            $('.template-title-block').each(function () {
                const $this = $(this);
                const $parent = $this.closest('.br-tag-item');
                const blockText = BlueRaven_normalize($this.text());
        
                if (inputVal.includes(blockText)) { $parent.addClass('active'); } else {  $parent.removeClass('active'); }
            });
        }
        
        function BlueRaven_updateDescriptionActives() {
            const inputVal = BlueRaven_normalize($('#brand-description-style').val());
        
            $('.template-description-block').each(function () {
                const $this = $(this);
                const $parent = $this.closest('.br-tag-item');
                const blockText = BlueRaven_normalize($this.text());
        
                if (inputVal.includes(blockText)) {$parent.addClass('active'); } else { $parent.removeClass('active');}
            });
        }
});  

(function ($) {
    $(document).off('click', '#post-create-product') 
                
    /* =========== Save branding =========== */
        
        .on('click', '#post-create-product', function (e) {
            e.preventDefault();
            
            const $description = $('#product-description');
            const descriptionContent = $description.val().trim();
            if (!descriptionContent) { alert('Product description cannot be empty'); return false;}
            const content = $('#create-new-product').serialize();
            const $error = $('#new-product-form-error-message');
            
            $('#product-block').toggle();
            $('#creating-product-block').toggle();
            
            BlueRaven_ProductOperation(content, 'new product', '');
        });

        const display = document.querySelector('#feather-count-display');
        if (display && /\D/.test(display.textContent.trim())) { 
            $("#product-block").hide()
            $("#product-block-nol").show()
        }
})(jQuery);  