<?php
/**
 * Sentinel Settings Page View
 * 
 * Plugin settings and configuration interface.
 */

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

// Manual table creation removed - tables should be created automatically


// Handle form submission
if (isset($_POST['submit']) && wp_verify_nonce($_POST['sentinel_settings_nonce'], 'sentinel_settings')) {
    // Log Management & Retention settings
    $log_settings = array(
        'cleanup_enabled' => isset($_POST['cleanup_enabled']) ? 1 : 0,
        'cleanup_age_days' => absint($_POST['cleanup_age_days'] ?? 30),
        'cleanup_max_entries' => absint($_POST['cleanup_max_entries'] ?? 10000),
        'archive_retention_type' => sanitize_text_field($_POST['archive_retention_type'] ?? 'days'),
        'archive_retention_days' => absint($_POST['archive_retention_days'] ?? 365),
        'db_optimization_enabled' => isset($_POST['db_optimization_enabled']) ? 1 : 0,
        'db_optimization_schedule' => sanitize_text_field($_POST['db_optimization_schedule'] ?? 'weekly'),
        'cleanup_schedule' => sanitize_text_field($_POST['cleanup_schedule'] ?? 'daily'),
        'ip_whitelist' => sanitize_textarea_field($_POST['ip_whitelist'] ?? '')
    );
    
    // Validation
    if ($log_settings['cleanup_age_days'] < 1) {
        $log_settings['cleanup_age_days'] = 30;
    }
    if ($log_settings['cleanup_max_entries'] < 100) {
        $log_settings['cleanup_max_entries'] = 1000;
    }
    if ($log_settings['archive_retention_days'] < 1 && $log_settings['archive_retention_type'] === 'custom') {
        $log_settings['archive_retention_days'] = 365;
    }
    
    // Performance & Resource Control settings
    $performance_settings = array(
        'batch_logging_enabled' => isset($_POST['batch_logging_enabled']) ? 1 : 0,
        'batch_size' => absint($_POST['batch_size'] ?? 100),
        'batch_frequency' => absint($_POST['batch_frequency'] ?? 5),
        'rate_limiting_enabled' => isset($_POST['rate_limiting_enabled']) ? 1 : 0,
        'rate_limit_per_minute' => absint($_POST['rate_limit_per_minute'] ?? 60),
        'rate_limit_per_hour' => absint($_POST['rate_limit_per_hour'] ?? 1000),
        'rate_limit_behavior' => sanitize_text_field($_POST['rate_limit_behavior'] ?? 'graceful_degradation'),
        'memory_monitoring_enabled' => isset($_POST['memory_monitoring_enabled']) ? 1 : 0,
        'memory_limit_threshold' => absint($_POST['memory_limit_threshold'] ?? 80),
        'excluded_user_roles' => isset($_POST['excluded_user_roles']) ? array_map('sanitize_text_field', $_POST['excluded_user_roles']) : array()
    );
    
    // Performance validation
    if ($performance_settings['batch_size'] < 1) {
        $performance_settings['batch_size'] = 50;
    }
    if ($performance_settings['batch_frequency'] < 30) {
        $performance_settings['batch_frequency'] = 60;
    }
    if ($performance_settings['rate_limit_per_minute'] < 1) {
        $performance_settings['rate_limit_per_minute'] = 100;
    }
    if ($performance_settings['rate_limit_per_hour'] < 1) {
        $performance_settings['rate_limit_per_hour'] = 1000;
    }
    if ($performance_settings['memory_limit_threshold'] < 50 || $performance_settings['memory_limit_threshold'] > 95) {
        $performance_settings['memory_limit_threshold'] = 80;
    }
    
    // Validate rate limiting behavior
    $valid_behaviors = array('graceful_degradation', 'hard_blocking', 'priority_only');
    if (!in_array($performance_settings['rate_limit_behavior'], $valid_behaviors)) {
        $performance_settings['rate_limit_behavior'] = 'graceful_degradation';
    }
    
    // Privacy & Security settings
    $privacy_settings = array(
        'log_ip_addresses' => isset($_POST['log_ip_addresses']) ? 1 : 0,
        'anonymize_data' => isset($_POST['anonymize_data']) ? 1 : 0,
        'anonymize_schedule' => isset($_POST['anonymize_schedule']) ? absint($_POST['anonymize_schedule']) : 30,
        'admin_notifications' => isset($_POST['admin_notifications']) ? 1 : 0,
        'role_based_access' => isset($_POST['role_based_access']) ? 1 : 0,
        'audit_log_access' => isset($_POST['audit_log_access']) ? 1 : 0,
        'right_to_be_forgotten' => isset($_POST['right_to_be_forgotten']) ? 1 : 0,
        'data_portability' => isset($_POST['data_portability']) ? 1 : 0
    );
    
    // Notification settings
    $notification_settings = array(
        'email_notifications' => isset($_POST['email_notifications']) ? 1 : 0,
        'notification_email' => sanitize_email($_POST['notification_email'] ?? get_option('admin_email')),
    );
    
    // Export settings
    $export_settings = array(
        'export_format' => sanitize_text_field($_POST['export_format'] ?? 'json'),
        'export_date_range' => sanitize_text_field($_POST['export_date_range'] ?? '30'),
        'api_access' => isset($_POST['api_access']) ? 1 : 0
    );
    
    // Merge all settings
    $all_settings = array_merge($log_settings, $performance_settings, $privacy_settings, $notification_settings, $export_settings);
    
    // --- BEGIN: Save new email notification fields ---
    $email_notification_fields = [
        'sentinel_email_notifications_enabled',
        'sentinel_email_realtime_critical',
        'sentinel_email_realtime_security',
        'sentinel_email_realtime_error',
        'sentinel_email_realtime_high',
        'sentinel_email_daily_summary',
        'sentinel_email_daily_error',
        'sentinel_email_daily_user',
        'sentinel_email_weekly_health',
        'sentinel_email_weekly_performance',
        'sentinel_email_weekly_security',
        'sentinel_email_cat_authentication',
        'sentinel_email_cat_content',
        'sentinel_email_cat_system',
        'sentinel_email_cat_error',
        'sentinel_email_cat_security',
        'sentinel_email_cat_user',
        'sentinel_email_priority_high',
        'sentinel_email_priority_medium',
        'sentinel_email_priority_low',
    ];
    foreach ($email_notification_fields as $field) {
        $all_settings[$field] = isset($_POST[$field]) ? 1 : 0;
    }
    // --- END: Save new email notification fields ---
    
    // Save settings
    update_option('sentinel_log_management', $all_settings);
    
    // Debug log the rate limiting behavior save
    error_log('[Sentinel] Rate limiting behavior saved: ' . $all_settings['rate_limit_behavior']);
    
    // Update cron schedules
    sentinel_update_cleanup_schedule();
    
    // Update batch logging schedule
    sentinel_update_batch_logging_schedule();
    
    // Update digest schedules
    sentinel_update_digest_schedules();
    
    // Store success message and tab for display
    $current_tab = sanitize_text_field($_POST['sentinel_current_tab'] ?? 'database');
    
    // Check if batch logging was enabled and set appropriate message
    if (!empty($all_settings['batch_logging_enabled'])) {
        $next_scheduled = wp_next_scheduled('sentinel_process_log_queue');
        if ($next_scheduled) {
            $settings_success_message = 'batch_logging_enabled';
        } else {
            $settings_success_message = 'batch_logging_warning';
        }
    } else {
        $settings_success_message = 'settings_saved';
    }
    
    // Set flag for JavaScript redirect
    $needs_redirect = true;
}

// Display success message from form submission
if (isset($settings_success_message)) {
    switch ($settings_success_message) {
        case 'settings_saved':
            echo '<div class="notice notice-success is-dismissible"><p>✅ Settings saved successfully!</p></div>';
            break;
        case 'batch_logging_enabled':
            echo '<div class="notice notice-success is-dismissible"><p>✅ Settings saved successfully! Batch logging is now active and scheduled for automatic processing.</p></div>';
            break;
        case 'batch_logging_warning':
            echo '<div class="notice notice-warning is-dismissible"><p>⚠️ Settings saved, but batch logging cron job could not be scheduled. Please check your WordPress cron configuration.</p></div>';
            break;
    }
}

// Display memory populate/clear success messages
if (get_transient('sentinel_memory_populate_success')) {
    echo '<div class="notice notice-success is-dismissible"><p><strong>✅ Memory Monitor Test Data Added!</strong> Scroll down to see the populated memory analysis in the Performance tab.</p></div>';
    delete_transient('sentinel_memory_populate_success');
}

