<?php

/**
 * Sentinel Admin Page View
 *
 * Main admin interface for viewing logs.
 */

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

global $wpdb;
$table = $wpdb->prefix . 'sentinel_logs';

// Get today's date range
$today_start = date('Y-m-d 00:00:00');
$today_end = date('Y-m-d 23:59:59');

// Role-based filtering for editors (only if enabled in settings)
$is_editor = current_user_can('edit_published_posts') && !current_user_can('manage_options');
$category_filter = '';

// Check if role-based log access is enabled in settings
$settings = get_option('sentinel_log_management', array());
// Remove IP whitelist enforcement logic
$role_based_access_enabled = !empty($settings['role_based_access']);

if ($is_editor && $role_based_access_enabled) {
    $category_filter = "AND category IN ('user', 'content', 'authentication')";
}

// Get today's stats
$today_logs = $wpdb->get_var($wpdb->prepare(
    "SELECT COUNT(*) FROM $table WHERE created_at BETWEEN %s AND %s $category_filter",
    $today_start,
    $today_end
));

$today_users = $wpdb->get_var($wpdb->prepare(
    "SELECT COUNT(DISTINCT user_id) FROM $table WHERE created_at BETWEEN %s AND %s AND user_id > 0 $category_filter",
    $today_start,
    $today_end
));

$top_event_today = $wpdb->get_row($wpdb->prepare(
    "SELECT event_key, COUNT(*) as count FROM $table
     WHERE created_at BETWEEN %s AND %s $category_filter
     GROUP BY event_key
     ORDER BY count DESC
     LIMIT 1",
    $today_start,
    $today_end
));

// Get system info
$db_size = $wpdb->get_var("SELECT ROUND(((data_length + index_length) / 1024 / 1024), 2) AS 'DB Size in MB' FROM information_schema.tables WHERE table_schema = DATABASE() AND table_name = '$table'");

// Get last 7 days activity for chart
$last_7_days = array();
for ($i = 6; $i >= 0; $i--) {
    $date = date('Y-m-d', strtotime("-$i days"));
    $start = $date . ' 00:00:00';
    $end = $date . ' 23:59:59';
    $count = $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM $table WHERE created_at BETWEEN %s AND %s $category_filter",
        $start,
        $end
    ));
    $last_7_days[] = array(
        'date' => date('M j', strtotime($date)),
        'count' => intval($count)
    );
}

// Get event distribution (last 7 days)
$event_distribution_raw = $wpdb->get_results(
    "SELECT event_key, COUNT(*) as count FROM $table
     WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY) $category_filter
     GROUP BY event_key
     ORDER BY count DESC
     LIMIT 10"
);
$event_distribution = array();
foreach ($event_distribution_raw as $row) {
    $event_distribution[] = array(
        'event_key' => $row->event_key,
        'count' => intval($row->count)
    );
}

// Get error event distribution (last 7 days) - Only for admins
$error_distribution_raw = array();
if (!$is_editor) {
    $error_distribution_raw = $wpdb->get_results(
        "SELECT event_key, COUNT(*) as count FROM $table
         WHERE created_at >= DATE_SUB(NOW(), INTERVAL 7 DAY)
         AND (event_key LIKE '%error%' OR event_key LIKE '%failed%' OR event_key IN (
             'php_fatal_error', 'php_warning', 'php_notice', 'php_deprecated',
             'wp_database_error', 'wp_memory_error', 'wp_permission_error', 'wp_config_error',
             'login_failed', 'auth_cookie_bad', 'nonce_verification_failed', 'permission_denied',
             'http_404_error', 'http_500_error', 'wp_remote_error', 'wp_cron_error',
             'plugin_error', 'theme_error', 'plugin_activation_error',
             'file_upload_error', 'file_permission_error'
         ))
         GROUP BY event_key
         ORDER BY count DESC
         LIMIT 10"
    );
}
$error_distribution = array();
foreach ($error_distribution_raw as $row) {
    $error_distribution[] = array(
        'event_key' => $row->event_key,
        'count' => intval($row->count)
    );
}

