<?php
/**
 * VMPFence Logging & Analytics Administration Page
 *
 * @package VMPFence
 * @since 2.1.0
 */

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

// Ensure tables exist before displaying page
if (class_exists('VMPFence_Logging_Database') && !VMPFence_Logging_Database::tables_exist()) {
    echo '<div class="notice notice-warning"><p><strong>VMPFence Logging:</strong> Database tables are being created. Please refresh the page in a moment.</p></div>';
    VMPFence_Logging_Database::ensure_tables_exist();
}

// Get logging service instance
$logging_service = VMPFence_Logging_Service::get_instance();

// Handle filter submissions
$filters = array(
    'severity' => isset($_GET['filter_severity']) ? sanitize_text_field($_GET['filter_severity']) : '',
    'category' => isset($_GET['filter_category']) ? sanitize_text_field($_GET['filter_category']) : '',
    'date_from' => isset($_GET['filter_date_from']) ? sanitize_text_field($_GET['filter_date_from']) : '',
    'date_to' => isset($_GET['filter_date_to']) ? sanitize_text_field($_GET['filter_date_to']) : '',
    'limit' => isset($_GET['filter_limit']) ? absint($_GET['filter_limit']) : 50,
);

// Handle actions
if (isset($_POST['vmpfence_logging_action'])) {
    check_admin_referer('vmpfence_logging_action');
    
    $action = sanitize_text_field($_POST['vmpfence_logging_action']);
    
    switch ($action) {
        case 'test_logging':
            $result = VMPFence_Logging_Service::log(
                'test_event',
                'info',
                array(
                    'message' => 'Test event from admin panel - triggered at ' . current_time('mysql'),
                    'test_data' => true,
                    'triggered_by' => 'admin_panel',
                    'user_id' => get_current_user_id()
                ),
                null
            );
            if ($result) {
                echo '<div class="notice notice-success"><p>Test event logged successfully! Event ID: ' . esc_html($result) . '</p></div>';
            } else {
                echo '<div class="notice notice-error"><p>Error logging test event.</p></div>';
            }
            break;
            
        case 'export_logs':
            $export_api_key = VMPFence_Config::get('central_api_key', '');
            $export_format = isset($_POST['export_format']) ? sanitize_text_field($_POST['export_format']) : 'json';
            $export_filters = array(
                'start_date' => isset($_POST['export_date_from']) ? sanitize_text_field($_POST['export_date_from']) : '',
                'end_date' => isset($_POST['export_date_to']) ? sanitize_text_field($_POST['export_date_to']) : '',
            );
            $api_client = new VMPFence_API_Client();
            $export_result = $api_client->export_logs($export_api_key, $export_format, $export_filters);
            if (!is_wp_error($export_result)) {
                // Store export data in transient for download
                $transient_key = 'vmpfence_export_' . md5(wp_json_encode($export_result));
                set_transient($transient_key, $export_result, 300); // 5 minutes
                
                // Build download URL
                $download_url = add_query_arg(array(
                    'action' => 'vmpfence_download_export',
                    'key' => $transient_key,
                    'format' => $export_format,
                    'nonce' => wp_create_nonce('vmpfence_download')
                ), admin_url('admin-ajax.php'));
                
                // Use JavaScript redirect to avoid headers already sent
                echo '<script>window.location.href = ' . wp_json_encode($download_url) . ';</script>';
                exit;
            } else {
                echo '<div class="notice notice-error"><p>Error exporting logs: ' . esc_html($export_result->get_error_message()) . '</p></div>';
            }
            break;
    }
}

// Get API key
$api_key = VMPFence_Config::get('central_api_key', '');

// Check if API key is configured
$api_configured = !empty($api_key);

// Check API availability by pinging it (with caching to avoid repeated checks)
$api_available = false;
if ($api_configured) {
    // Check transient cache first (avoid pinging on every page load)
    $cached_status = get_transient('vmpfence_api_status');
    
    if ($cached_status !== false) {
        // Use cached status
        $api_available = ($cached_status === 'online');
    } else {
        // Ping API to check availability
        $api_client = new VMPFence_API_Client();
        $ping_result = $api_client->ping_api_key($api_key);
        
        if (!is_wp_error($ping_result) && isset($ping_result['is_valid']) && $ping_result['is_valid']) {
            $api_available = true;
            set_transient('vmpfence_api_status', 'online', 60); // Cache for 1 minute
        } else {
            $api_available = false;
            set_transient('vmpfence_api_status', 'offline', 60); // Cache for 1 minute
        }
    }
}