if (get_transient('sentinel_memory_clear_success')) {
    echo '<div class="notice notice-info is-dismissible"><p><strong>🧹 Memory Monitor Test Data Cleared!</strong> The memory analysis will now build up naturally with real site activity.</p></div>';
    delete_transient('sentinel_memory_clear_success');
}

// Display admin notices from URL parameters
if (isset($_GET['message'])) {
    switch ($_GET['message']) {
        case 'settings_saved':
            echo '<div class="notice notice-success is-dismissible"><p>✅ Settings saved successfully!</p></div>';
            break;
        case 'batch_logging_enabled':
            echo '<div class="notice notice-success is-dismissible"><p>✅ Settings saved successfully! Batch logging is now active and scheduled for automatic processing.</p></div>';
            break;
        case 'batch_logging_warning':
            echo '<div class="notice notice-warning is-dismissible"><p>⚠️ Settings saved, but batch logging cron job could not be scheduled. Please check your WordPress cron configuration.</p></div>';
            break;
        case 'cleanup_success':
            $count = isset($_GET['count']) ? intval($_GET['count']) : 0;
            echo '<div class="notice notice-success is-dismissible"><p>✅ Cleanup completed successfully! Archived ' . $count . ' logs.</p></div>';
            break;
        case 'cleanup_error':
            echo '<div class="notice notice-error is-dismissible"><p>❌ Cleanup failed! Cleanup class not available.</p></div>';
            break;
        case 'optimize_success':
            echo '<div class="notice notice-success is-dismissible"><p>⚡ Database optimization completed successfully!</p></div>';
            break;
        case 'optimize_error':
            echo '<div class="notice notice-error is-dismissible"><p>❌ Optimization failed! Cleanup class not available.</p></div>';
            break;
        case 'process_queue_success':
            $count = isset($_GET['count']) ? intval($_GET['count']) : 0;
            echo '<div class="notice notice-success is-dismissible"><p>📤 Queue processed successfully! Processed ' . $count . ' log entries.</p></div>';
            break;
        case 'process_queue_error':
            echo '<div class="notice notice-error is-dismissible"><p>❌ Queue processing failed! Logger class not available.</p></div>';
            break;

    }
}

// Also check for settings-updated parameter from WordPress
if (isset($_GET['settings-updated']) && $_GET['settings-updated'] === 'true') {
    // This ensures the tab restoration works even if no custom message is set
}

// Get current settings with defaults
$default_settings = array(
    'cleanup_enabled' => 1,
    'cleanup_age_days' => 90,
    'cleanup_max_entries' => 10000,
    'archive_retention_type' => '1year',
    'archive_retention_days' => 365,
    'db_optimization_enabled' => 1,
    'db_optimization_schedule' => 'weekly',
    'cleanup_schedule' => 'daily',
    // Performance & Resource Control
    'batch_logging_enabled' => 0,
    'batch_size' => 50,
    'batch_frequency' => 60,
    '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,
    'excluded_user_roles' => array('administrator'),
    // Privacy & Security
    'log_ip_addresses' => 1,
    'anonymize_data' => 0,
    'anonymize_schedule' => 30,
    'admin_notifications' => 1,
    'role_based_access' => 0,
    'audit_log_access' => 0,
    // User Privacy Controls
    'right_to_be_forgotten' => 0,
    'data_portability' => 0,
    // Notifications
    'email_notifications' => 0,
    'notification_email' => get_option('admin_email'),
    'alert_threshold' => 'medium',
    // Export
    'export_format' => 'json',
    'export_date_range' => '30',
    'api_access' => 0,
    'ip_whitelist' => '',
    // --- BEGIN: Default values for new email notification fields ---
    'sentinel_email_notifications_enabled' => 0,
    'sentinel_email_realtime_critical' => 0,
    'sentinel_email_realtime_security' => 0,
    'sentinel_email_realtime_error' => 0,
    'sentinel_email_realtime_high' => 0,
    'sentinel_email_daily_summary' => 0,
    'sentinel_email_daily_error' => 0,
    'sentinel_email_daily_user' => 0,
    'sentinel_email_weekly_health' => 0,
    'sentinel_email_weekly_performance' => 0,
    'sentinel_email_weekly_security' => 0,
    'sentinel_email_cat_authentication' => 0,
    'sentinel_email_cat_content' => 0,
    'sentinel_email_cat_system' => 0,
    'sentinel_email_cat_error' => 0,
    'sentinel_email_cat_security' => 0,
    'sentinel_email_cat_user' => 0,
    'sentinel_email_priority_high' => 0,
    'sentinel_email_priority_medium' => 0,
    'sentinel_email_priority_low' => 0,
    // --- END: Default values for new email notification fields ---
);

$settings = wp_parse_args(get_option('sentinel_log_management', array()), $default_settings);

// Check table existence
global $wpdb;
$main_table = $wpdb->prefix . 'sentinel_logs';
$archive_table = $wpdb->prefix . 'sentinel_logs_archive';

$main_table_exists = $wpdb->get_var("SHOW TABLES LIKE '$main_table'") == $main_table;
$archive_table_exists = $wpdb->get_var("SHOW TABLES LIKE '$archive_table'") == $archive_table;
?>