// Get recent activity (last 10 events)
$recent_activity = $wpdb->get_results(
    "SELECT * FROM $table
     WHERE 1=1 $category_filter
     ORDER BY created_at DESC
     LIMIT 10"
);
// Get usernames for display
$user_ids = array();
foreach ($recent_activity as $activity) {
    if ($activity->user_id > 0) {
        $user_ids[] = $activity->user_id;
    }
}
$user_ids = array_unique($user_ids);
$usernames = array();
if ($user_ids) {
    $placeholders = implode(',', array_fill(0, count($user_ids), '%d'));
    $users_data = $wpdb->get_results($wpdb->prepare(
        "SELECT ID, user_login, display_name FROM {$wpdb->users} WHERE ID IN ($placeholders)",
        $user_ids
    ));
    foreach ($users_data as $u) {
        $usernames[$u->ID] = $u->display_name ?: $u->user_login;
    }
}
$usernames[0] = 'Guest/Anonymous';

// Get hourly activity for the last 7 days (for heatmap)
$heatmap_data = array();
for ($i = 6; $i >= 0; $i--) {
    $date = date('Y-m-d', strtotime("-$i days"));
    $row = array('date' => $date, 'hours' => array_fill(0, 24, 0));
    $results = $wpdb->get_results($wpdb->prepare(
        "SELECT HOUR(created_at) as hour, COUNT(*) as count FROM $table WHERE created_at BETWEEN %s AND %s $category_filter GROUP BY hour",
        $date . ' 00:00:00',
        $date . ' 23:59:59'
    ));
    foreach ($results as $result) {
        $row['hours'][intval($result->hour)] = intval($result->count);
    }
    $heatmap_data[] = $row;
}
?>