// Initialize variables
$analytics = null;
$daily_stats = null;
$retention_policy = null;

// Generate timeline data from local events (last 7 days)
$timeline_data = array('timeline' => array());
for ($i = 6; $i >= 0; $i--) {
    $date = date('Y-m-d', strtotime("-{$i} days"));
    $label = date('M j', strtotime($date));
    
    global $wpdb;
    $events_table = $wpdb->prefix . 'vmpfence_api_logs';
    $count = (int) $wpdb->get_var($wpdb->prepare(
        "SELECT COUNT(*) FROM {$events_table} WHERE DATE(created_at) = %s",
        $date
    ));
    
    $timeline_data['timeline'][] = array(
        'date' => $label,
        'count' => $count
    );
}

// Get local analytics from WordPress database (works offline)
$logging_service = VMPFence_Logging_Service::get_instance();

// Get analytics for today
$analytics_today = $logging_service->get_dashboard_analytics('today');
$analytics_week = $logging_service->get_dashboard_analytics('week');
$analytics_month = $logging_service->get_dashboard_analytics('month');

// Get database statistics
require_once VMPFENCE_PLUGIN_DIR . 'includes/class-database.php';
$database = new VMPFence_Logging_Database();
$db_stats = $database->get_stats();

// Initialize variables for old batch system (no longer used in local-first architecture)
$batch_count = 0;
$time_since_flush = 0;

$local_analytics = array(
    'total_events' => $analytics_month['total_events'],
    'critical_events' => $analytics_month['critical_events'],
    'events_today' => $analytics_today['total_events'],
    'events_this_week' => $analytics_week['total_events'],
    'unsynced_events' => $db_stats['unsynced_events'],
    'total_events_db' => $db_stats['total_events'],
);

// Set analytics for display (use month data as default)
$analytics = $analytics_month;

// Always use local analytics (local-first approach)
$display_stats = $local_analytics;

// Get distinct event types from database for filter dropdown (last 30 days)
$events_table = $wpdb->prefix . 'vmpfence_api_logs';
$db_event_stats = $wpdb->get_results(
    "SELECT 
        event_type,
        COUNT(*) as count
    FROM {$events_table}
    WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
    GROUP BY event_type
    ORDER BY count DESC"
);

// Combine with expected event types (always show common categories)
$expected_event_types = array(
    'firewall_block' => 'Firewall Block',
    'firewall_allow' => 'Firewall Allow',
    'xss_detected' => 'XSS Detected',
    'sqli_detected' => 'SQLi Detected',
    'malware_detected' => 'Malware Detected',
    'scan_completed' => 'Scan Completed',
    'ip_blocked' => 'IP Blocked',
    'user_login_success' => 'Login Success',
    'login_failed' => 'Login Failed',
    'plugin_activated' => 'Plugin Activated',
    'plugin_deactivated' => 'Plugin Deactivated',
    'user_registered' => 'User Registered',
    'admin_user_created' => 'Admin User Created',
    'theme_switched' => 'Theme Switched',
    'file_uploaded' => 'File Uploaded',
    'test_event' => 'Test Event',
);

// Build event stats array with counts from database
$event_stats = array();
foreach ($db_event_stats as $stat) {
    $event_stats[$stat->event_type] = (object) array(
        'event_type' => $stat->event_type,
        'count' => $stat->count,
        'display_name' => isset($expected_event_types[$stat->event_type]) 
            ? $expected_event_types[$stat->event_type]
            : ucwords(str_replace('_', ' ', $stat->event_type))
    );
}

// Add expected types with 0 count if not in database
foreach ($expected_event_types as $type => $name) {
    if (!isset($event_stats[$type])) {
        $event_stats[$type] = (object) array(
            'event_type' => $type,
            'count' => 0,
            'display_name' => $name
        );
    }
}

