<?php
/**
 * ==========================
 * 🔐 IGNY8 FILE RULE HEADER
 * ==========================
 * @file         : global-layout.php
 * @location     : /core/global-layout.php
 * @type         : Layout
 * @scope        : Global
 * @allowed      : HTML layout, CSS/JS includes, navigation rendering
 * @reusability  : Globally Reusable
 * @notes        : Master layout template for all admin pages
 */
 

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Load helper functions
require_once plugin_dir_path(__FILE__) . 'admin/global-helpers.php';

// Evidence functions removed - no longer needed

// Component functions are loaded globally in igny8.php

// KPI configuration is loaded globally in igny8.php

// Load KPI data for header metrics based on current module/submodule
$kpi_data = [];
if (isset($GLOBALS['igny8_kpi_config']) && !empty($GLOBALS['igny8_kpi_config'])) {
    $kpi_config = $GLOBALS['igny8_kpi_config'];
    
    // Determine the table_id based on current module and submodule
    $current_module = $GLOBALS['current_module'] ?? '';
    $current_submodule = $GLOBALS['current_submodule'] ?? '';
    $current_page = $_GET['page'] ?? '';
    
    // Special handling for home pages
    if ($current_page === 'igny8-planner' && empty($current_submodule)) {
        $table_id = 'planner_home';
    } elseif ($current_page === 'igny8-writer' && empty($current_submodule)) {
        $table_id = 'writer_home';
    } elseif (!empty($current_module) && !empty($current_submodule)) {
        $table_id = $current_module . '_' . $current_submodule;
    } else {
        $table_id = '';
    }
    
    // Load KPI data if configuration exists for this table
    if (!empty($table_id) && isset($kpi_config[$table_id])) {
        $kpi_data = igny8_get_kpi_data_safe($table_id, $kpi_config[$table_id]);
    }
}
?>
<div class="igny8-page-wrapper">

    <!-- SIDEBAR SECTION -->
    <aside class="igny8-sidebar">
        <!-- LOGO / BRAND -->
        <div class="igny8-sidebar-logo">
            <h2>IGNY8 AI SEO</h2>
        </div>

        <!-- VERSION BADGE -->
        <div class="igny8-version-badge">
            <span class="igny8-badge igny8-btn-danger">v<?php echo get_plugin_data(plugin_dir_path(__FILE__) . '../igny8.php')['Version']; ?></span>
        </div>

        <!-- BREADCRUMB NAVIGATION -->
        <div class="igny8-breadcrumb">
            <?php echo igny8_render_breadcrumb(); ?>
        </div>

        <!-- DEBUG STATUS CIRCLES (submodule pages only) -->
        <?php 
        $is_debug_enabled = defined('WP_DEBUG') && WP_DEBUG;
        $is_monitoring_enabled = get_option('igny8_debug_enabled', false);
        $is_submodule_page = !empty($_GET['sm']) || !empty($GLOBALS['current_submodule']);
        
        if ($is_debug_enabled && $is_monitoring_enabled && $is_submodule_page): 
            // Simple debug circles - will be updated by JavaScript based on actual debug card states
            $debug_circles = [
                'database' => ['title' => 'Database', 'status' => 'secondary'],
                'table' => ['title' => 'Table', 'status' => 'secondary'],
                'filters' => ['title' => 'Filters', 'status' => 'secondary'],
                'forms' => ['title' => 'Forms', 'status' => 'secondary'],
                'automation' => ['title' => 'Automation', 'status' => 'secondary'],
                'ai_logs' => ['title' => 'AI Logs', 'status' => 'secondary']
            ];
        ?>
        <div class="igny8-sidebar-status-bar" style="padding: 12px 16px; border-bottom: 1px solid var(--border);">
            <div class="igny8-status-row">
                <div class="igny8-flex" style="justify-content: center; gap: 8px;">
                    <?php foreach ($debug_circles as $circle_key => $circle_data): ?>
                        <div class="bg-circle-sm bg-<?php echo esc_attr($circle_data['status']); ?> igny8-debug-circle" data-component="<?php echo esc_attr($circle_key); ?>" title="<?php echo esc_attr($circle_data['title']); ?>"></div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <!-- MAIN NAVIGATION -->
        <nav class="igny8-sidebar-nav">
            <?php 
            $current_page = $_GET['page'] ?? '';
            $home_active = ($current_page === 'igny8-home') ? 'active' : '';
            $settings_active = (strpos($current_page, 'igny8-settings') !== false) ? 'active' : '';
            $help_active = (strpos($current_page, 'igny8-help') !== false) ? 'active' : '';
            
            // Always show home, settings, and help
            ?>
            <a href="<?php echo admin_url('admin.php?page=igny8-home'); ?>" class="igny8-sidebar-link <?php echo $home_active; ?>">
                <span class="dashicons dashicons-dashboard"></span>
                <span class="label">Igny8 Home</span>
            </a>
            
            <?php 
            // Show modules only if they are enabled
            if (function_exists('igny8_is_module_enabled')) {
                // Main modules
                if (igny8_is_module_enabled('planner')) {
                    $planner_active = (strpos($current_page, 'igny8-planner') !== false) ? 'active' : '';
                    ?>
                    <a href="<?php echo admin_url('admin.php?page=igny8-planner'); ?>" class="igny8-sidebar-link <?php echo $planner_active; ?>">
                        <span class="dashicons dashicons-tag"></span>
                        <span class="label">Planner</span>
                    </a>
                    <?php
                }
                
                if (igny8_is_module_enabled('writer')) {
                    $writer_active = (strpos($current_page, 'igny8-writer') !== false) ? 'active' : '';
                    ?>
                    <a href="<?php echo admin_url('admin.php?page=igny8-writer'); ?>" class="igny8-sidebar-link <?php echo $writer_active; ?>">
                        <span class="dashicons dashicons-edit"></span>
                        <span class="label">Writer</span>
                    </a>
                    <?php
                }
                
                if (igny8_is_module_enabled('linker')) {
                    $linker_active = (strpos($current_page, 'igny8-linker') !== false) ? 'active' : '';
                    ?>
                    <a href="<?php echo admin_url('admin.php?page=igny8-linker'); ?>" class="igny8-sidebar-link <?php echo $linker_active; ?>">
                        <span class="dashicons dashicons-admin-links"></span>
                        <span class="label">Linker</span>
                    </a>
                    <?php
                }
                
                if (igny8_is_module_enabled('personalize')) {
                    $personalize_active = (strpos($current_page, 'igny8-personalize') !== false) ? 'active' : '';
                    ?>
                    <a href="<?php echo admin_url('admin.php?page=igny8-personalize'); ?>" class="igny8-sidebar-link <?php echo $personalize_active; ?>">
                        <span class="dashicons dashicons-admin-customizer"></span>
                        <span class="label">Personalize</span>
                    </a>
                    <div class="igny8-sidebar-divider"></div> <?php
                }

                ?>
                
                <?php
                // Thinker before schedules
                if (igny8_is_module_enabled('thinker')) {
                    $thinker_active = (strpos($current_page, 'igny8-thinker') !== false) ? 'active' : '';
                    ?>
                    <a href="<?php echo admin_url('admin.php?page=igny8-thinker'); ?>" class="igny8-sidebar-link <?php echo $thinker_active; ?>">
                        <span class="dashicons dashicons-lightbulb"></span>
                        <span class="label">Thinker</span>
                    </a>
                    <?php
                }
                
                // Admin modules
                if (igny8_is_module_enabled('schedules')) {
                    $schedules_active = (strpos($current_page, 'igny8-schedules') !== false) ? 'active' : '';
                    ?>
                    <a href="<?php echo admin_url('admin.php?page=igny8-schedules'); ?>" class="igny8-sidebar-link <?php echo $schedules_active; ?>">
                        <span class="dashicons dashicons-calendar-alt"></span>
                        <span class="label">Schedules</span>
                    </a>
                    <?php
                }
                
                
                // Analytics before Settings
                if (igny8_is_module_enabled('analytics')) {
                    $analytics_active = (strpos($current_page, 'igny8-analytics') !== false) ? 'active' : '';
                    ?>
                    <a href="<?php echo admin_url('admin.php?page=igny8-analytics'); ?>" class="igny8-sidebar-link <?php echo $analytics_active; ?>">
                        <span class="dashicons dashicons-chart-line"></span>
                        <span class="label">Analytics</span>
                    </a>
                    <?php
                }
                
            } else {
                // Fallback: show all modules if module manager is not available
                ?>
                <a href="<?php echo admin_url('admin.php?page=igny8-planner'); ?>" class="igny8-sidebar-link <?php echo (strpos($current_page, 'igny8-planner') !== false) ? 'active' : ''; ?>">
                    <span class="dashicons dashicons-tag"></span>
                    <span class="label">Planner</span>
                </a>
                <a href="<?php echo admin_url('admin.php?page=igny8-writer'); ?>" class="igny8-sidebar-link <?php echo (strpos($current_page, 'igny8-writer') !== false) ? 'active' : ''; ?>">
                    <span class="dashicons dashicons-edit"></span>
                    <span class="label">Writer</span>
                </a>
                <a href="<?php echo admin_url('admin.php?page=igny8-optimizer'); ?>" class="igny8-sidebar-link <?php echo (strpos($current_page, 'igny8-optimizer') !== false) ? 'active' : ''; ?>">
                    <span class="dashicons dashicons-performance"></span>
                    <span class="label">Optimizer</span>
                </a>
                <a href="<?php echo admin_url('admin.php?page=igny8-linker'); ?>" class="igny8-sidebar-link <?php echo (strpos($current_page, 'igny8-linker') !== false) ? 'active' : ''; ?>">
                    <span class="dashicons dashicons-admin-links"></span>
                    <span class="label">Linker</span>
                </a>
                <a href="<?php echo admin_url('admin.php?page=igny8-personalize'); ?>" class="igny8-sidebar-link <?php echo (strpos($current_page, 'igny8-personalize') !== false) ? 'active' : ''; ?>">
                    <span class="dashicons dashicons-admin-customizer"></span>
                    <span class="label">Personalize</span>
                </a>
                
                <div class="igny8-sidebar-divider"></div>
                
                <a href="<?php echo admin_url('admin.php?page=igny8-thinker'); ?>" class="igny8-sidebar-link <?php echo (strpos($current_page, 'igny8-thinker') !== false) ? 'active' : ''; ?>">
                    <span class="dashicons dashicons-lightbulb"></span>
                    <span class="label">Thinker</span>
                </a>
                <a href="<?php echo admin_url('admin.php?page=igny8-schedules'); ?>" class="igny8-sidebar-link <?php echo (strpos($current_page, 'igny8-schedules') !== false) ? 'active' : ''; ?>">
                    <span class="dashicons dashicons-calendar-alt"></span>
                    <span class="label">Schedules</span>
                </a>
                <a href="<?php echo admin_url('admin.php?page=igny8-analytics'); ?>" class="igny8-sidebar-link <?php echo (strpos($current_page, 'igny8-analytics') !== false) ? 'active' : ''; ?>">
                    <span class="dashicons dashicons-chart-line"></span>
                    <span class="label">Analytics</span>
                </a>
                <?php
            }
            ?>
            
            
            <a href="<?php echo admin_url('admin.php?page=igny8-settings'); ?>" class="igny8-sidebar-link <?php echo $settings_active; ?>">
                <span class="dashicons dashicons-admin-generic"></span>
                <span class="label">Settings</span>
            </a>
            <a href="<?php echo admin_url('admin.php?page=igny8-help'); ?>" class="igny8-sidebar-link <?php echo $help_active; ?>">
                <span class="dashicons dashicons-sos"></span>
                <span class="label">Help</span>
            </a>
        </nav>
        
        <div class="igny8-sidebar-divider"></div>
        

        <!-- JavaScript to update sidebar debug circles based on debug card states -->
        <?php if ($is_debug_enabled && $is_monitoring_enabled && $is_submodule_page): ?>
        <script>
        document.addEventListener('DOMContentLoaded', function() {
            // Function to update sidebar debug circles based on debug card states
            function updateSidebarDebugCircles() {
                const circles = document.querySelectorAll('.igny8-debug-circle');
                
                circles.forEach(circle => {
                    const component = circle.getAttribute('data-component');
                    let matchingCard = null;
                    
                    if (component === 'ai_logs') {
                        // Special handling for AI logs - it's in the automation section
                        const debugCards = document.querySelectorAll('.igny8-debug-item');
                        debugCards.forEach(card => {
                            const cardText = card.textContent.toLowerCase();
                            if (cardText.includes('ai logs') || cardText.includes('ai_logs')) {
                                matchingCard = card;
                            }
                        });
                    } else {
                        // Regular handling for other components
                        const debugCards = document.querySelectorAll('.igny8-debug-item');
                        debugCards.forEach(card => {
                            const cardText = card.textContent.toLowerCase();
                            const componentName = component.toLowerCase();
                            
                            if (cardText.includes(componentName)) {
                                matchingCard = card;
                            }
                        });
                    }
                    
                    if (matchingCard) {
                        // Get the status from the background color
                        const bgColor = matchingCard.style.backgroundColor;
                        let status = 'secondary'; // default
                        
                        if (bgColor.includes('212, 237, 218') || bgColor.includes('rgb(212, 237, 218)')) { // success green
                            status = 'success';
                        } else if (bgColor.includes('255, 243, 205') || bgColor.includes('rgb(255, 243, 205)')) { // warning yellow
                            status = 'warning';
                        } else if (bgColor.includes('248, 215, 218') || bgColor.includes('rgb(248, 215, 218)')) { // error red
                            status = 'danger';
                        }
                        
                        // Update circle classes
                        circle.className = `bg-circle-sm bg-${status} igny8-debug-circle`;
                    }
                });
            }
            
            // Update circles when page loads
            setTimeout(updateSidebarDebugCircles, 1000); // Wait for debug cards to load
            
            // Update circles periodically to catch dynamic changes
            setInterval(updateSidebarDebugCircles, 3000);
        });
        </script>
        <?php endif; ?>

        <!-- FOOTER SHORTCUTS -->
        <div class="igny8-sidebar-footer-container">
            <div class="igny8-sidebar-footer">
                <a href="<?php echo admin_url('options-general.php'); ?>" class="igny8-sidebar-link">
                    <span class="dashicons dashicons-admin-generic"></span>
                    <span class="label">Settings</span>
                </a>
                <a href="<?php echo wp_logout_url(); ?>" class="igny8-sidebar-link">
                    <span class="dashicons dashicons-migrate"></span>
                    <span class="label">Logout</span>
                </a>
            </div>
        </div>
    </aside>

    <!-- MAIN CONTAINER -->
    <div class="igny8-main-area">

        <!-- HEADER SECTION -->
        <header class="igny8-header">
            <!-- LEFT: Dynamic Submenu Navigation -->
            <div class="igny8-header-left">
                <div class="igny8-submenu">
                    <div class="igny8-submenu-buttons">
                        <?php echo igny8_render_submenu(); ?>
                    </div>
                </div>
            </div>

            <!-- CENTER: Page Title & Description -->
            <div class="igny8-header-center">
                <div class="igny8-page-title">
                    <h1><?php
                    // Hardcoded page titles
                    $page_titles = [
                        'igny8-home' => 'Dashboard',
                        'igny8-planner' => 'Planner',
                        'igny8-writer' => 'Writer',
                        'igny8-thinker' => 'Thinker',
                        'igny8-analytics' => 'Analytics',
                        'igny8-settings' => 'Settings',
                        'igny8-schedules' => 'Schedules',
                        'igny8-help' => 'Help'
                    ];
                    echo $page_titles[$current_page] ?? 'IGNY8 AI SEO';
                    ?></h1>
                </div>
            </div>

            <!-- RIGHT: Metrics Bar + Icons -->
            <div class="igny8-header-right">
                <!-- Metrics - Compact Format -->
                <div class="igny8-metrics-compact">
                    <?php 
                    // Use the same KPI logic as before but inline
                    if (empty($kpi_data)) {
                        $max_fallback = ($current_module === 'planner') ? 4 : 6;
                        $all_fallback_metrics = [
                            
                            ['value' => 0, 'label' => 'Active', 'color' => 'green'],
                            ['value' => 0, 'label' => 'Pending', 'color' => 'amber'],
                            ['value' => 0, 'label' => 'Completed', 'color' => 'purple'],
                            ['value' => 0, 'label' => 'Recent', 'color' => 'blue']
                           
                        ];
                        $fallback_metrics = array_slice($all_fallback_metrics, 0, $max_fallback);
                        
                        foreach ($fallback_metrics as $metric):
                    ?>
                        <div class="metric <?php echo $metric['color']; ?>">
                            <span class="val"><?php echo number_format($metric['value']); ?></span>
                            <span class="lbl"><?php echo $metric['label']; ?></span>
                        </div>
                    <?php 
                        endforeach;
                    } else {
                        // Get metrics - 4 for planner pages, 6 for others
                        $max_metrics = ($current_module === 'planner') ? 4 : 6;
                        $metrics = array_slice($kpi_data, 0, $max_metrics, true);
                        $color_map = ['', 'green', 'amber', 'purple', 'blue', 'teal'];
                        $color_index = 0;
                        
                        foreach ($metrics as $metric_key => $metric_value):
                            $kpi_config = $GLOBALS['igny8_kpi_config'] ?? [];
                            $color = '';
                            if (isset($kpi_config[$table_id][$metric_key]['color'])) {
                                $color = $kpi_config[$table_id][$metric_key]['color'];
                            } else {
                                $color = $color_map[$color_index] ?? '';
                            }
                            
                            $label = $metric_key;
                            if (isset($kpi_config[$table_id][$metric_key]['label'])) {
                                $label = $kpi_config[$table_id][$metric_key]['label'];
                            }
                        ?>
                            <div class="metric <?php echo $color; ?>">
                                <span class="val"><?php echo number_format($metric_value); ?></span>
                                <span class="lbl"><?php echo $label; ?></span>
                            </div>
                        <?php 
                        $color_index++;
                        endforeach;
                    }
                    ?>
                </div>

                <!-- Header User Icon -->
                <div class="igny8-header-icons">
                    <span class="dashicons dashicons-admin-users" title="User"></span>
                </div>
            </div>
        </header>

        <!-- MAIN CONTENT AREA -->
        <main class="igny8-content">
            <?php echo $igny8_page_content ?? '<p>No content provided.</p>'; ?>
            
            <!-- MODULE DEBUG SECTION (conditional based on toggle and submodule pages) -->
            <?php 
            // Only show module debug if:
            // 1. WP_DEBUG is enabled
            // 2. Debug monitoring toggle is enabled
            // 3. We're on a submodule page (not home page)
            $is_debug_enabled = defined('WP_DEBUG') && WP_DEBUG;
            $is_monitoring_enabled = get_option('igny8_debug_enabled', false);
            $is_submodule_page = !empty($_GET['sm']) || !empty($GLOBALS['current_submodule']);
            
            if ($is_debug_enabled && $is_monitoring_enabled && $is_submodule_page) {
                require_once plugin_dir_path(__FILE__) . '../debug/module-debug.php';
                $debug_content = igny8_get_module_debug_content();
                if (!empty($debug_content)) {
                    echo $debug_content;
                }
            }
            ?>
        </main>
        
        <!-- FOOTER SECTION -->
        <footer class="igny8-footer">
            <div class="igny8-footer-content">
                <span>&copy; <?php echo date('Y'); ?> Igny8 Plugin</span>
            </div>
        </footer>
    </div>
</div>