<div class="wrap">
    <div class="sentinel-dashboard">
        <div class="sentinel-logo">
            <div class="sentinel-logo-card">
                <img src="<?php echo plugins_url('assets/img/Logo.png', dirname(__FILE__, 2)); ?>" alt="Sentinel Logo"
                    height="80" />
            </div>
        </div>
        <h1 class="sentinel-dashboard-title">Sentinel Dashboard</h1>

        <?php
        // Quick Setup card. Only renders while onboarding is pending and
        // the current user can manage_options (the class enforces both).
        if (class_exists('Sentinel_Admin_Onboarding')) {
            Sentinel_Admin_Onboarding::get_instance()->render_card();
        }
        ?>

        <?php if (isset($_GET['logs_cleared'])): ?>
            <div class="notice notice-success is-dismissible">
                <p><?php echo intval($_GET['logs_cleared']); ?> old log entries have been cleared successfully.</p>
            </div>
        <?php endif; ?>

        <?php if (isset($_GET['test_data_generated'])): ?>
            <div class="notice notice-success is-dismissible">
                <p><?php echo intval($_GET['test_data_generated']); ?> test log entries have been generated successfully.
                </p>
            </div>
        <?php endif; ?>

        <!-- Performance Monitor Buttons -->
        <?php
        // Get current settings for monitors
        $default_settings = array(
            'rate_limiting_enabled' => 1,
            'memory_monitoring_enabled' => 1,
            'batch_logging_enabled' => 0,
        );
        $settings = wp_parse_args(get_option('sentinel_log_management', array()), $default_settings);
        ?>

        <div class="sentinel-monitor-buttons">
            <div class="sentinel-monitor-grid">

                <!-- Rate Limiting Monitor Button -->
                <div class="sentinel-monitor-card <?php echo !empty($settings['rate_limiting_enabled']) ? 'enabled' : 'disabled'; ?>"
                    <?php echo !empty($settings['rate_limiting_enabled']) ? 'data-monitor="rate-limiting"' : 'data-tooltip="Rate limiting is disabled. Enable it in Settings → Performance to access detailed monitoring."'; ?>>
                    <div class="sentinel-monitor-icon">
                        <i class="dashicons dashicons-chart-bar"></i>
                    </div>
                    <div class="sentinel-monitor-info">
                        <h4>Rate Limiting Status</h4>
                        <p>Monitor request limits and behavior</p>
                        <span
                            class="sentinel-monitor-status <?php echo !empty($settings['rate_limiting_enabled']) ? 'active' : 'inactive'; ?>">
                            <?php echo !empty($settings['rate_limiting_enabled']) ? 'Active' : 'Disabled'; ?>
                        </span>
                    </div>
                    <div class="sentinel-monitor-action">
                        <?php if (!empty($settings['rate_limiting_enabled'])): ?>
                            <i class="dashicons dashicons-arrow-right-alt2"></i>
                        <?php else: ?>
                            <i class="dashicons dashicons-lock"></i>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Memory Insights Monitor Button -->
                <div class="sentinel-monitor-card <?php echo !empty($settings['memory_monitoring_enabled']) ? 'enabled' : 'disabled'; ?>"
                    <?php echo !empty($settings['memory_monitoring_enabled']) ? 'data-monitor="memory-insights"' : 'data-tooltip="Memory monitoring is disabled. Enable it in Settings → Performance to access advanced memory analysis."'; ?>>
                    <div class="sentinel-monitor-icon">
                        <i class="dashicons dashicons-performance"></i>
                    </div>
                    <div class="sentinel-monitor-info">
                        <h4>Memory Insights</h4>
                        <p>Advanced memory analysis and optimization</p>
                        <span
                            class="sentinel-monitor-status <?php echo !empty($settings['memory_monitoring_enabled']) ? 'active' : 'inactive'; ?>">
                            <?php echo !empty($settings['memory_monitoring_enabled']) ? 'Active' : 'Disabled'; ?>
                        </span>
                    </div>
                    <div class="sentinel-monitor-action">
                        <?php if (!empty($settings['memory_monitoring_enabled'])): ?>
                            <i class="dashicons dashicons-arrow-right-alt2"></i>
                        <?php else: ?>
                            <i class="dashicons dashicons-lock"></i>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Performance Status Monitor Button (Always Available) -->
                <div class="sentinel-monitor-card enabled" data-monitor="performance-status">
                    <div class="sentinel-monitor-icon">
                        <i class="dashicons dashicons-dashboard"></i>
                    </div>
                    <div class="sentinel-monitor-info">
                        <h4>Performance Status</h4>
                        <p>System performance and resource usage</p>
                        <span class="sentinel-monitor-status active">Always On</span>
                    </div>
                    <div class="sentinel-monitor-action">
                        <i class="dashicons dashicons-arrow-right-alt2"></i>
                    </div>
                </div>

            </div>
        </div>

        <!-- Overview Stats -->
        <div class="sentinel-stats-grid">
            <div class="sentinel-stat-card">
                <div class="sentinel-stat-icon">
                    <i class="dashicons dashicons-chart-line"></i>
                </div>
                <div class="sentinel-stat-content">
                    <div class="sentinel-stat-value"><?php echo number_format($today_logs); ?></div>
                    <div class="sentinel-stat-label">Logs Today</div>
                </div>
            </div>
            <div class="sentinel-stat-card">
                <div class="sentinel-stat-icon">
                    <i class="dashicons dashicons-groups"></i>
                </div>
                <div class="sentinel-stat-content">
                    <div class="sentinel-stat-value"><?php echo number_format($today_users); ?></div>
                    <div class="sentinel-stat-label">Active Users Today</div>
                </div>
            </div>
            <div class="sentinel-stat-card">
                <div class="sentinel-stat-icon">
                    <i class="dashicons dashicons-star-filled"></i>
                </div>
                <div class="sentinel-stat-content">
                    <div class="sentinel-stat-value">
                        <?php echo $top_event_today ? esc_html($top_event_today->event_key) : 'None'; ?></div>
                    <div class="sentinel-stat-label">Top Event Today</div>
                </div>
            </div>
            <div class="sentinel-stat-card">
                <div class="sentinel-stat-icon">
                    <i class="dashicons dashicons-database"></i>
                </div>
                <div class="sentinel-stat-content">
                    <div class="sentinel-stat-value"><?php echo $db_size ? $db_size . 'MB' : 'N/A'; ?></div>
                    <div class="sentinel-stat-label">Database Size</div>
                </div>
            </div>
            <div class="sentinel-stat-card">
                <div class="sentinel-stat-icon">
                    <i class="dashicons dashicons-backup"></i>
                </div>
                <div class="sentinel-stat-content">
                    <div class="sentinel-stat-value">30 days</div>
                    <div class="sentinel-stat-label">Retention Policy</div>
                </div>
            </div>
            <div class="sentinel-stat-card sentinel-card--premium">
                <div class="sentinel-stat-icon">
                    <i class="dashicons dashicons-lock"></i>
                </div>
                <div class="sentinel-stat-content">
                    <div class="sentinel-stat-value sentinel-premium-blur">--/--/----</div>
                    <div class="sentinel-stat-label">Oldest Log Date <span class="sentinel-premium-label">Premium</span>
                    </div>
                </div>
                <div class="sentinel-premium-overlay">
                    <span class="dashicons dashicons-lock"></span>
                </div>
            </div>
        </div>



        <!-- Charts Section -->
        <div class="sentinel-charts-section">
            <div class="sentinel-chart-container">
                <h3>Activity Timeline (Last 7 Days)</h3>
                <canvas id="activityChart" width="400" height="200"></canvas>
            </div>
            <div class="sentinel-chart-container">
                <h3>Event Distribution</h3>
                <canvas id="eventChart" width="400" height="200"></canvas>
            </div>
            <?php if (!$is_editor || !$role_based_access_enabled): ?>
                <div class="sentinel-chart-container">
                    <h3>Error Distribution (Last 7 Days)</h3>
                    <canvas id="errorChart" width="400" height="200"></canvas>
                </div>
            <?php endif; ?>
            <div class="sentinel-chart-container">
                <h3>Hourly Activity Heatmap</h3>
                <canvas id="activityHeatmap" width="400" height="200"></canvas>
            </div>
        </div>
        <!-- Recent Activity Feed -->
        <div class="sentinel-activity-feed">
            <h3>Recent Activity</h3>
            <div class="sentinel-activity-list">
                <?php if ($recent_activity): ?>
                    <?php foreach ($recent_activity as $activity): ?>
                        <div class="sentinel-activity-item">
                            <div class="sentinel-activity-icon">
                                <i
                                    class="dashicons dashicons-<?php echo sentinel_get_activity_icon($activity->event_key); ?>"></i>
                            </div>
                            <div class="sentinel-activity-content">
                                <div class="sentinel-activity-text">
                                    <?php echo sentinel_format_activity_message($activity, $usernames); ?>
                                </div>
                                <div class="sentinel-activity-meta">
                                    <span class="sentinel-activity-time">
                                        <?php echo human_time_diff(strtotime($activity->created_at), current_time('timestamp')); ?>
                                        ago
                                    </span>
                                    <span class="sentinel-activity-user">
                                        <?php echo esc_html(isset($usernames[$activity->user_id]) ? $usernames[$activity->user_id] : 'Unknown'); ?>
                                    </span>
                                    <?php
                                    // PREMIUM: Add "View Changes" button for file monitoring events
                                    if (sentinel_is_premium() && $activity->event_key === 'file_modified') {
                                        $activity_data = json_decode($activity->data, true);
                                        if (is_array($activity_data) && isset($activity_data['has_diff']) && $activity_data['has_diff']) {
                                            $baseline_id = isset($activity_data['baseline_id']) ? $activity_data['baseline_id'] : '';
                                            $filename = isset($activity_data['file_name']) ? $activity_data['file_name'] : '';

                                            if (!empty($baseline_id)) {
                                    ?>
                                                <button class="sentinel-diff-btn"
                                                    data-baseline-id="<?php echo esc_attr($baseline_id); ?>"
                                                    data-filename="<?php echo esc_attr($filename); ?>"
                                                    type="button"
                                                    title="View file changes"
                                                    style="margin-left: 8px;">
                                                    <i class="dashicons dashicons-editor-code" style="font-size: 14px; line-height: 1;"></i>
                                                </button>
                                    <?php
                                            }
                                        }
                                    }
                                    ?>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                <?php else: ?>
                    <div class="sentinel-activity-item">No recent activity found.</div>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <!-- Performance Monitor Modals -->
    <div id="sentinel-modal-overlay" class="sentinel-modal-overlay">
        <div class="sentinel-modal-container">
            <div class="sentinel-modal-header">
                <h2 id="sentinel-modal-title">Monitor Details</h2>
                <button type="button" id="sentinel-modal-close" class="sentinel-modal-close" aria-label="Close modal">
                    <span class="dashicons dashicons-no-alt"></span>
                </button>
            </div>
            <div class="sentinel-modal-content" id="sentinel-modal-content">
                <!-- Modal content will be dynamically loaded here -->
            </div>
        </div>
    </div>

    <!-- Hidden Content Divs (outside modal so they don't get overwritten) -->
    <?php
    // Define settings with defaults for modal content
    $modal_default_settings = array(
        'rate_limiting_enabled' => 1,
        'rate_limit_per_minute' => 100,
        'rate_limit_per_hour' => 1000,
        'rate_limit_behavior' => 'graceful_degradation',
        'memory_monitoring_enabled' => 1,
        'memory_limit_threshold' => 80,
        'batch_logging_enabled' => 0,
        'batch_size' => 50,
        'batch_frequency' => 60,
    );
    $modal_settings = wp_parse_args(get_option('sentinel_log_management', array()), $modal_default_settings);

    ?>

    <!-- Hidden Rate Limiting Content -->
    <div id="rate-limiting-modal-content" style="display: none;">
        <?php if (!empty($modal_settings['rate_limiting_enabled'])): ?>
            <div class="sentinel-performance-status">
                <div class="sentinel-performance-grid">
                    <?php
                    // Get current rate limiting status
                    $per_minute_limit = intval($modal_settings['rate_limit_per_minute'] ?? 100);
                    $per_hour_limit = intval($modal_settings['rate_limit_per_hour'] ?? 1000);

                    // Get current usage
                    $minute_key = 'sentinel_rate_limit_minute_' . date('Y-m-d-H-i');
                    $hour_key = 'sentinel_rate_limit_hour_' . date('Y-m-d-H');
                    $minute_count = intval(get_transient($minute_key) ?: 0);
                    $hour_count = intval(get_transient($hour_key) ?: 0);

                    // Calculate percentages
                    $minute_percent = $per_minute_limit > 0 ? ($minute_count / $per_minute_limit) * 100 : 0;
                    $hour_percent = $per_hour_limit > 0 ? ($hour_count / $per_hour_limit) * 100 : 0;

                    // Determine status classes
                    $minute_status = $minute_percent >= 90 ? 'critical' : ($minute_percent >= 80 ? 'warning' : 'good');
                    $hour_status = $hour_percent >= 90 ? 'critical' : ($hour_percent >= 80 ? 'warning' : 'good');
                    ?>

                    <div class="sentinel-performance-card">
                        <h4>📊 Per-Minute Usage</h4>
                        <p><strong><?php echo $minute_count; ?></strong> / <?php echo $per_minute_limit; ?>
                            events</p>
                        <div class="sentinel-progress-bar">
                            <div class="sentinel-progress-fill <?php echo $minute_status; ?>"
                                style="width: <?php echo min(100, $minute_percent); ?>%"></div>
                        </div>
                        <p><strong><?php echo round($minute_percent, 1); ?>%</strong> of limit used</p>

                        <?php if ($minute_percent >= 80): ?>
                            <p
                                style="color: <?php echo $minute_status === 'critical' ? '#dc2626' : '#d97706'; ?>; font-weight: 600;">
                                ⚠️ <?php echo $minute_status === 'critical' ? 'CRITICAL' : 'WARNING'; ?>:
                                Approaching rate limit!
                            </p>
                        <?php endif; ?>
                    </div>

                    <div class="sentinel-performance-card">
                        <h4>⏰ Per-Hour Usage</h4>
                        <p><strong><?php echo $hour_count; ?></strong> / <?php echo $per_hour_limit; ?> events
                        </p>
                        <div class="sentinel-progress-bar">
                            <div class="sentinel-progress-fill <?php echo $hour_status; ?>"
                                style="width: <?php echo min(100, $hour_percent); ?>%"></div>
                        </div>
                        <p><strong><?php echo round($hour_percent, 1); ?>%</strong> of limit used</p>

                        <?php if ($hour_percent >= 80): ?>
                            <p
                                style="color: <?php echo $hour_status === 'critical' ? '#dc2626' : '#d97706'; ?>; font-weight: 600;">
                                ⚠️ <?php echo $hour_status === 'critical' ? 'CRITICAL' : 'WARNING'; ?>: Approaching
                                rate limit!
                            </p>
                        <?php endif; ?>
                    </div>
                </div>

                <!-- Rate Limiting Behavior Section -->
                <div style="margin-top: 20px; padding: 15px; background: #f0f9ff; border-radius: 8px;">
                    <h4 style="margin-top: 0;">🔄 Rate Limiting Behavior</h4>
                    <?php
                    $behavior_options = array(
                        'drop_events' => array('name' => 'Drop Events', 'description' => 'Silently ignore excess events'),
                        'graceful_degradation' => array('name' => 'Graceful Degradation', 'description' => 'Reduce logging detail for less critical events'),
                        'queue_events' => array('name' => 'Queue Events', 'description' => 'Queue excess events for batch processing')
                    );
                    $current_behavior = $behavior_options[$modal_settings['rate_limit_behavior']] ?? $behavior_options['graceful_degradation'];
                    ?>

                    <p style="margin-bottom: 10px;"><strong>Current Behavior:</strong>
                        <?php echo $current_behavior['name']; ?></p>
                    <p style="margin-bottom: 10px; color: #666;"><?php echo $current_behavior['description']; ?>
                    </p>

                    <p style="margin-bottom: 10px;"><strong>Priority Protection:</strong></p>
                    <ul style="margin-left: 20px;">
                        <li><strong>Critical events:</strong> Always logged (bypasses limits)</li>
                        <li><strong>Error events:</strong> Full limit (100%)</li>
                        <li><strong>Warning events:</strong> 70% of limit</li>
                        <li><strong>Info events:</strong> 50% of limit</li>
                    </ul>
                </div>

                <p style="text-align: center; margin-top: 15px; color: #666; font-size: 13px;">
                    <em>Status refreshes on page reload. Counters reset every minute/hour.</em>
                </p>
            </div>
        <?php endif; ?>
    </div>

    <!-- Hidden Memory Insights Content -->
    <div id="memory-insights-modal-content" style="display: none;">
        <?php if (!empty($modal_settings['memory_monitoring_enabled'])): ?>
            <div class="sentinel-memory-insights">
                <?php
                // Get memory insights
                $memory_insights = array();
                if (class_exists('Sentinel_Memory_Monitor')) {
                    $monitor = new Sentinel_Memory_Monitor();
                    $memory_insights = $monitor->get_memory_insights();
                }

                // Get current memory stats
                $memory_stats = class_exists('Sentinel_Memory_Monitor') ?
                    Sentinel_Memory_Monitor::get_memory_stats() : array();
                ?>

                <div class="sentinel-performance-grid">
                    <!-- Current Memory Status -->
                    <div class="sentinel-performance-card">
                        <h4>📊 Current Memory Status</h4>
                        <?php if (!empty($memory_stats)): ?>
                            <div class="sentinel-memory-stats">
                                <div class="sentinel-memory-stat">
                                    <div class="value"
                                        style="color: <?php echo $memory_stats['usage_percent'] > 80 ? '#dc2626' : ($memory_stats['usage_percent'] > 60 ? '#d97706' : '#16a34a'); ?>;">
                                        <?php echo $memory_stats['usage_percent']; ?>%
                                    </div>
                                    <div class="label">Memory Usage</div>
                                </div>
                                <div class="sentinel-memory-stat">
                                    <div class="value"><?php echo $memory_stats['current_usage_formatted']; ?></div>
                                    <div class="label">Current Usage</div>
                                </div>
                                <div class="sentinel-memory-stat">
                                    <div class="value"><?php echo $memory_stats['peak_usage_formatted']; ?></div>
                                    <div class="label">Peak Usage</div>
                                </div>
                                <div class="sentinel-memory-stat">
                                    <div class="value"><?php echo $memory_stats['limit_formatted']; ?></div>
                                    <div class="label">Memory Limit</div>
                                </div>
                            </div>

                            <div class="sentinel-progress-bar" style="margin-top: 15px;">
                                <div class="sentinel-progress-fill <?php echo $memory_stats['usage_percent'] > 80 ? 'critical' : ($memory_stats['usage_percent'] > 60 ? 'warning' : 'good'); ?>"
                                    style="width: <?php echo min($memory_stats['usage_percent'], 100); ?>%;"></div>
                            </div>

                            <?php if ($memory_stats['usage_percent'] > 80): ?>
                                <div
                                    style="margin-top: 10px; padding: 8px; background: #fef3c7; border-radius: 4px; border-left: 3px solid #f59e0b;">
                                    <strong>⚠️ High Memory Usage!</strong> Consider optimization or increasing memory
                                    limit.
                                </div>
                            <?php endif; ?>
                        <?php else: ?>
                            <p style="color: #6b7280; font-style: italic;">Memory stats will appear here once
                                monitoring is active.</p>
                        <?php endif; ?>
                    </div>

                    <!-- Memory Insights -->
                    <div class="sentinel-performance-card">
                        <h4>🔍 Memory Analysis</h4>
                        <?php if (!empty($memory_insights['total_requests_analyzed'])): ?>
                            <div class="sentinel-memory-stats">
                                <div class="sentinel-memory-stat">
                                    <div class="value"><?php echo $memory_insights['total_requests_analyzed']; ?>
                                    </div>
                                    <div class="label">Requests Analyzed</div>
                                </div>
                                <div class="sentinel-memory-stat">
                                    <div class="value"
                                        style="color: <?php echo $memory_insights['high_memory_percentage'] > 20 ? '#dc2626' : '#16a34a'; ?>;">
                                        <?php echo $memory_insights['high_memory_percentage']; ?>%
                                    </div>
                                    <div class="label">High Memory</div>
                                </div>
                            </div>

                            <?php if (!empty($memory_insights['top_memory_hogs'])): ?>
                                <div style="margin-top: 15px;">
                                    <h5 style="margin-bottom: 10px; color: #374151;">🐷 Top Memory Consumers:</h5>
                                    <?php foreach (array_slice($memory_insights['top_memory_hogs'], 0, 3) as $hog): ?>
                                        <div
                                            style="margin-bottom: 5px; padding: 5px; background: #f3f4f6; border-radius: 3px; font-size: 12px;">
                                            <strong><?php echo esc_html($hog['operation']); ?>:</strong>
                                            <span style="color: #dc2626;"><?php echo esc_html($hog['memory_formatted']); ?></span>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        <?php else: ?>
                            <p style="color: #6b7280; font-style: italic;">
                                Gathering memory usage data...<br>
                                <small>Check back after some site activity to see insights.</small>
                            </p>
                        <?php endif; ?>
                    </div>

                    <!-- Smart Recommendations -->
                    <div class="sentinel-performance-card">
                        <h4>💡 Smart Recommendations</h4>
                        <?php if (!empty($memory_insights['recommendations'])): ?>
                            <?php foreach ($memory_insights['recommendations'] as $rec): ?>
                                <div style="margin-bottom: 10px; padding: 10px; background: #f0f9ff; border-radius: 6px;">
                                    <h5 style="margin: 0 0 5px 0; color: #0c4a6e;">
                                        <?php echo esc_html($rec['title']); ?></h5>
                                    <p style="margin: 0 0 5px 0; color: #374151; font-size: 13px;">
                                        <?php echo esc_html($rec['description']); ?></p>
                                    <?php if (!empty($rec['actions'])): ?>
                                        <ul style="margin: 0; padding-left: 15px; color: #6b7280; font-size: 12px;">
                                            <?php foreach ($rec['actions'] as $action): ?>
                                                <li><?php echo esc_html($action); ?></li>
                                            <?php endforeach; ?>
                                        </ul>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                        <?php else: ?>
                            <div
                                style="padding: 15px; background: #f0fdf4; border-radius: 6px; border-left: 3px solid #16a34a;">
                                <div style="color: #16a34a; font-weight: bold;">✅ All Good!</div>
                                <p style="margin: 5px 0 0 0; color: #166534; font-size: 13px;">
                                    No memory issues detected. Your site is running efficiently.
                                </p>
                            </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>

    <!-- Hidden Performance Status Content -->
    <div id="performance-status-modal-content" style="display: none;">

        <div class="sentinel-performance-status">
            <?php
            $memory_usage = memory_get_usage(true);
            $memory_limit_str = ini_get('memory_limit');

            // Convert memory limit to bytes
            if (function_exists('wp_convert_hr_to_bytes')) {
                $memory_limit = wp_convert_hr_to_bytes($memory_limit_str);
            } else {
                // Manual conversion fallback
                $memory_limit = $memory_limit_str;
                if (preg_match('/^(\d+)(.)$/', $memory_limit_str, $matches)) {
                    $memory_limit = $matches[1];
                    switch (strtoupper($matches[2])) {
                        case 'G':
                            $memory_limit *= 1024 * 1024 * 1024;
                            break;
                        case 'M':
                            $memory_limit *= 1024 * 1024;
                            break;
                        case 'K':
                            $memory_limit *= 1024;
                            break;
                    }
                }
            }

            $memory_percent = ($memory_usage / $memory_limit) * 100;
            $memory_usage_mb = round($memory_usage / 1024 / 1024, 1);
            $memory_limit_mb = round($memory_limit / 1024 / 1024, 1);
            ?>

            <div class="sentinel-performance-grid">
                <!-- Memory Usage Card -->
                <div class="sentinel-performance-card">
                    <h4>
                        <span
                            class="emoji"><?php echo $memory_percent > 80 ? '🔴' : ($memory_percent > 60 ? '🟡' : '🟢'); ?></span>
                        Memory Usage
                    </h4>
                    <div class="sentinel-progress-bar">
                        <div class="sentinel-progress-fill <?php echo $memory_percent > 80 ? 'critical' : ($memory_percent > 60 ? 'warning' : 'good'); ?>"
                            style="width: <?php echo min($memory_percent, 100); ?>%"></div>
                    </div>
                    <p><strong><?php echo round($memory_percent, 1); ?>%</strong> of memory limit used</p>
                    <div class="sentinel-memory-stats">
                        <div class="sentinel-memory-stat">
                            <div class="value"><?php echo $memory_usage_mb; ?>MB</div>
                            <div class="label">Used</div>
                        </div>
                        <div class="sentinel-memory-stat">
                            <div class="value"><?php echo $memory_limit_mb; ?>MB</div>
                            <div class="label">Limit</div>
                        </div>
                    </div>
                </div>

                <!-- Feature Status Card -->
                <div class="sentinel-performance-card">
                    <h4><span class="emoji">⚙️</span> Features</h4>
                    <p style="margin-bottom: 15px; color: #666;">Active monitoring systems</p>

                    <div class="sentinel-batch-stats">
                        <div class="sentinel-batch-stat">
                            <div class="value"
                                style="color: <?php echo $modal_settings['rate_limiting_enabled'] ? '#28a745' : '#dc3545'; ?>;">
                                <?php echo $modal_settings['rate_limiting_enabled'] ? '✅' : '❌'; ?>
                            </div>
                            <div class="label">Rate Limiting</div>
                        </div>
                        <div class="sentinel-batch-stat">
                            <div class="value"
                                style="color: <?php echo $modal_settings['memory_monitoring_enabled'] ? '#28a745' : '#dc3545'; ?>;">
                                <?php echo $modal_settings['memory_monitoring_enabled'] ? '✅' : '❌'; ?>
                            </div>
                            <div class="label">Memory Monitor</div>
                        </div>
                        <div class="sentinel-batch-stat">
                            <div class="value"
                                style="color: <?php echo $modal_settings['batch_logging_enabled'] ? '#28a745' : '#dc3545'; ?>;">
                                <?php echo $modal_settings['batch_logging_enabled'] ? '✅' : '❌'; ?>
                            </div>
                            <div class="label">Batch Logging</div>
                        </div>
                    </div>
                </div>

                <!-- System Health Card -->
                <div class="sentinel-performance-card">
                    <h4><span class="emoji">🚀</span> System Health</h4>
                    <p style="margin-bottom: 15px; color: #666;">Overall system status indicators</p>

                    <div class="sentinel-batch-stats">
                        <div class="sentinel-batch-stat">
                            <div class="value"
                                style="color: <?php echo $memory_percent < 80 ? '#28a745' : '#dc3545'; ?>;">
                                <?php echo $memory_percent < 80 ? '✅' : '⚠️'; ?>
                            </div>
                            <div class="label">Memory Health</div>
                        </div>
                        <div class="sentinel-batch-stat">
                            <div class="value" style="color: #28a745;">✅</div>
                            <div class="label">Monitoring</div>
                        </div>
                        <div class="sentinel-batch-stat">
                            <div class="value" style="color: #28a745;">🟢</div>
                            <div class="label">Status</div>
                        </div>
                    </div>
                </div>
            </div>

            <?php if ($modal_settings['memory_monitoring_enabled'] && $memory_percent > $modal_settings['memory_limit_threshold']): ?>
                <div class="sentinel-performance-card"
                    style="margin-top: 20px; background: #fff3cd; border: 1px solid #ffc107;">
                    <h4 style="color: #856404;"><span class="emoji">⚠️</span> Memory Usage Warning</h4>
                    <p style="color: #856404;">
                        Current usage (<?php echo round($memory_percent, 1); ?>%) exceeds your threshold
                        (<?php echo $modal_settings['memory_limit_threshold']; ?>%).
                        Consider optimizing or increasing memory limits.
                    </p>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
    // Pass data to JavaScript
    window.sentinelDashboardData = {
        activityData: <?php echo json_encode($last_7_days); ?>,
        eventData: <?php echo json_encode($event_distribution); ?>,
        errorData: <?php echo json_encode($error_distribution); ?>,
        heatmapData: <?php echo json_encode($heatmap_data); ?>
    };
</script>