// Fetch filtered events from local database if filters are applied
$filtered_events = null;
if (!empty($filters['severity']) || !empty($filters['category']) || !empty($filters['date_from']) || !empty($filters['date_to'])) {
    global $wpdb;
    $events_table = $wpdb->prefix . 'vmpfence_api_logs';
    
    // Build WHERE clause
    $where_conditions = array('1=1');
    $query_params = array();
    
    if (!empty($filters['severity'])) {
        $where_conditions[] = 'severity = %s';
        $query_params[] = $filters['severity'];
    }
    
    if (!empty($filters['category'])) {
        $where_conditions[] = 'event_type = %s';
        $query_params[] = $filters['category'];
    }
    
    if (!empty($filters['date_from'])) {
        $where_conditions[] = 'DATE(created_at) >= %s';
        $query_params[] = $filters['date_from'];
    }
    
    if (!empty($filters['date_to'])) {
        $where_conditions[] = 'DATE(created_at) <= %s';
        $query_params[] = $filters['date_to'];
    }
    
    $where_clause = implode(' AND ', $where_conditions);
    $limit = absint($filters['limit']);
    
    // Build and execute query
    if (!empty($query_params)) {
        $query = "SELECT * FROM {$events_table} WHERE {$where_clause} ORDER BY created_at DESC LIMIT {$limit}";
        $prepared_query = $wpdb->prepare($query, $query_params);
    } else {
        $query = "SELECT * FROM {$events_table} WHERE {$where_clause} ORDER BY created_at DESC LIMIT {$limit}";
        $prepared_query = $query;
    }
    
    $events = $wpdb->get_results($prepared_query, ARRAY_A);
    
    // Format events for display
    $formatted_events = array();
    if ($events) {
        foreach ($events as $event) {
            $formatted_events[] = array(
                'id' => $event['id'],
                'event_type' => $event['event_type'],
                'severity' => $event['severity'],
                'message' => $event['message'],
                'created_at' => $event['created_at'],
                'timestamp' => $event['created_at'],
                'ip_address' => $event['ip_address'],
                'event_data' => !empty($event['metadata']) ? json_decode($event['metadata'], true) : array()
            );
        }
    }
    
    $filtered_events = array(
        'events' => $formatted_events,
        'total' => count($formatted_events),
        'source' => 'local'
    );
}

?>

