
 /**
 * =============================================================================
 * @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        MAIN Admin JS 
 * 
 * =============================================================================
 * 
 * || INDEX:
 * ||   - PAGE LOADING
 * ||   - HANDLE NAV
 * ||   - CLEAN UP
 * ||   - STATUS INDICATOR  
 * || 
 * =============================================================================
 */

(function($) {
    
    const ns = blueRavenAdmin.namespace || 'blueRavenAdmin';
    
    function BlueRaven_initPlugin() {
        
        $(document).on(`click.${ns}`, '.enterra-nav-button', BlueRaven_handleNavButtonClick);

        const urlParams = new URLSearchParams(window.location.search);
        const hasProduct = urlParams.has('product');
    
        if (hasProduct) {$('#my-products').trigger('click'); }else{ $('#home').trigger('click');}  
    }
    
/*
============================================================
    PAGE LOADING
============================================================
*/        
    
    // =========== Load Page =========== //
    
    function BlueRaven_loadPage(pageName) {
        const urlParams = new URLSearchParams(window.location.search);
        
        $.ajax({
            url: blueRavenAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'blue_raven_load_sub_menus',
                pageURL: urlParams.toString(),
                page: pageName,
                nonce: blueRavenAdmin.nonce
            },
            success: BlueRaven_showPageContent,
            error: BlueRaven_showErrorState
        });
    }
    
    function BlueRaven_showPageContent(response) { $('#blue-raven-view-container').html(response); }
    function BlueRaven_showErrorState() { $('#blue-raven-view-container').html('<p class="error">Error loading tool</p>'); }

    function BlueRaven_FetchFeatherCount() {
        const urlParams = new URLSearchParams(window.location.search);
        
        $.ajax({
            url: blueRavenAdmin.ajaxurl,
            type: 'POST',
            data: {
                action: 'blue_raven_load_sub_menus',
                pageURL: urlParams.toString(),
                page: 'feather',
                nonce: blueRavenAdmin.nonce
            },
            success: function(response) {
                $('#feather-count-display').html(response);
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.error('Error:', textStatus, errorThrown);
            }
        });
    }
  

/*
============================================================
    HANDLE NAV
============================================================
*/    
    
    // =========== Nav clicks =========== //    
    
    function BlueRaven_handleNavButtonClick(e) {
        const pageName = e.currentTarget.id; 
        $(".enterra-nav-button").removeClass('active');
        $(e.currentTarget).addClass('active');

        BlueRaven_loadPage(pageName);
        BlueRaven_FetchFeatherCount();
    }
    
/*
============================================================
    INIT
============================================================
*/

    $(function() {
        BlueRaven_initPlugin();
        
        $(window).on(`beforeunload.${ns}`, function() {if (window.blueRavenAdminCleanup) blueRavenAdminCleanup();});
        $(document).on('click', '#feather-count-display', function() { BlueRaven_FetchFeatherCount() });
    });
    
})(jQuery);

/*
============================================================
    STATUS INDICATOR 
============================================================
*/
(function() {
    const indicator = document.getElementById('status-indicator');
    if (!indicator) return;

    indicator.style.backgroundColor = 'gray';
    indicator.title = 'Checking system status...';
    
    const xhr = new XMLHttpRequest();
    xhr.open('GET', 'https://portal.enterrahost.com/systemstatus.php?t=' + Date.now(), true);
    xhr.setRequestHeader('Accept', 'application/rss+xml');
  
    xhr.onload = function() {
        if (xhr.status >= 200 && xhr.status < 300) {
            try {
                const parser = new DOMParser();
                const xmlDoc = parser.parseFromString(xhr.responseText, "text/xml");
        
                if (xmlDoc.getElementsByTagName("parsererror").length > 0) throw new Error('Invalid XML format');
        
                const items = xmlDoc.getElementsByTagName("item");
                let highestPriority = 'none'; // Default to no issues

                // Define the priority hierarchy
                const priorityLevels = {
                    'critical': 4,
                    'high': 3,
                    'medium': 2,
                    'low': 1
                };
                let currentHighestLevel = 0;

                for (let i = 0; i < items.length; i++) {
                    const priorityElements = items[i].getElementsByTagName("priority");
                    if (priorityElements.length > 0) {
                        const priorityText = priorityElements[0].textContent.trim().toLowerCase();
                        
                        // Find the matching priority level
                        for (const [priority, level] of Object.entries(priorityLevels)) {
                            if (priorityText.includes(priority)) {
                                if (level > currentHighestLevel) {
                                    currentHighestLevel = level;
                                    highestPriority = priority;
                                }
                                break; // Break out of the inner loop once a match is found
                            }
                        }
                        // If we found a critical issue, we can break early
                        if (currentHighestLevel === priorityLevels.critical) break;
                    }
                }
                
                // =========== Set the appropriate color =========== //
                switch(highestPriority) {
                    case 'critical':
                        indicator.style.backgroundColor = 'red';
                        indicator.title = 'Critical system issue';
                        break;
                    case 'high': // NEW CASE ADDED
                        indicator.style.backgroundColor = 'orange';
                        indicator.title = 'High priority system issue';
                        break;
                    case 'medium':
                        indicator.style.backgroundColor = 'orange'; // or 'yellow' for a different visual
                        indicator.title = 'Medium system issue';
                        break;
                    case 'low':
                        indicator.style.backgroundColor = 'yellow';
                        indicator.title = 'Low priority system issue';
                        break;
                    default:
                        indicator.style.backgroundColor = 'green';
                        indicator.title = 'All systems operational';
                }
            } catch (e) {
                console.error('Error processing status:', e);
                indicator.style.backgroundColor = 'gray';
                indicator.title = 'Status check failed - click to check manually';
            }
        } else {
            console.error('Request failed with status:', xhr.status);
            indicator.style.backgroundColor = 'gray';
            indicator.title = 'Status unavailable - click to check manually';
        }
    };
  
    xhr.onerror = function() {
        console.error('Request failed');
        indicator.style.backgroundColor = 'gray';
        indicator.title = 'Status unavailable - click to check manually';
    };
  
    xhr.send();
    
})();