<div class="wrap 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">Settings</h1>

    <!-- Tab Navigation -->
    <div class="sentinel-tab-navigation">
        <a href="#" class="sentinel-tab sentinel-tab-active" data-tab="database">
            <i class="dashicons dashicons-database"></i>
            <span>Database Status</span>
        </a>
        <a href="#" class="sentinel-tab" data-tab="log-management">
            <i class="dashicons dashicons-admin-tools"></i>
            <span>Log Management</span>
        </a>
        <a href="#" class="sentinel-tab" data-tab="performance">
            <i class="dashicons dashicons-performance"></i>
            <span>Performance</span>
        </a>
        <a href="#" class="sentinel-tab" data-tab="privacy">
            <i class="dashicons dashicons-shield"></i>
            <span>Privacy & Security</span>
        </a>
        <a href="#" class="sentinel-tab" data-tab="notifications">
            <i class="dashicons dashicons-bell"></i>
            <span>Notifications</span>
        </a>
        <a href="#" class="sentinel-tab" data-tab="export">
            <i class="dashicons dashicons-download"></i>
            <span>Export & Integration</span>
        </a>
    </div>

    <form method="post" action="<?php echo esc_url(admin_url('admin.php?page=sentinel-settings')); ?>"
        id="sentinel-main-settings-form">
        <?php wp_nonce_field('sentinel_settings', 'sentinel_settings_nonce'); ?>
        <!-- Hidden field to store current tab -->
        <input type="hidden" name="sentinel_current_tab" id="sentinel_current_tab"
            value="<?php echo esc_attr(isset($_GET['tab']) ? sanitize_text_field($_GET['tab']) : 'database'); ?>" />

        <!-- Database Status Tab -->
        <div id="database-tab" class="sentinel-tab-content">
            <div class="sentinel-settings-card">
                <div class="sentinel-settings-card-header">
                    <h2 class="sentinel-settings-card-title">
                        <i class="dashicons dashicons-database"></i>
                        Database Status
                    </h2>
                </div>
                <div class="sentinel-settings-card-content">
                    <table class="form-table">
                        <tr>
                            <th scope="row">Main Table</th>
                            <td>
                                <?php if ($main_table_exists): ?>
                                <span class="sentinel-db-status-success">✅ <code><?php echo $main_table; ?></code>
                                    ready</span>
                                <?php else: ?>
                                <span class="sentinel-db-status-error">❌ <code><?php echo $main_table; ?></code>
                                    missing</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">Archive Table</th>
                            <td>
                                <?php if ($archive_table_exists): ?>
                                <span class="sentinel-db-status-success">✅ <code><?php echo $archive_table; ?></code>
                                    ready</span>
                                <?php else: ?>
                                <span class="sentinel-db-status-error">❌ <code><?php echo $archive_table; ?></code>
                                    missing</span>
                                <?php endif; ?>
                            </td>
                        </tr>
                    </table>

                    <?php if (!$main_table_exists || !$archive_table_exists): ?>
                    <div class="sentinel-db-status-message sentinel-db-status-message--warning">
                        <p><strong>⚠️ Database tables are missing!</strong> This indicates a plugin installation issue.
                        </p>
                        <p><em>Tables should be created automatically. If this persists, try deactivating and
                                reactivating the
                                plugin.</em></p>
                    </div>
                    <?php else: ?>
                    <div class="sentinel-db-status-message sentinel-db-status-message--success">
                        <p><strong>✅ Database is ready!</strong> All required tables exist and log management features
                            are
                            available.</p>
                    </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>

        <!-- Log Management & Retention Tab -->
        <div id="log-management-tab" class="sentinel-tab-content" style="display: none;">
            <div class="sentinel-settings-card">
                <div class="sentinel-settings-card-header">
                    <h2 class="sentinel-settings-card-title">
                        <i class="dashicons dashicons-admin-tools"></i>
                        Log Management & Retention
                    </h2>
                </div>
                <div class="sentinel-settings-card-content">
                    <table class="form-table">
                        <!-- Auto-Cleanup Toggle -->
                        <tr>
                            <th scope="row">
                                <label for="cleanup_enabled">Auto-Cleanup</label>
                            </th>
                            <td>
                                <label>
                                    <input type="checkbox" name="cleanup_enabled" id="cleanup_enabled" value="1"
                                        <?php checked($settings['cleanup_enabled']); ?>>
                                    <span>Enable automatic cleanup of old logs</span>
                                </label>
                                <p class="description">When enabled, old logs will be automatically moved to archive or
                                    deleted based on the settings below.</p>
                            </td>
                        </tr>

                        <!-- Cleanup Age Limit -->
                        <tr>
                            <th scope="row">
                                <label for="cleanup_age_days">Age Limit</label>
                            </th>
                            <td>
                                <input type="number" name="cleanup_age_days" id="cleanup_age_days"
                                    value="<?php echo esc_attr($settings['cleanup_age_days']); ?>" min="1" max="3650"
                                    class="small-text">
                                <span>days</span>
                                <p class="description">Archive logs older than this many days. (Minimum: 1 day, Maximum:
                                    10
                                    years)</p>
                            </td>
                        </tr>

                        <!-- Cleanup Count Limit -->
                        <tr>
                            <th scope="row">
                                <label for="cleanup_max_entries">Entry Limit</label>
                            </th>
                            <td>
                                <input type="number" name="cleanup_max_entries" id="cleanup_max_entries"
                                    value="<?php echo esc_attr($settings['cleanup_max_entries']); ?>" min="100"
                                    max="1000000" class="small-text">
                                <span>entries</span>
                                <p class="description">Archive logs when total entries exceed this number. (Minimum:
                                    100,
                                    Maximum: 1,000,000)</p>
                            </td>
                        </tr>

                        <!-- Cleanup Schedule -->
                        <tr>
                            <th scope="row">
                                <label for="cleanup_schedule">Cleanup Schedule</label>
                            </th>
                            <td>
                                <select name="cleanup_schedule" id="cleanup_schedule">
                                    <option value="hourly" <?php selected($settings['cleanup_schedule'], 'hourly'); ?>>
                                        Every
                                        Hour</option>
                                    <option value="daily" <?php selected($settings['cleanup_schedule'], 'daily'); ?>>
                                        Daily
                                    </option>
                                    <option value="weekly" <?php selected($settings['cleanup_schedule'], 'weekly'); ?>>
                                        Weekly</option>
                                </select>
                                <p class="description">How often to check for logs that need cleanup.</p>
                            </td>
                        </tr>

                        <!-- Archive Retention -->
                        <tr>
                            <th scope="row">
                                <label for="archive_retention_type">Archive Retention</label>
                            </th>
                            <td>
                                <select name="archive_retention_type" id="archive_retention_type">
                                    <option value="forever"
                                        <?php selected($settings['archive_retention_type'], 'forever'); ?>>Keep Forever
                                    </option>
                                    <option value="6months"
                                        <?php selected($settings['archive_retention_type'], '6months'); ?>>6 Months
                                    </option>
                                    <option value="1year"
                                        <?php selected($settings['archive_retention_type'], '1year'); ?>>1
                                        Year</option>
                                    <option value="2years"
                                        <?php selected($settings['archive_retention_type'], '2years'); ?>>2 Years
                                    </option>
                                    <option value="custom"
                                        <?php selected($settings['archive_retention_type'], 'custom'); ?>>Custom
                                    </option>
                                </select>

                                <div id="custom_archive_days"
                                    style="margin-top: 10px; <?php echo $settings['archive_retention_type'] !== 'custom' ? 'display: none;' : ''; ?>">
                                    <input type="number" name="archive_retention_days"
                                        value="<?php echo esc_attr($settings['archive_retention_days']); ?>" min="1"
                                        max="3650" class="small-text">
                                    <span>days</span>
                                </div>

                                <p class="description">How long to keep archived logs before permanent deletion.</p>
                            </td>
                        </tr>

                        <!-- Database Optimization -->
                        <tr>
                            <th scope="row">
                                <label for="db_optimization_enabled">Database Optimization</label>
                            </th>
                            <td>
                                <label>
                                    <input type="checkbox" name="db_optimization_enabled" id="db_optimization_enabled"
                                        value="1" <?php checked($settings['db_optimization_enabled']); ?>>
                                    <span>Enable automatic database optimization</span>
                                </label>
                                <p class="description">Optimize database tables to maintain performance and reduce
                                    storage
                                    space.</p>
                            </td>
                        </tr>

                        <!-- Optimization Schedule -->
                        <tr>
                            <th scope="row">
                                <label for="db_optimization_schedule">Optimization Schedule</label>
                            </th>
                            <td>
                                <select name="db_optimization_schedule" id="db_optimization_schedule">
                                    <option value="daily"
                                        <?php selected($settings['db_optimization_schedule'], 'daily'); ?>>Daily
                                    </option>
                                    <option value="weekly"
                                        <?php selected($settings['db_optimization_schedule'], 'weekly'); ?>>Weekly
                                    </option>
                                    <option value="monthly"
                                        <?php selected($settings['db_optimization_schedule'], 'monthly'); ?>>Monthly
                                    </option>
                                </select>
                                <p class="description">How often to run database optimization.</p>
                            </td>
                        </tr>
                    </table>

                    <!-- Current Stats -->
                    <div style="margin-top: 30px; padding: 15px; background: #f9f9f9;">
                        <h4>📊 Current Database Status</h4>
                        <?php
                    $main_count = 0;
                    $archive_count = 0;
                    $oldest_log = null;
                    
                    if ($main_table_exists) {
                        $main_count = $wpdb->get_var("SELECT COUNT(*) FROM $main_table");
                        $oldest_log = $wpdb->get_var("SELECT created_at FROM $main_table ORDER BY created_at ASC LIMIT 1");
                    }
                    
                    if ($archive_table_exists) {
                        $archive_count = $wpdb->get_var("SELECT COUNT(*) FROM $archive_table");
                    }
                    ?>
                        <p><strong>Active Logs:</strong> <?php echo number_format($main_count); ?> entries</p>
                        <p><strong>Archived Logs:</strong> <?php echo number_format($archive_count); ?> entries</p>
                        <p><strong>Oldest Log:</strong>
                            <?php echo $oldest_log ? date('Y-m-d H:i:s', strtotime($oldest_log)) : 'No logs yet'; ?></p>
                        <?php if ($oldest_log): ?>
                        <p><strong>Age:</strong>
                            <?php echo human_time_diff(strtotime($oldest_log), current_time('timestamp')); ?></p>
                        <?php endif; ?>

                        <?php
                    // Check for fallback logs
                    $fallback_logs = get_transient('sentinel_fallback_logs');
                    if ($fallback_logs): ?>
                        <div
                            style="margin-top: 15px; padding: 10px; background: #fff3cd; border-left: 4px solid #ffc107;">
                            <h5>⚠️ Fallback Logs (Database logging failed)</h5>
                            <?php foreach (array_reverse($fallback_logs) as $log): ?>
                            <p style="margin: 5px 0; font-size: 12px;">
                                <strong><?php echo esc_html($log['timestamp']); ?>:</strong>
                                <?php echo esc_html($log['event_key']); ?> -
                                <?php echo esc_html(isset($log['data']['error_message']) ? $log['data']['error_message'] : 'No message'); ?>
                            </p>
                            <?php endforeach; ?>
                            <p style="font-size: 11px; color: #666; margin-top: 10px;">
                                <em>These errors were logged to WordPress error_log when database logging failed.</em>
                            </p>
                        </div>
                        <?php endif; ?>
                    </div>

                    <!-- Manual Actions -->
                    <div style="margin-top: 20px;">
                        <h4>🔧 Manual Actions</h4>
                        <p>
                            <a href="<?php echo admin_url('admin.php?page=sentinel-settings&action=cleanup_now'); ?>"
                                class="button button-secondary">
                                🧹 Run Cleanup Now
                            </a>

                            <a href="<?php echo admin_url('admin.php?page=sentinel-settings&action=optimize_now'); ?>"
                                class="button button-secondary" style="margin-left: 10px;">
                                ⚡ Optimize Database Now
                            </a>

                            <?php if ($settings['batch_logging_enabled']): ?>
                            <a href="<?php echo admin_url('admin.php?page=sentinel-settings&action=process_queue_now'); ?>"
                                class="button button-secondary" style="margin-left: 10px;">
                                📤 Process Queue Now
                            </a>

                            <a href="<?php echo admin_url('admin.php?page=sentinel-settings&action=cron_diagnostics'); ?>"
                                class="button button-secondary" style="margin-left: 10px;" target="_blank">
                                🔍 Diagnose Cron Issues
                            </a>
                            <?php endif; ?>

                            <a href="<?php echo admin_url('admin.php?page=sentinel-settings&action=anonymize_logs'); ?>"
                                class="button button-secondary" style="margin-left: 10px;">
                                🕵️ Anonymize Logs
                            </a>
                        </p>
                    </div>
                </div>
            </div>
        </div>

        <!-- Performance & Resource Control Tab -->
        <div id="performance-tab" class="sentinel-tab-content" style="display: none;">
            <div class="sentinel-settings-card">
                <div class="sentinel-settings-card-header">
                    <h2 class="sentinel-settings-card-title">
                        <i class="dashicons dashicons-performance"></i>
                        Performance & Resource Control
                    </h2>
                </div>
                <div class="sentinel-settings-card-content">
                    <table class="form-table">
                        <!-- Batch Logging -->
                        <tr>
                            <th scope="row">
                                <label for="batch_logging_enabled">Batch Logging</label>
                            </th>
                            <td>
                                <label>
                                    <input type="checkbox" name="batch_logging_enabled" id="batch_logging_enabled"
                                        value="1" <?php checked($settings['batch_logging_enabled']); ?>>
                                    <span>Enable batch logging (queue logs instead of immediate database
                                        writes)</span>
                                </label>
                                <p class="description">Improves performance by queuing logs and writing them in
                                    batches instead of immediately.</p>
                            </td>
                        </tr>

                        <!-- Batch Size -->
                        <tr id="batch_size_row"
                            style="<?php echo $settings['batch_logging_enabled'] ? '' : 'display: none;'; ?>">
                            <th scope="row">
                                <label for="batch_size">Batch Size</label>
                            </th>
                            <td>
                                <input type="number" name="batch_size" id="batch_size"
                                    value="<?php echo esc_attr($settings['batch_size']); ?>" min="1" max="500"
                                    class="small-text">
                                <span>logs per batch</span>
                                <p class="description">Number of logs to process in each batch. Higher values =
                                    better performance but more memory usage.</p>
                            </td>
                        </tr>

                        <!-- Batch Frequency -->
                        <tr id="batch_frequency_row"
                            style="<?php echo $settings['batch_logging_enabled'] ? '' : 'display: none;'; ?>">
                            <th scope="row">
                                <label for="batch_frequency">Batch Frequency</label>
                            </th>
                            <td>
                                <input type="number" name="batch_frequency" id="batch_frequency"
                                    value="<?php echo esc_attr($settings['batch_frequency']); ?>" min="30" max="3600"
                                    class="small-text">
                                <span>seconds</span>
                                <p class="description">How often to process batched logs. Lower values = more
                                    frequent processing.</p>
                            </td>
                        </tr>

                        <!-- Rate Limiting -->
                        <tr>
                            <th scope="row">
                                <label for="rate_limiting_enabled">Rate Limiting</label>
                            </th>
                            <td>
                                <label>
                                    <input type="checkbox" name="rate_limiting_enabled" id="rate_limiting_enabled"
                                        value="1" <?php checked($settings['rate_limiting_enabled']); ?>>
                                    <span>Enable rate limiting to prevent spam and abuse</span>
                                </label>
                                <p class="description">Limits the number of log entries that can be created per
                                    minute/hour.</p>
                            </td>
                        </tr>

                        <!-- Rate Limit Per Minute -->
                        <tr id="rate_limit_minute_row"
                            style="<?php echo $settings['rate_limiting_enabled'] ? '' : 'display: none;'; ?>">
                            <th scope="row">
                                <label for="rate_limit_per_minute">Per Minute Limit</label>
                            </th>
                            <td>
                                <input type="number" name="rate_limit_per_minute" id="rate_limit_per_minute"
                                    value="<?php echo esc_attr($settings['rate_limit_per_minute']); ?>" min="1"
                                    max="1000" class="small-text">
                                <span>events per minute</span>
                                <p class="description">Maximum number of log events allowed per minute.</p>
                            </td>
                        </tr>

                        <!-- Rate Limit Per Hour -->
                        <tr id="rate_limit_hour_row"
                            style="<?php echo $settings['rate_limiting_enabled'] ? '' : 'display: none;'; ?>">
                            <th scope="row">
                                <label for="rate_limit_per_hour">Per Hour Limit</label>
                            </th>
                            <td>
                                <input type="number" name="rate_limit_per_hour" id="rate_limit_per_hour"
                                    value="<?php echo esc_attr($settings['rate_limit_per_hour']); ?>" min="1"
                                    max="10000" class="small-text">
                                <span>events per hour</span>
                                <p class="description">Maximum number of log events allowed per hour.</p>
                            </td>
                        </tr>

                        <!-- Rate Limiting Behavior -->
                        <tr id="rate_limit_behavior_row"
                            style="<?php echo $settings['rate_limiting_enabled'] ? '' : 'display: none;'; ?>">
                            <th scope="row">
                                <label for="rate_limit_behavior">Rate Limiting Behavior</label>
                            </th>
                            <td>
                                <select name="rate_limit_behavior" id="rate_limit_behavior">
                                    <option value="graceful_degradation"
                                        <?php selected($settings['rate_limit_behavior'] ?? 'graceful_degradation', 'graceful_degradation'); ?>>
                                        🔄 Graceful Degradation (Sample events when over limit)
                                    </option>
                                    <option value="hard_blocking"
                                        <?php selected($settings['rate_limit_behavior'] ?? 'graceful_degradation', 'hard_blocking'); ?>>
                                        🚫 Hard Blocking (Stop logging when over limit)
                                    </option>
                                    <option value="priority_only"
                                        <?php selected($settings['rate_limit_behavior'] ?? 'graceful_degradation', 'priority_only'); ?>>
                                        ⚠️ Priority Only (Only critical/error events when over limit)
                                    </option>
                                </select>
                                <p class="description">Choose how the system behaves when rate limits are exceeded.</p>

                                <div
                                    style="margin-top: 10px; padding: 10px; background: #f8f9fa; border-radius: 4px; font-size: 13px;">
                                    <strong>Behavior Details:</strong><br>
                                    • <strong>Graceful Degradation:</strong> Samples every 10th event to maintain
                                    visibility while reducing load<br>
                                    • <strong>Hard Blocking:</strong> Completely stops logging until the next time
                                    window (most aggressive)<br>
                                    • <strong>Priority Only:</strong> Only logs critical and error events, blocks
                                    warning/info events
                                </div>
                            </td>
                        </tr>

                        <!-- Memory Monitoring -->
                        <tr>
                            <th scope="row">
                                <label for="memory_monitoring_enabled">Smart Memory Monitoring</label>
                            </th>
                            <td>
                                <label>
                                    <input type="checkbox" name="memory_monitoring_enabled"
                                        id="memory_monitoring_enabled" value="1"
                                        <?php checked($settings['memory_monitoring_enabled']); ?>>
                                    <span>Enable comprehensive memory monitoring & optimization</span>
                                </label>
                                <p class="description">Monitors memory usage patterns and provides optimization
                                    recommendations to prevent crashes.</p>
                            </td>
                        </tr>

                        <!-- Memory Threshold -->
                        <tr id="memory_threshold_row"
                            style="<?php echo $settings['memory_monitoring_enabled'] ? '' : 'display: none;'; ?>">
                            <th scope="row">
                                <label for="memory_limit_threshold">Memory Threshold</label>
                            </th>
                            <td>
                                <input type="number" name="memory_limit_threshold" id="memory_limit_threshold"
                                    value="<?php echo esc_attr($settings['memory_limit_threshold']); ?>" min="50"
                                    max="95" class="small-text">
                                <span>% of memory limit</span>
                                <p class="description">Skip logging when memory usage exceeds this percentage of the
                                    PHP memory limit.</p>
                            </td>
                        </tr>

                        <!-- Excluded User Roles -->
                        <tr>
                            <th scope="row">
                                <label for="excluded_user_roles">Excluded User Roles</label>
                            </th>
                            <td>
                                <?php
                            $wp_roles = wp_roles();
                            $available_roles = $wp_roles->get_names();
                            $excluded_roles = $settings['excluded_user_roles'];
                            ?>
                                <fieldset>
                                    <p class="description" style="margin-bottom: 10px;">Select user roles to exclude
                                        from activity logging (reduces log volume):</p>

                                    <?php
                                    // Get role counts for better information
                                    $role_counts = array();
                                    foreach ($available_roles as $role => $name) {
                                        $users_of_role = get_users(array('role' => $role, 'count_total' => true));
                                        $role_counts[$role] = is_array($users_of_role) ? count($users_of_role) : $users_of_role;
                                    }
                                    ?>

                                    <div class="sentinel-excluded-roles-container">
                                        <?php foreach ($available_roles as $role => $name): ?>
                                        <?php $is_excluded = in_array($role, $excluded_roles); ?>
                                        <label class="sentinel-role-item <?php echo $is_excluded ? 'excluded' : ''; ?>">
                                            <input type="checkbox" name="excluded_user_roles[]"
                                                value="<?php echo esc_attr($role); ?>" <?php checked($is_excluded); ?>>

                                            <div class="sentinel-role-content">
                                                <div class="sentinel-role-details">
                                                    <div class="sentinel-role-name">
                                                        <?php echo esc_html($name); ?>
                                                    </div>
                                                    <div class="sentinel-role-count">
                                                        <?php echo number_format($role_counts[$role]); ?>
                                                        user<?php echo $role_counts[$role] !== 1 ? 's' : ''; ?>
                                                    </div>
                                                </div>

                                                <?php if ($is_excluded): ?>
                                                <span class="sentinel-excluded-badge">
                                                    Excluded
                                                </span>
                                                <?php endif; ?>
                                            </div>
                                        </label>
                                        <?php endforeach; ?>
                                    </div>
                                </fieldset>

                                <p class="description">
                                    <strong>How it works:</strong> Activities by users with these roles will not be
                                    logged.
                                    This includes login/logout, post creation, comments, etc.
                                    <br><strong>Note:</strong> System errors and security events may still be logged
                                    regardless of user role.
                                </p>

                                <?php if (!empty($excluded_roles)): ?>
                                <div class="sentinel-excluded-warning">
                                    <strong>⚠️ Currently Excluding:</strong>
                                    <?php 
                                    $excluded_names = array();
                                    $total_excluded_users = 0;
                                    foreach ($excluded_roles as $role) {
                                        if (isset($available_roles[$role])) {
                                            $excluded_names[] = $available_roles[$role];
                                            $total_excluded_users += $role_counts[$role];
                                        }
                                    }
                                    echo implode(', ', $excluded_names);
                                    ?>
                                    <br><small>This affects <?php echo number_format($total_excluded_users); ?>
                                        user<?php echo $total_excluded_users !== 1 ? 's' : ''; ?> on your site.</small>
                                </div>
                                <?php endif; ?>
                            </td>
                        </tr>
                    </table>

                    <!-- Rate Limiting Status (if enabled) -->
                    <?php if (!empty($settings['rate_limiting_enabled'])): ?>
                    <div class="sentinel-performance-status">
                        <h4>⚡ Rate Limiting Status</h4>

                        <div class="sentinel-performance-grid">
                            <?php
                            // Get current rate limiting status
                            $per_minute_limit = intval($settings['rate_limit_per_minute'] ?? 100);
                            $per_hour_limit = intval($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>

                        <div style="margin-top: 20px; padding: 15px; background: #f0f9ff; border-radius: 8px;">
                            <?php
                            $behavior = $settings['rate_limit_behavior'] ?? 'graceful_degradation';
                            $behavior_info = array(
                                'graceful_degradation' => array(
                                    'title' => '🔄 Graceful Degradation Active',
                                    'description' => 'Every 10th event is sampled and logged to maintain visibility.'
                                ),
                                'hard_blocking' => array(
                                    'title' => '🚫 Hard Blocking Active',
                                    'description' => 'All logging is completely stopped when rate limits are exceeded.'
                                ),
                                'priority_only' => array(
                                    'title' => '⚠️ Priority Only Active',
                                    'description' => 'Only critical and error events are logged when over the limit.'
                                )
                            );
                            
                            $current_behavior = $behavior_info[$behavior] ?? $behavior_info['graceful_degradation'];
                            ?>
                            <h4 style="margin-top: 0;"><?php echo $current_behavior['title']; ?></h4>
                            <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>
                            <p style="margin-bottom: 0;"><strong>When over limit:</strong>
                                <?php echo $current_behavior['description']; ?></p>
                        </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; ?>

                    <!-- Memory Insights (if enabled) -->
                    <?php if (!empty($settings['memory_monitoring_enabled'])): ?>
                    <div class="sentinel-memory-insights">
                        <h4>🧠 Memory Insights & Optimization</h4>

                        <?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>

                                <!-- Test Data Buttons -->
                                <div style="margin-top: 15px; text-align: center;">
                                    <form method="post" style="display: inline-block; margin-right: 10px;">
                                        <?php wp_nonce_field('sentinel_populate_memory', 'sentinel_populate_nonce'); ?>
                                        <button type="submit" name="populate_memory_data" value="1"
                                            class="button button-secondary" style="font-size: 12px;">
                                            🧪 Populate Test Data
                                        </button>
                                    </form>
                                    <?php
                                    // Check if test data exists
                                    $test_data_exists = get_option('sentinel_memory_analysis_history', false);
                                    if ($test_data_exists): ?>
                                    <form method="post" style="display: inline-block;">
                                        <?php wp_nonce_field('sentinel_clear_memory', 'sentinel_clear_nonce'); ?>
                                        <button type="submit" name="clear_memory_data" value="1"
                                            class="button button-secondary" style="font-size: 12px;">
                                            🧹 Clear Test Data
                                        </button>
                                    </form>
                                    <?php endif; ?>
                                </div>
                                <?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>

                                    <!-- Test Data Buttons for when no recommendations exist -->
                                    <div style="margin-top: 15px; text-align: center;">
                                        <form method="post" style="display: inline-block; margin-right: 10px;">
                                            <?php wp_nonce_field('sentinel_populate_memory', 'sentinel_populate_nonce'); ?>
                                            <button type="submit" name="populate_memory_data" value="1"
                                                class="button button-secondary" style="font-size: 12px;">
                                                🧪 Populate Test Data
                                            </button>
                                        </form>
                                        <?php
                                        // Check if test data exists
                                        $test_data_exists = get_option('sentinel_memory_analysis_history', false);
                                        if ($test_data_exists): ?>
                                        <form method="post" style="display: inline-block;">
                                            <?php wp_nonce_field('sentinel_clear_memory', 'sentinel_clear_nonce'); ?>
                                            <button type="submit" name="clear_memory_data" value="1"
                                                class="button button-secondary" style="font-size: 12px;">
                                                🧹 Clear Test Data
                                            </button>
                                        </form>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    <?php endif; ?>

                    <!-- Performance Status -->
                    <div class="sentinel-performance-status">
                        <h4>⚡ Performance Status</h4>

                        <?php
                        $memory_usage = memory_get_usage(true);
                        $memory_limit_str = ini_get('memory_limit');
                        
                        // Convert memory limit to bytes (fallback for older WP versions)
                        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>

                            <!-- Batch Logging Card -->
                            <?php if ($settings['batch_logging_enabled']): ?>
                            <?php 
                                $queue_stats = Sentinel_Logger::get_queue_stats();
                                $next_batch = $queue_stats['next_scheduled'] ? date('Y-m-d H:i:s', $queue_stats['next_scheduled']) : 'Not scheduled';
                                $cron_status = $queue_stats['next_scheduled'] ? '✅ Active' : '❌ Not scheduled';
                                $queue_color = $queue_stats['next_scheduled'] ? '#6bcf7f' : '#ff6b6b';
                                $batch_frequency = !empty($settings['batch_frequency']) ? $settings['batch_frequency'] : 60;
                            ?>
                            <div class="sentinel-performance-card">
                                <h4>
                                    <span
                                        class="sentinel-status-icon <?php echo $queue_stats['next_scheduled'] ? 'sentinel-status-active' : 'sentinel-status-inactive'; ?>">
                                        <?php echo $queue_stats['next_scheduled'] ? '🟢' : '🔴'; ?>
                                    </span>
                                    Batch Logging
                                </h4>
                                <div class="sentinel-progress-bar">
                                    <div class="sentinel-progress-fill <?php echo $queue_stats['next_scheduled'] ? 'good' : 'critical'; ?>"
                                        style="width: <?php echo min($queue_stats['queue_percent'], 100); ?>%;"></div>
                                </div>
                                <p>
                                    <strong><?php echo $queue_stats['queue_size']; ?></strong> items queued
                                    (<strong><?php echo $queue_stats['queue_percent']; ?>%</strong> full)
                                </p>
                                <div class="sentinel-batch-stats">
                                    <div class="sentinel-batch-stat">
                                        <div class="value"><?php echo $queue_stats['batch_size']; ?></div>
                                        <div class="label">Batch Size</div>
                                    </div>
                                    <div class="sentinel-batch-stat">
                                        <div class="value">
                                            <?php echo $batch_frequency; ?><?php echo $batch_frequency == 1 ? ' sec' : ' secs'; ?>
                                        </div>
                                        <div class="label">Frequency</div>
                                    </div>
                                </div>

                                <div class="sentinel-batch-actions">
                                    <a href="<?php echo add_query_arg(array('action' => 'process_queue_now'), admin_url('admin.php?page=sentinel-settings')); ?>"
                                        class="button button-primary"
                                        <?php echo $queue_stats['queue_size'] == 0 ? 'disabled' : ''; ?>>
                                        🚀 Process Queue Now
                                    </a>
                                    <a href="<?php echo add_query_arg(array('action' => 'cron_diagnostics'), admin_url('admin.php?page=sentinel-settings')); ?>"
                                        class="button">
                                        🔍 Diagnose Cron Issues
                                    </a>
                                </div>

                                <?php if ($queue_stats['next_scheduled']): ?>
                                <div class="sentinel-next-batch-time">
                                    <?php if ($queue_stats['next_scheduled'] > current_time('timestamp')): ?>
                                    Next batch:
                                    <?php echo human_time_diff($queue_stats['next_scheduled'], current_time('timestamp')); ?>
                                    from now
                                    <?php else: ?>
                                    <span style="color: #ff6b6b;">⚠️ Batch overdue by
                                        <?php echo human_time_diff($queue_stats['next_scheduled'], current_time('timestamp')); ?></span>
                                    <?php endif; ?>
                                </div>
                                <?php else: ?>
                                <div class="sentinel-next-batch-time">
                                    <span style="color: #d63638;">Not Scheduled</span>
                                </div>
                                <?php endif; ?>
                            </div>
                            <?php else: ?>
                            <!-- Batch Logging Disabled -->
                            <div class="sentinel-performance-card" style="opacity: 0.7;">
                                <h4>
                                    <span class="sentinel-status-icon sentinel-status-inactive">⚪</span>
                                    Batch Logging
                                </h4>
                                <p style="text-align: center; color: #999; font-style: italic; padding: 20px 0;">
                                    Enable batch logging to improve performance with high-volume sites
                                </p>
                            </div>
                            <?php endif; ?>

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

                        <?php if ($settings['memory_monitoring_enabled'] && $memory_percent > $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 $settings['memory_limit_threshold']; ?>%).
                                Consider optimizing or increasing memory limits.
                            </p>
                        </div>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

        <!-- Privacy & Security Tab -->
        <div id="privacy-tab" class="sentinel-tab-content" style="display: none;">
            <!-- Data Privacy Controls -->
            <div class="sentinel-settings-card">
                <div class="sentinel-settings-card-header">
                    <h2 class="sentinel-settings-card-title">
                        <i class="dashicons dashicons-shield"></i>
                        Data Privacy Controls
                    </h2>
                </div>
                <div class="sentinel-settings-card-content">
                    <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="log_ip_addresses">IP Address Logging</label>
                            </th>
                            <td>
                                <label>
                                    <input type="checkbox" name="log_ip_addresses" id="log_ip_addresses" value="1"
                                        <?php checked($settings['log_ip_addresses']); ?>>
                                    <span>Log user IP addresses</span>
                                </label>
                                <p class="description">Enable to track IP addresses in activity logs for
                                    security monitoring.</p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="anonymize_data">Data Anonymization</label>
                            </th>
                            <td>
                                <label>
                                    <input type="checkbox" name="anonymize_data" id="anonymize_data" value="1"
                                        <?php checked($settings['anonymize_data']); ?>>
                                    <span>Anonymize sensitive data after 30 days</span>
                                </label>
                                <p class="description">Automatically anonymize IP addresses and user data for
                                    privacy compliance.</p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="anonymize_schedule">Anonymization Schedule</label>
                            </th>
                            <td>
                                <select name="anonymize_schedule" id="anonymize_schedule">
                                    <option value="30" <?php selected($settings['anonymize_schedule'], 30); ?>>After 30
                                        days</option>
                                    <option value="60" <?php selected($settings['anonymize_schedule'], 60); ?>>After 60
                                        days</option>
                                    <option value="90" <?php selected($settings['anonymize_schedule'], 90); ?>>After 90
                                        days (GDPR compliant)</option>
                                    <option value="180" <?php selected($settings['anonymize_schedule'], 180); ?>>After 6
                                        months</option>
                                    <option value="365" <?php selected($settings['anonymize_schedule'], 365); ?>>After 1
                                        year (CCPA compliant)</option>
                                </select>
                                <p class="description">How long to wait before anonymizing sensitive data.</p>
                            </td>
                        </tr>
                    </table>
                </div>
            </div>

            <!-- Access Control & Security -->
            <div class="sentinel-settings-card">
                <div class="sentinel-settings-card-header">
                    <h2 class="sentinel-settings-card-title">
                        <i class="dashicons dashicons-lock"></i>
                        Access Control & Security
                    </h2>
                </div>
                <div class="sentinel-settings-card-content">
                    <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="role_based_access">Role-Based Log Access</label>
                            </th>
                            <td>
                                <label>
                                    <input type="checkbox" name="role_based_access" id="role_based_access" value="1"
                                        <?php checked(!empty($settings['role_based_access'])); ?>>
                                    <span>Restrict log access based on user roles</span>
                                </label>
                                <p class="description">When enabled, editors will only see user, content, and
                                    authentication events. Admins see all events.</p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="audit_log_access">Audit Log Access</label>
                            </th>
                            <td>
                                <label>
                                    <input type="checkbox" name="audit_log_access" id="audit_log_access" value="1"
                                        <?php checked(!empty($settings['audit_log_access'])); ?>>
                                    <span>Log who accesses sensitive log data</span>
                                </label>
                                <p class="description">When enabled, Sentinel will log whenever a user views the logs or
                                    dashboard, including who, when, and from where.</p>
                            </td>
                        </tr>
                    </table>
                </div>
            </div>

            <!-- User Privacy Controls -->
            <div class="sentinel-settings-card">
                <div class="sentinel-settings-card-header">
                    <h2 class="sentinel-settings-card-title">
                        <i class="dashicons dashicons-groups"></i>
                        User Privacy Controls
                    </h2>
                </div>
                <div class="sentinel-settings-card-content">
                    <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="right_to_be_forgotten">Right to be Forgotten</label>
                            </th>
                            <td>
                                <label>
                                    <input type="checkbox" name="right_to_be_forgotten" id="right_to_be_forgotten"
                                        value="1" <?php checked(!empty($settings['right_to_be_forgotten'])); ?>>
                                    <span>Allow users to request data deletion</span>
                                </label>
                                <p class="description">Enable GDPR Article 17 compliance - users can request deletion of
                                    their personal data from logs.</p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="data_portability">Data Portability</label>
                            </th>
                            <td>
                                <label>
                                    <input type="checkbox" name="data_portability" id="data_portability" value="1"
                                        <?php checked(!empty($settings['data_portability'])); ?>>
                                    <span>Allow users to export their data</span>
                                </label>
                                <p class="description">Enable GDPR Article 20 compliance - users can export their
                                    personal data in machine-readable format.</p>
                            </td>
                        </tr>
                    </table>
                </div>
            </div>
        </div>

        <!-- Notifications Tab -->
        <div id="notifications-tab" class="sentinel-tab-content" style="display: none;">
            <div class="sentinel-settings-card">
                <div class="sentinel-settings-card-header">
                    <h2 class="sentinel-settings-card-title">
                        <i class="dashicons dashicons-bell"></i>
                        Notifications & Alerts
                    </h2>
                </div>
                <div class="sentinel-settings-card-content">
                    <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="notification_email">Notification Email</label>
                            </th>
                            <td>
                                <input type="email" name="notification_email" id="notification_email"
                                    value="<?php echo esc_attr($settings['notification_email']); ?>"
                                    class="regular-text">
                                <p class="description">Email address to receive security notifications.</p>
                            </td>
                        </tr>

                    </table>
                </div>
            </div>
            <!-- Compliance & Monitoring -->
            <div class="sentinel-settings-card">
                <div class="sentinel-settings-card-header">
                    <h2 class="sentinel-settings-card-title">
                        <i class="dashicons dashicons-admin-generic"></i>
                        Compliance & Monitoring
                    </h2>
                </div>
                <div class="sentinel-settings-card-content">
                    <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="admin_notifications">Security Event Notifications</label>
                            </th>
                            <td>
                                <label>
                                    <input type="checkbox" name="admin_notifications" id="admin_notifications" value="1"
                                        <?php checked($settings['admin_notifications']); ?>>
                                    <span>Email notifications for security events</span>
                                </label>
                                <p class="description">Send email alerts for login failures, plugin changes, and
                                    security events.</p>
                            </td>
                        </tr>
                        <!-- BEGIN: Email Notification Settings UI (Compliance & Monitoring) -->
                        <tr>
                            <th scope="row">
                                <label for="sentinel_email_notifications_enabled">Enable Email Notifications</label>
                            </th>
                            <td>
                                <label>
                                    <input type="checkbox" name="sentinel_email_notifications_enabled"
                                        id="sentinel_email_notifications_enabled" value="1"
                                        <?php checked(!empty($settings['sentinel_email_notifications_enabled'])); ?>>
                                    <span>Send email notifications for selected events</span>
                                </label>
                                <div id="sentinel_email_notification_options" style="margin-top: 16px;"
                                    <?php if (!empty($settings['sentinel_email_notifications_enabled'])) echo ' class="is-visible"'; ?>>
                                    <!-- BEGIN: Real-time Alerts Card -->
                                    <div class="sentinel-email-card-group">
                                        <h4>Real-time Alerts</h4>
                                        <div class="sentinel-email-card-grid">
                                            <label class="sentinel-email-pill-toggle"><input type="checkbox"
                                                    name="sentinel_email_realtime_critical" value="1"
                                                    <?php checked(!empty($settings['sentinel_email_realtime_critical'])); ?>><span>Critical
                                                    Events Only</span></label>
                                            <label class="sentinel-email-pill-toggle"><input type="checkbox"
                                                    name="sentinel_email_realtime_security" value="1"
                                                    <?php checked(!empty($settings['sentinel_email_realtime_security'])); ?>><span>Security
                                                    Events</span></label>
                                            <label class="sentinel-email-pill-toggle"><input type="checkbox"
                                                    name="sentinel_email_realtime_error" value="1"
                                                    <?php checked(!empty($settings['sentinel_email_realtime_error'])); ?>><span>Error
                                                    Events</span></label>
                                            <label class="sentinel-email-pill-toggle"><input type="checkbox"
                                                    name="sentinel_email_realtime_high" value="1"
                                                    <?php checked(!empty($settings['sentinel_email_realtime_high'])); ?>><span>High
                                                    Priority Events</span></label>
                                        </div>
                                    </div>
                                    <!-- END: Real-time Alerts Card -->
                                    <!-- BEGIN: Daily Digest Card -->
                                    <div class="sentinel-email-card-group">
                                        <h4>Daily Digest</h4>
                                        <div class="sentinel-email-card-grid">
                                            <label class="sentinel-email-pill-toggle"><input type="checkbox"
                                                    name="sentinel_email_daily_summary" value="1"
                                                    <?php checked(!empty($settings['sentinel_email_daily_summary'])); ?>><span>Event
                                                    Summary</span></label>
                                            <label class="sentinel-email-pill-toggle"><input type="checkbox"
                                                    name="sentinel_email_daily_error" value="1"
                                                    <?php checked(!empty($settings['sentinel_email_daily_error'])); ?>><span>Error
                                                    Report</span></label>
                                            <label class="sentinel-email-pill-toggle"><input type="checkbox"
                                                    name="sentinel_email_daily_user" value="1"
                                                    <?php checked(!empty($settings['sentinel_email_daily_user'])); ?>><span>User
                                                    Activity</span></label>
                                        </div>
                                    </div>
                                    <!-- END: Daily Digest Card -->
                                    <!-- BEGIN: Weekly Digest Card -->
                                    <div class="sentinel-email-card-group">
                                        <h4>Weekly Digest</h4>
                                        <div class="sentinel-email-card-grid">
                                            <label class="sentinel-email-pill-toggle"><input type="checkbox"
                                                    name="sentinel_email_weekly_health" value="1"
                                                    <?php checked(!empty($settings['sentinel_email_weekly_health'])); ?>><span>System
                                                    Health Report</span></label>
                                            <label class="sentinel-email-pill-toggle"><input type="checkbox"
                                                    name="sentinel_email_weekly_performance" value="1"
                                                    <?php checked(!empty($settings['sentinel_email_weekly_performance'])); ?>><span>Performance
                                                    Metrics</span></label>
                                            <label class="sentinel-email-pill-toggle"><input type="checkbox"
                                                    name="sentinel_email_weekly_security" value="1"
                                                    <?php checked(!empty($settings['sentinel_email_weekly_security'])); ?>><span>Security
                                                    Summary</span></label>
                                        </div>
                                    </div>
                                    <!-- END: Weekly Digest Card -->
                                    <!-- BEGIN: Categories Card -->
                                    <div class="sentinel-email-card-group">
                                        <h4>Categories</h4>
                                        <div class="sentinel-email-card-grid">
                                            <label class="sentinel-email-pill-toggle"><input type="checkbox"
                                                    name="sentinel_email_cat_authentication" value="1"
                                                    <?php checked(!empty($settings['sentinel_email_cat_authentication'])); ?>><span>Authentication</span></label>
                                            <label class="sentinel-email-pill-toggle"><input type="checkbox"
                                                    name="sentinel_email_cat_content" value="1"
                                                    <?php checked(!empty($settings['sentinel_email_cat_content'])); ?>><span>Content</span></label>
                                            <label class="sentinel-email-pill-toggle"><input type="checkbox"
                                                    name="sentinel_email_cat_system" value="1"
                                                    <?php checked(!empty($settings['sentinel_email_cat_system'])); ?>><span>System</span></label>
                                            <label class="sentinel-email-pill-toggle"><input type="checkbox"
                                                    name="sentinel_email_cat_error" value="1"
                                                    <?php checked(!empty($settings['sentinel_email_cat_error'])); ?>><span>Error</span></label>
                                            <label class="sentinel-email-pill-toggle"><input type="checkbox"
                                                    name="sentinel_email_cat_security" value="1"
                                                    <?php checked(!empty($settings['sentinel_email_cat_security'])); ?>><span>Security</span></label>
                                            <label class="sentinel-email-pill-toggle"><input type="checkbox"
                                                    name="sentinel_email_cat_user" value="1"
                                                    <?php checked(!empty($settings['sentinel_email_cat_user'])); ?>><span>User</span></label>
                                        </div>
                                    </div>
                                    <!-- END: Categories Card -->
                                    <!-- BEGIN: Priorities Card -->
                                    <div class="sentinel-email-card-group">
                                        <h4>Priorities</h4>
                                        <div class="sentinel-email-card-grid">
                                            <label class="sentinel-email-pill-toggle"><input type="checkbox" checked
                                                    disabled><span>Critical (always enabled)</span></label>
                                            <label class="sentinel-email-pill-toggle"><input type="checkbox"
                                                    name="sentinel_email_priority_high" value="1"
                                                    <?php checked(!empty($settings['sentinel_email_priority_high'])); ?>><span>High</span></label>
                                            <label class="sentinel-email-pill-toggle"><input type="checkbox"
                                                    name="sentinel_email_priority_medium" value="1"
                                                    <?php checked(!empty($settings['sentinel_email_priority_medium'])); ?>><span>Medium</span></label>
                                            <label class="sentinel-email-pill-toggle"><input type="checkbox"
                                                    name="sentinel_email_priority_low" value="1"
                                                    <?php checked(!empty($settings['sentinel_email_priority_low'])); ?>><span>Low</span></label>
                                        </div>
                                    </div>
                                    <!-- END: Priorities Card -->
                                </div>
                            </td>
                        </tr>
                        <!-- END: Email Notification Settings UI -->
                    </table>
                </div>
            </div>
        </div>

        <!-- Export & Integration Tab -->
        <div id="export-tab" class="sentinel-tab-content" style="display: none;">
            <div class="sentinel-settings-card">
                <div class="sentinel-settings-card-header">
                    <h2 class="sentinel-settings-card-title">
                        <i class="dashicons dashicons-download"></i>
                        Export & Integration
                    </h2>
                </div>
                <div class="sentinel-settings-card-content">
                    <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="export_format">Export Format</label>
                            </th>
                            <td>
                                <select name="export_format" id="export_format">
                                    <option value="csv" <?php selected($settings['export_format'], 'csv'); ?>>CSV (Comma
                                        Separated Values)</option>
                                    <option value="json" <?php selected($settings['export_format'], 'json'); ?>>JSON
                                        (JavaScript Object Notation)</option>
                                    <option value="xml" <?php selected($settings['export_format'], 'xml'); ?>>XML
                                        (eXtensible Markup Language)</option>
                                </select>
                                <p class="description">Choose the format for exported log data.</p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="export_date_range">Date Range</label>
                            </th>
                            <td>
                                <select name="export_date_range" id="export_date_range">
                                    <option value="7" <?php selected($settings['export_date_range'], '7'); ?>>Last 7
                                        days</option>
                                    <option value="30" <?php selected($settings['export_date_range'], '30'); ?>>Last 30
                                        days</option>
                                    <option value="90" <?php selected($settings['export_date_range'], '90'); ?>>Last 90
                                        days</option>
                                    <option value="all" <?php selected($settings['export_date_range'], 'all'); ?>>All
                                        time</option>
                                </select>
                                <p class="description">Select date range for export.</p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="api_access">API Access</label>
                            </th>
                            <td>
                                <label>
                                    <input type="checkbox" name="api_access" id="api_access" value="1"
                                        <?php checked($settings['api_access']); ?>>
                                    <span>Enable REST API access</span>
                                </label>
                                <p class="description">Allow external applications to access log data via REST API.</p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="export_source_toggle">Export Source</label>
                            </th>
                            <td>
                                <div class="sentinel-segmented-toggle" id="export_source_toggle" role="group"
                                    aria-label="Export Source">
                                    <button type="button" class="sentinel-segmented-btn active" data-value="main"
                                        aria-pressed="true">Main Logs</button>
                                    <button type="button" class="sentinel-segmented-btn" data-value="both"
                                        aria-pressed="false">Both</button>
                                    <button type="button" class="sentinel-segmented-btn" data-value="archive"
                                        aria-pressed="false">Archive Logs</button>
                                    <div class="slider"></div>
                                </div>
                                <div class="sentinel-segmented-desc">Choose which logs to export: active logs, archived
                                    logs, or both.</div>
                            </td>
                        </tr>
                    </table>

                    <div style="margin-top: 30px;">
                        <h4>🔧 Export Actions</h4>
                        <div style="margin-top: 18px;">
                            <div class="sentinel-export-actions">
                                <input type="hidden" id="sentinel-export-logs-json-nonce"
                                    value="<?php echo esc_attr(wp_create_nonce('sentinel_export_logs_json')); ?>">
                                <button type="button" class="button button-primary"
                                    id="sentinel-export-btn">Export</button>
                                <button type="button" class="button button-secondary"
                                    id="sentinel-export-quick-btn">Quick Export Last 30 Days</button>
                                <span class="sentinel-export-desc">Export logs using the selected options above, or use
                                    the quick action for the last 30 days.</span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Submit Button - Always Visible -->
        <div class="sentinel-settings-submit-container"
            style="margin-top: 30px; padding: 20px; background: #fff; border: 1px solid #ddd;">
            <input type="submit" name="submit" value="Save Settings" class="button button-primary"
                style="font-size: 16px; padding: 10px 20px;" form="sentinel-main-settings-form" />
        </div>

        <!-- Digest Cron Status -->
        <?php if (current_user_can('manage_options')): ?>
        <div
            style="margin-top: 30px; padding: 20px; background: #f0f9ff; border: 1px solid #0ea5e9; border-radius: 8px;">
            <h3 style="margin-top: 0; color: #0c4a6e;">📧 Digest Report Status</h3>

            <?php
            // Check digest cron status
            $daily_next = wp_next_scheduled('sentinel_daily_digest');
            $weekly_next = wp_next_scheduled('sentinel_weekly_digest');
            $current_time = current_time('timestamp');
            
            // Check if any digests are enabled
            $daily_enabled = !empty($settings['sentinel_email_daily_summary']) || 
                            !empty($settings['sentinel_email_daily_error']) || 
                            !empty($settings['sentinel_email_daily_user']);
            $weekly_enabled = !empty($settings['sentinel_email_weekly_health']) || 
                             !empty($settings['sentinel_email_weekly_performance']) || 
                             !empty($settings['sentinel_email_weekly_security']);
            ?>

            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 20px; margin-top: 15px;">
                <!-- Daily Digest Status -->
                <div style="padding: 15px; background: white; border-radius: 6px; border: 1px solid #e5e7eb;">
                    <h4 style="margin: 0 0 10px 0; color: #374151;">
                        <?php echo $daily_enabled ? '🟢' : '⚪'; ?> Daily Digest
                    </h4>
                    <?php if ($daily_enabled): ?>
                    <?php if ($daily_next): ?>
                    <p style="margin: 5px 0; color: #059669;">
                        <strong>Next run:</strong> <?php echo date('Y-m-d H:i:s', $daily_next); ?>
                    </p>
                    <p style="margin: 5px 0; color: #6b7280; font-size: 13px;">
                        <?php echo human_time_diff($daily_next, $current_time); ?> from now
                    </p>
                    <?php else: ?>
                    <p style="margin: 5px 0; color: #dc2626;">❌ Not scheduled</p>
                    <?php endif; ?>
                    <?php else: ?>
                    <p style="margin: 5px 0; color: #6b7280;">Disabled (no daily digests enabled)</p>
                    <?php endif; ?>
                </div>

                <!-- Weekly Digest Status -->
                <div style="padding: 15px; background: white; border-radius: 6px; border: 1px solid #e5e7eb;">
                    <h4 style="margin: 0 0 10px 0; color: #374151;">
                        <?php echo $weekly_enabled ? '🟢' : '⚪'; ?> Weekly Digest
                    </h4>
                    <?php if ($weekly_enabled): ?>
                    <?php if ($weekly_next): ?>
                    <p style="margin: 5px 0; color: #059669;">
                        <strong>Next run:</strong> <?php echo date('Y-m-d H:i:s', $weekly_next); ?>
                    </p>
                    <p style="margin: 5px 0; color: #6b7280; font-size: 13px;">
                        <?php echo human_time_diff($weekly_next, $current_time); ?> from now
                    </p>
                    <?php else: ?>
                    <p style="margin: 5px 0; color: #dc2626;">❌ Not scheduled</p>
                    <?php endif; ?>
                    <?php else: ?>
                    <p style="margin: 5px 0; color: #6b7280;">Disabled (no weekly digests enabled)</p>
                    <?php endif; ?>
                </div>
            </div>

            <div
                style="margin-top: 15px; padding: 10px; background: #fef3c7; border-radius: 4px; border-left: 3px solid #f59e0b;">
                <p style="margin: 0; color: #92400e; font-size: 13px;">
                    <strong>💡 Tip:</strong> Digest reports will only be sent if you have enabled email notifications
                    and selected at least one digest type above.
                </p>
            </div>


        </div>
        <?php endif; ?>
    </form>
</div>

<?php
// Pass data to JavaScript for post-submission handling
if (isset($needs_redirect) && $needs_redirect && isset($current_tab)) {
    wp_localize_script('sentinel-settings', 'sentinelSettingsData', array(
        'needsRedirect' => true,
        'currentTab' => $current_tab
    ));
}
?>