<div class="wrap vmpfence-logging-analytics">
    <h1><?php echo esc_html(get_admin_page_title()); ?></h1>
    
    <?php if (!$api_configured): ?>
        <div class="notice notice-warning">
            <p><strong>API Not Configured:</strong> Please configure your API key in the <a href="<?php echo esc_url(admin_url('admin.php?page=vmpfence-dashboard')); ?>">setup wizard</a> to enable full logging and analytics features.</p>
        </div>
    <?php elseif ($api_configured && !$api_available): ?>
        <div class="notice notice-info">
            <p><strong>Working Offline:</strong> The remote API is currently unavailable. Showing local data only. Remote features (historical analytics, exports) will be available when the API is accessible.</p>
        </div>
    <?php endif; ?>
    
    <!-- Stats Overview -->
    <div class="vmpfence-stats-grid">
        <div class="stat-box">
            <div class="stat-icon">📊</div>
            <div class="stat-content">
                <div class="stat-value"><?php echo esc_html(number_format($display_stats['total_events'] ?? 0)); ?></div>
                <div class="stat-label">Total Events <?php echo !$api_available ? '(Local)' : ''; ?></div>
            </div>
        </div>
        
        <div class="stat-box critical">
            <div class="stat-icon">🚨</div>
            <div class="stat-content">
                <div class="stat-value"><?php echo esc_html(number_format($display_stats['critical_events'] ?? 0)); ?></div>
                <div class="stat-label">Critical Events <?php echo !$api_available ? '(Local)' : ''; ?></div>
            </div>
        </div>
        
        <div class="stat-box warning">
            <div class="stat-icon">⚠️</div>
            <div class="stat-content">
                <div class="stat-value"><?php echo esc_html(number_format($display_stats['events_today'] ?? 0)); ?></div>
                <div class="stat-label">Events Today <?php echo !$api_available ? '(Local)' : ''; ?></div>
            </div>
        </div>
        
        <div class="stat-box success">
            <div class="stat-icon">✅</div>
            <div class="stat-content">
                <div class="stat-value"><?php echo esc_html(number_format($display_stats['events_this_week'] ?? 0)); ?></div>
                <div class="stat-label">Events This Week <?php echo !$api_available ? '(Local)' : ''; ?></div>
            </div>
        </div>
    </div>

    <!-- Batch Queue Status -->
    <div class="vmpfence-section">
        <h2>Batch Queue Status</h2>
        <div class="queue-status">
            <p><strong>Queued Events:</strong> <?php echo esc_html($batch_count); ?> / 50</p>
            <p><strong>Last Flush:</strong> <?php echo esc_html($time_since_flush); ?> ago</p>
            <p><strong>Auto-flush:</strong> Every 5 minutes or at 50 events</p>
            
            <?php if ($api_configured): ?>
                <?php if ($batch_count > 0): ?>
                    <form method="post" style="display: inline;">
                        <?php wp_nonce_field('vmpfence_logging_action'); ?>
                        <input type="hidden" name="vmpfence_logging_action" value="flush_batch">
                        <button type="submit" class="button button-secondary">Flush Queue Now</button>
                    </form>
                <?php endif; ?>
                
                <form method="post" style="display: inline; margin-left: 10px;">
                    <?php wp_nonce_field('vmpfence_logging_action'); ?>
                    <input type="hidden" name="vmpfence_logging_action" value="test_logging">
                    <button type="submit" class="button button-secondary">Send Test Event</button>
                </form>
            <?php else: ?>
                <p class="description">API key required to use logging features</p>
            <?php endif; ?>
        </div>
    </div>

    <!-- Event Timeline Chart -->
    <?php if (!is_wp_error($timeline_data) && !empty($timeline_data['timeline'])): ?>
    <div class="vmpfence-section">
        <h2>Event Timeline (Last 7 Days)</h2>
        <div class="timeline-chart">
            <canvas id="timeline-chart" width="800" height="300"></canvas>
        </div>
    </div>
    <?php endif; ?>

    <!-- Severity Breakdown -->
    <?php if (isset($analytics['events_by_severity'])): ?>
    <div class="vmpfence-section">
        <h2>Severity Breakdown</h2>
        <div class="severity-bars">
            <?php 
            // Use the correct total from analytics
            $analytics_total = isset($analytics['total_events']) && $analytics['total_events'] > 0 
                ? $analytics['total_events'] 
                : array_sum($analytics['events_by_severity']);
            ?>
            <?php foreach ($analytics['events_by_severity'] as $severity => $count): ?>
                <?php 
                $percentage = $analytics_total > 0 ? ($count / $analytics_total) * 100 : 0;
                $severity_class = strtolower($severity);
                ?>
                <div class="severity-row">
                    <span class="severity-label <?php echo esc_attr($severity_class); ?>">
                        <?php echo esc_html(ucfirst($severity)); ?>
                    </span>
                    <div class="severity-bar-container">
                        <div class="severity-bar <?php echo esc_attr($severity_class); ?>" 
                             style="width: <?php echo esc_attr($percentage); ?>%"></div>
                    </div>
                    <span class="severity-count"><?php echo esc_html(number_format($count)); ?></span>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <?php endif; ?>

    <!-- Event Filters -->
    <div class="vmpfence-section">
        <h2>Event Filters</h2>
        <form method="get" class="event-filters">
            <input type="hidden" name="page" value="vmpfence-logging-analytics">
            
            <div class="filter-row">
                <label>
                    Severity:
                    <select name="filter_severity">
                        <option value="">All</option>
                        <option value="critical" <?php selected($filters['severity'], 'critical'); ?>>Critical</option>
                        <option value="error" <?php selected($filters['severity'], 'error'); ?>>Error</option>
                        <option value="warning" <?php selected($filters['severity'], 'warning'); ?>>Warning</option>
                        <option value="info" <?php selected($filters['severity'], 'info'); ?>>Info</option>
                    </select>
                </label>
                
                <label>
                    Category:
                    <select name="filter_category">
                        <option value=""><?php _e('All Categories', 'vmpfence-security'); ?></option>
                        <?php if (!empty($event_stats)): ?>
                            <?php foreach ($event_stats as $stat): ?>
                                <option value="<?php echo esc_attr($stat->event_type); ?>" <?php selected($filters['category'], $stat->event_type); ?>>
                                    <?php echo esc_html($stat->display_name); ?> (<?php echo esc_html($stat->count); ?>)
                                </option>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </select>
                </label>
                
                <label>
                    Date From:
                    <input type="date" name="filter_date_from" value="<?php echo esc_attr($filters['date_from']); ?>">
                </label>
                
                <label>
                    Date To:
                    <input type="date" name="filter_date_to" value="<?php echo esc_attr($filters['date_to']); ?>">
                </label>
                
                <label>
                    Limit:
                    <select name="filter_limit">
                        <option value="25" <?php selected($filters['limit'], 25); ?>>25</option>
                        <option value="50" <?php selected($filters['limit'], 50); ?>>50</option>
                        <option value="100" <?php selected($filters['limit'], 100); ?>>100</option>
                        <option value="250" <?php selected($filters['limit'], 250); ?>>250</option>
                    </select>
                </label>
                
                <button type="submit" class="button button-primary">Apply Filters</button>
                <a href="?page=vmpfence-logging-analytics" class="button">Reset</a>
            </div>
        </form>
        
        <?php 
        // Display filtered events if filters are applied (works offline with local data)
        if (isset($filtered_events) && !is_wp_error($filtered_events) && !empty($filtered_events['events'])): 
        ?>
            <div style="margin-top: 20px;">
                <h3>Filtered Results (<?php echo count($filtered_events['events']); ?> events)</h3>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th>Timestamp</th>
                            <th>Severity</th>
                            <th>Category</th>
                            <th>Message</th>
                            <th>Details</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($filtered_events['events'] as $event): 
                            // Extract category from event_type
                            $category = $event['event_type'] ?? 'N/A';
                            
                            // Extract message from event_data
                            $message = '';
                            if (!empty($event['event_data'])) {
                                if (isset($event['event_data']['message'])) {
                                    $message = $event['event_data']['message'];
                                } elseif (isset($event['event_data']['rule_description'])) {
                                    $message = $event['event_data']['rule_description'];
                                } elseif (isset($event['event_data']['url'])) {
                                    $message = 'Request: ' . $event['event_data']['url'];
                                } elseif (isset($event['event_data']['ip'])) {
                                    $message = 'IP: ' . $event['event_data']['ip'];
                                } else {
                                    $first_key = array_key_first($event['event_data']);
                                    if ($first_key) {
                                        $first_value = $event['event_data'][$first_key];
                                        if (is_string($first_value) && strlen($first_value) < 100) {
                                            $message = ucfirst($first_key) . ': ' . $first_value;
                                        } else {
                                            $message = count($event['event_data']) . ' data fields';
                                        }
                                    }
                                }
                            }
                            
                            $metadata = $event['event_data'] ?? array();
                        ?>
                            <tr>
                                <td><?php echo esc_html(date('Y-m-d H:i:s', strtotime($event['timestamp'] ?? $event['created_at'] ?? ''))); ?></td>
                                <td>
                                    <span class="severity-badge <?php echo esc_attr(strtolower($event['severity'] ?? 'info')); ?>">
                                        <?php echo esc_html(ucfirst($event['severity'] ?? 'info')); ?>
                                    </span>
                                </td>
                                <td><?php echo esc_html(ucfirst(str_replace('_', ' ', $category))); ?></td>
                                <td><?php echo esc_html($message); ?></td>
                                <td>
                                    <?php if (!empty($metadata)): ?>
                                        <button type="button" class="button button-small view-details" 
                                                data-details="<?php echo esc_attr(wp_json_encode($metadata)); ?>">
                                            View Details
                                        </button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php elseif (!empty($filters['severity']) || !empty($filters['category']) || !empty($filters['date_from']) || !empty($filters['date_to'])): ?>
            <div style="margin-top: 20px;">
                <p class="description">No events found matching your filters. Try adjusting the filter criteria.</p>
            </div>
        <?php endif; ?>
    </div>

    <!-- Recent Events Table -->
    <div class="vmpfence-section">
        <h2>Recent Events</h2>
        <?php
        if ($api_configured && $api_available) {
            // Determine which events to display - filtered or timeline
            $events_to_display = null;
            $events_source = 'timeline';
            
            if (isset($filtered_events) && !is_wp_error($filtered_events) && !empty($filtered_events['events'])) {
                $events_to_display = $filtered_events['events'];
                $events_source = 'filtered';
            } elseif (!is_wp_error($timeline_data) && !empty($timeline_data['events'])) {
                $events_to_display = $timeline_data['events'];
                $events_source = 'timeline';
            }
            
            // Display events table if we have events
            if (!empty($events_to_display)):
            ?>
                <?php if ($events_source === 'filtered'): ?>
                    <p class="description">Showing filtered results (<?php echo count($events_to_display); ?> events):</p>
                <?php endif; ?>
                
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th>Timestamp</th>
                            <th>Severity</th>
                            <th>Category</th>
                            <th>Message</th>
                            <th>Details</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($events_to_display as $event): 
                            // Extract category from event_type (API returns event_type, not category)
                            $category = $event['event_type'] ?? 'N/A';
                            
                            // Extract message from event_data (API returns event_data dict, not message string)
                            $message = '';
                            if (!empty($event['event_data'])) {
                                // Check for common message fields in event_data
                                if (isset($event['event_data']['message'])) {
                                    $message = $event['event_data']['message'];
                                } elseif (isset($event['event_data']['rule_description'])) {
                                    $message = $event['event_data']['rule_description'];
                                } elseif (isset($event['event_data']['url'])) {
                                    $message = 'Request: ' . $event['event_data']['url'];
                                } elseif (isset($event['event_data']['ip'])) {
                                    $message = 'IP: ' . $event['event_data']['ip'];
                                } else {
                                    // Fallback: show first key-value pair or count of data
                                    $first_key = array_key_first($event['event_data']);
                                    if ($first_key) {
                                        $first_value = $event['event_data'][$first_key];
                                        if (is_string($first_value) && strlen($first_value) < 100) {
                                            $message = ucfirst($first_key) . ': ' . $first_value;
                                        } else {
                                            $message = count($event['event_data']) . ' data fields';
                                        }
                                    }
                                }
                            }
                            
                            // Use event_data as metadata for details button
                            $metadata = $event['event_data'] ?? array();
                        ?>
                            <tr>
                                <td><?php echo esc_html(date('Y-m-d H:i:s', strtotime($event['timestamp'] ?? ''))); ?></td>
                                <td>
                                    <span class="severity-badge <?php echo esc_attr(strtolower($event['severity'] ?? 'info')); ?>">
                                        <?php echo esc_html(ucfirst($event['severity'] ?? 'info')); ?>
                                    </span>
                                </td>
                                <td><?php echo esc_html(ucfirst(str_replace('_', ' ', $category))); ?></td>
                                <td><?php echo esc_html($message); ?></td>
                                <td>
                                    <?php if (!empty($metadata)): ?>
                                        <button type="button" class="button button-small view-details" 
                                                data-details="<?php echo esc_attr(wp_json_encode($metadata)); ?>">
                                            View Details
                                        </button>
                                    <?php endif; ?>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            <?php else: ?>
                <p><?php echo $events_source === 'filtered' ? 'No events found matching your filters.' : 'No events found in the API.'; ?></p>
            <?php endif;
        } elseif ($api_configured && !$api_available) {
            // Show local queued events
            if ($batch_count > 0):
            ?>
                <p class="description">Showing <?php echo esc_html($batch_count); ?> queued event(s) waiting to be sent to the API:</p>
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th>Severity</th>
                            <th>Category</th>
                            <th>Message</th>
                            <th>Queued At</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach (array_slice($batch_queue, 0, 10) as $queued_event): ?>
                            <tr>
                                <td>
                                    <span class="severity-badge <?php echo esc_attr(strtolower($queued_event['severity'] ?? 'info')); ?>">
                                        <?php echo esc_html(ucfirst($queued_event['severity'] ?? 'info')); ?>
                                    </span>
                                </td>
                                <td><?php echo esc_html(ucfirst($queued_event['category'] ?? 'N/A')); ?></td>
                                <td><?php echo esc_html($queued_event['message'] ?? ''); ?></td>
                                <td><?php echo esc_html(date('Y-m-d H:i:s', $queued_event['timestamp'] ?? current_time('timestamp'))); ?></td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <?php if ($batch_count > 10): ?>
                    <p class="description">Showing first 10 of <?php echo esc_html($batch_count); ?> queued events.</p>
                <?php endif; ?>
            <?php else: ?>
                <p>No events in local queue. Events will appear here when logged.</p>
            <?php endif;
        } else {
            ?>
            <p class="description">API not configured. Please set up your API key to view events.</p>
        <?php } ?>
    </div>

    <!-- Export Section -->
    <div class="vmpfence-section">
        <h2>Export Logs</h2>
        <form method="post" class="export-form">
            <?php wp_nonce_field('vmpfence_logging_action'); ?>
            <input type="hidden" name="vmpfence_logging_action" value="export_logs">
            
            <div class="filter-row">
                <label>
                    Date From:
                    <input type="date" name="export_date_from" value="<?php echo esc_attr(date('Y-m-d', strtotime('-30 days'))); ?>">
                </label>
                
                <label>
                    Date To:
                    <input type="date" name="export_date_to" value="<?php echo esc_attr(date('Y-m-d')); ?>">
                </label>
                
                <label>
                    Format:
                    <select name="export_format">
                        <option value="json">JSON</option>
                        <option value="csv">CSV</option>
                    </select>
                </label>
                
                <button type="submit" class="button button-primary">Export Logs</button>
            </div>
        </form>
    </div>

    <!-- Retention Policy -->
    <?php if (!is_wp_error($retention_policy)): ?>
    <div class="vmpfence-section">
        <h2>Data Retention Policy</h2>
        <div class="retention-info">
            <p><strong>Retention Period:</strong> <?php echo esc_html($retention_policy['retention_days'] ?? 90); ?> days</p>
            <p><strong>Oldest Event:</strong> <?php echo esc_html($retention_policy['oldest_event'] ?? 'N/A'); ?></p>
            <p><strong>Storage Used:</strong> <?php echo esc_html($retention_policy['storage_mb'] ?? 'N/A'); ?> MB</p>
            <p><em>Events older than the retention period are automatically deleted.</em></p>
        </div>
    </div>
    <?php endif; ?>
</div>

<!-- Event Details Modal -->
<div id="event-details-modal" class="vmpfence-modal" style="display: none;">
    <div class="modal-content">
        <span class="close">&times;</span>
        <h2>Event Details</h2>
        <pre id="event-details-content"></pre>
    </div>
</div>

<style>
.vmpfence-logging-analytics {
    max-width: 1400px;
}

.vmpfence-stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
    gap: 20px;
    margin: 20px 0;
}

.stat-box {
    background: #fff;
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 20px;
    display: flex;
    align-items: center;
    gap: 15px;
    box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.stat-box.critical {
    border-left: 4px solid #dc3232;
}

.stat-box.warning {
    border-left: 4px solid #f0ad4e;
}

.stat-box.success {
    border-left: 4px solid #46b450;
}

.stat-icon {
    font-size: 32px;
}

.stat-value {
    font-size: 28px;
    font-weight: bold;
    color: #1d2327;
}

.stat-label {
    font-size: 14px;
    color: #757575;
    text-transform: uppercase;
}

.vmpfence-section {
    background: #fff;
    border: 1px solid #ddd;
    border-radius: 8px;
    padding: 20px;
    margin: 20px 0;
}

.vmpfence-section h2 {
    margin-top: 0;
    border-bottom: 2px solid #0073aa;
    padding-bottom: 10px;
}

.queue-status p {
    margin: 10px 0;
}

.severity-bars {
    margin: 20px 0;
}

.severity-row {
    display: flex;
    align-items: center;
    gap: 15px;
    margin: 15px 0;
}

.severity-label {
    min-width: 80px;
    font-weight: 600;
    text-transform: uppercase;
    font-size: 12px;
}

.severity-label.critical {
    color: #dc3232;
}

.severity-label.high {
    color: #d63638;
}

.severity-label.medium {
    color: #f0ad4e;
}

.severity-label.low {
    color: #46b450;
}

.severity-label.error {
    color: #d63638;
}

.severity-label.warning {
    color: #f0ad4e;
}

.severity-label.info {
    color: #0073aa;
}

.severity-bar-container {
    flex: 1;
    background: #f0f0f1;
    height: 24px;
    border-radius: 4px;
    overflow: hidden;
}

.severity-bar {
    height: 100%;
    transition: width 0.3s ease;
}

.severity-bar.critical {
    background: #dc3232;
}

.severity-bar.high {
    background: #d63638;
}

.severity-bar.medium {
    background: #f0ad4e;
}

.severity-bar.low {
    background: #46b450;
}

.severity-bar.error {
    background: #d63638;
}

.severity-bar.warning {
    background: #f0ad4e;
}

.severity-bar.info {
    background: #0073aa;
}

.severity-count {
    min-width: 60px;
    text-align: right;
    font-weight: 600;
}

.event-filters,
.export-form {
    margin: 15px 0;
}

.filter-row {
    display: flex;
    gap: 15px;
    align-items: end;
    flex-wrap: wrap;
}

.filter-row label {
    display: flex;
    flex-direction: column;
    gap: 5px;
}

.severity-badge {
    padding: 4px 8px;
    border-radius: 4px;
    font-size: 11px;
    font-weight: 600;
    text-transform: uppercase;
    color: #fff !important;
    display: inline-block;
}

.severity-badge.critical {
    background: #dc3232 !important;
}

.severity-badge.error {
    background: #d63638 !important;
}

.severity-badge.warning {
    background: #f0ad4e !important;
    color: #333 !important;
}

.severity-badge.info {
    background: #0073aa !important;
}

.vmpfence-modal {
    position: fixed;
    z-index: 100000;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0,0,0,0.5);
}

.modal-content {
    background-color: #fff;
    margin: 5% auto;
    padding: 20px;
    border: 1px solid #888;
    border-radius: 8px;
    width: 80%;
    max-width: 800px;
    max-height: 80vh;
    overflow-y: auto;
}

.close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
    cursor: pointer;
}

.close:hover,
.close:focus {
    color: #000;
}

#event-details-content {
    background: #f5f5f5;
    padding: 15px;
    border-radius: 4px;
    overflow-x: auto;
}

.timeline-chart {
    margin: 20px 0;
    min-height: 300px;
}

.retention-info p {
    margin: 10px 0;
}

.error {
    color: #d63638;
    font-style: italic;
}
</style>

<script>
jQuery(document).ready(function($) {
    // View details modal
    $('.view-details').on('click', function() {
        var details = $(this).data('details');
        $('#event-details-content').text(JSON.stringify(details, null, 2));
        $('#event-details-modal').show();
    });
    
    $('.close').on('click', function() {
        $('#event-details-modal').hide();
    });
    
    $(window).on('click', function(event) {
        if (event.target.id === 'event-details-modal') {
            $('#event-details-modal').hide();
        }
    });
    
    // Simple timeline chart (if canvas available)
    <?php if (!is_wp_error($timeline_data) && !empty($timeline_data['timeline'])): ?>
    var canvas = document.getElementById('timeline-chart');
    if (canvas && canvas.getContext) {
        var ctx = canvas.getContext('2d');
        var timelineData = <?php echo wp_json_encode($timeline_data['timeline']); ?>;
        
        // Simple bar chart rendering
        var maxValue = Math.max(...timelineData.map(d => d.count || 0));
        var barWidth = canvas.width / timelineData.length;
        var barSpacing = 5;
        
        timelineData.forEach(function(point, index) {
            var barHeight = (point.count / maxValue) * (canvas.height - 40);
            var x = index * barWidth;
            var y = canvas.height - barHeight - 20;
            
            ctx.fillStyle = '#0073aa';
            ctx.fillRect(x + barSpacing, y, barWidth - (barSpacing * 2), barHeight);
            
            // Draw label
            ctx.fillStyle = '#333';
            ctx.font = '10px Arial';
            ctx.fillText(point.date, x + 5, canvas.height - 5);
            
            // Draw count
            ctx.fillText(point.count, x + 5, y - 5);
        });
    }
    <?php endif; ?>
});
</script>
