<?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'),
        'api_access' => isset($_POST['api_access']) ? 1 : 0
    );

    // 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),
        'memory_leak_detection_enabled' => isset($_POST['memory_leak_detection_enabled']) ? 1 : 0,
        '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'] < 1 || $performance_settings['memory_limit_threshold'] > 100) {
        $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,
        'file_monitoring_enabled' => isset($_POST['file_monitoring_enabled']) ? 1 : 0,
        // Premium file monitoring options
        'monitor_custom_files' => isset($_POST['monitor_custom_files']) ? 1 : 0,
        'custom_file_paths' => sanitize_textarea_field($_POST['custom_file_paths'] ?? ''),
        'monitor_theme_files' => isset($_POST['monitor_theme_files']) ? 1 : 0,
        'monitor_plugin_files' => isset($_POST['monitor_plugin_files']) ? 1 : 0,
        'realtime_monitoring' => isset($_POST['realtime_monitoring']) ? 1 : 0,
        'file_monitoring_frequency' => sanitize_text_field($_POST['file_monitoring_frequency'] ?? 'daily'),
        'exclude_log_files' => isset($_POST['exclude_log_files']) ? 1 : 0,
        'file_size_threshold' => absint($_POST['file_size_threshold'] ?? 10),
        'custom_exclusions' => sanitize_textarea_field($_POST['custom_exclusions'] ?? '')
    );


    // Notification settings
    $notification_settings = array(
        'email_notifications' => isset($_POST['email_notifications']) ? 1 : 0,
        'notification_email' => sanitize_email($_POST['notification_email'] ?? get_option('admin_email')),
    );

    // Security settings
    $security_settings = array(
        'ip_allowlist' => sanitize_textarea_field($_POST['ip_whitelist'] ?? '')
    );

    // Premium Security Controls (only process if premium)
    if (sentinel_is_premium()) {
        $premium_security_settings = array(
            // Brute Force Detection
            'bruteforce_threshold' => absint($_POST['bruteforce_threshold'] ?? 5),
            'bruteforce_window' => absint($_POST['bruteforce_window'] ?? 300),

            // User Enumeration Detection
            'enumeration_threshold' => absint($_POST['enumeration_threshold'] ?? 10),
            'enumeration_window' => absint($_POST['enumeration_window'] ?? 600),

            // XML-RPC Protection
            'xmlrpc_threshold' => absint($_POST['xmlrpc_threshold'] ?? 20),
            'xmlrpc_window' => absint($_POST['xmlrpc_window'] ?? 300),

            // Action Engine
            'action_mode' => sanitize_text_field($_POST['action_mode'] ?? 'observe'),
            'throttle_delay' => absint($_POST['throttle_delay'] ?? 3),
            'temp_block_duration' => absint($_POST['temp_block_duration'] ?? 3600),

            // Admin Trust
            'trust_admin_ips' => isset($_POST['trust_admin_ips']) ? 1 : 0,
            'admin_trust_duration' => absint($_POST['admin_trust_duration'] ?? 86400),

            // Incident Management
            'incident_auto_resolve' => absint($_POST['incident_auto_resolve'] ?? 21600),
            'notification_cooldown' => absint($_POST['notification_cooldown'] ?? 1800)
        );

        // Validation for premium settings
        if ($premium_security_settings['bruteforce_threshold'] < 1) {
            $premium_security_settings['bruteforce_threshold'] = 5;
        }
        if ($premium_security_settings['enumeration_threshold'] < 1) {
            $premium_security_settings['enumeration_threshold'] = 10;
        }
        if ($premium_security_settings['xmlrpc_threshold'] < 1) {
            $premium_security_settings['xmlrpc_threshold'] = 20;
        }
        if (!in_array($premium_security_settings['action_mode'], array('observe', 'throttle', 'block'))) {
            $premium_security_settings['action_mode'] = 'observe';
        }

        // Merge premium settings into security settings
        $security_settings = array_merge($security_settings, $premium_security_settings);
    }

    // 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'),
        'premium_license' => sanitize_text_field($_POST['premium_license'] ?? '')
    );

    // Save premium license separately
    if (isset($_POST['premium_license'])) {
        $license_key = sanitize_text_field($_POST['premium_license']);
        $old_license_key = get_option('sentinel_premium_license', '');

        // Always update and validate when settings are saved (user might want to re-validate same key)
        update_option('sentinel_premium_license', $license_key);

        // Always clear license cache to force fresh validation
        if (function_exists('sentinel_clear_license_cache')) {
            sentinel_clear_license_cache();
        }

        // Always trigger validation when settings are saved
        if (!empty($license_key) && function_exists('sentinel_is_premium')) {
            $validation_result = sentinel_is_premium();
            error_log('[Sentinel] License key updated and validated: ' . ($validation_result ? 'VALID' : 'INVALID'));
        }

        error_log('[Sentinel] License key updated: ' . (!empty($license_key) ? 'SET' : 'CLEARED'));
    }

    // Preserve existing API key (it's managed separately via AJAX, not the form)
    $existing_settings = get_option('sentinel_log_management', array());
    $preserved_api_key = $existing_settings['api_key'] ?? '';

    // Merge all settings
    $all_settings = array_merge($log_settings, $performance_settings, $privacy_settings, $notification_settings, $export_settings);

    // Add the preserved API key back to the settings
    if (!empty($preserved_api_key)) {
        $all_settings['api_key'] = $preserved_api_key;
    }

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

    // Validate custom file paths if provided
    $validation_messages = array();
    if (!empty($_POST['custom_file_paths']) && class_exists('Sentinel_File_Monitor')) {
        $validation_results = Sentinel_File_Monitor::validate_custom_file_paths($_POST['custom_file_paths']);

        if (!empty($validation_results['invalid'])) {
            foreach ($validation_results['invalid'] as $invalid) {
                $validation_messages[] = "Line {$invalid['line']}: {$invalid['path']} - {$invalid['message']}";
            }
        }

        if (!empty($validation_results['warnings'])) {
            foreach ($validation_results['warnings'] as $warning) {
                $validation_messages[] = "Line {$warning['line']}: {$warning['path']} - {$warning['message']}";
            }
        }

        // Store validation messages in transient for display
        if (!empty($validation_messages)) {
            set_transient('sentinel_file_path_validation', $validation_messages, 60);
        }
    }

    // Save settings
    update_option('sentinel_log_management', $all_settings);
    update_option('sentinel_security_settings', array_merge(get_option('sentinel_security_settings', array()), $security_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 custom file path validation messages
$file_path_validation = get_transient('sentinel_file_path_validation');
if (!empty($file_path_validation)) {
    echo '<div class="notice notice-warning is-dismissible">';
    echo '<p><strong>⚠️ Custom File Paths Validation:</strong></p>';
    echo '<ul style="margin-left: 20px;">';
    foreach ($file_path_validation as $message) {
        echo '<li>' . esc_html($message) . '</li>';
    }
    echo '</ul>';
    echo '<p><em>Invalid paths have been ignored. Files that don\'t exist will be monitored if they are created later.</em></p>';
    echo '</div>';
    delete_transient('sentinel_file_path_validation');
}

// 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;
        case 'retry_success':
            $count = isset($_GET['count']) ? intval($_GET['count']) : 0;
            echo '<div class="notice notice-success is-dismissible"><p>🔄 Retry completed successfully! Processed ' . $count . ' failed log entries.</p></div>';
            break;
        case 'retry_no_entries':
            echo '<div class="notice notice-info is-dismissible"><p>ℹ️ No failed log entries found in retry queue.</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,
    'memory_leak_detection_enabled' => 0,
    '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,
    // File Monitoring
    'file_monitoring_enabled' => 0,
    'monitor_custom_files' => 0,
    'custom_file_paths' => '',
    'monitor_theme_files' => 0,
    'monitor_plugin_files' => 0,
    'realtime_monitoring' => 0,
    'file_monitoring_frequency' => 'daily',
    'exclude_log_files' => 1,
    'file_size_threshold' => 10,
    'custom_exclusions' => "*.log\n*.tmp\n*.cache",
    // Notifications
    'email_notifications' => 0,
    'notification_email' => get_option('admin_email'),
    'alert_threshold' => 'medium',
    // Export
    'export_format' => 'json',
    'export_date_range' => '30',
    'api_access' => 0,
    // Premium License
    'premium_license' => get_option('sentinel_premium_license', ''),
    // --- 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);

// Load security settings separately to get current IP allowlist
$security_settings_current = get_option('sentinel_security_settings', array());
$settings['ip_allowlist'] = $security_settings_current['ip_allowlist'] ?? '';

// Load current API key for display
$current_api_key = $settings['api_key'] ?? '';

// Load premium security settings for display
if (sentinel_is_premium()) {
    $premium_security_defaults = array(
        'bruteforce_threshold' => 5,
        'bruteforce_window' => 300,
        'enumeration_threshold' => 10,
        'enumeration_window' => 600,
        'xmlrpc_threshold' => 20,
        'xmlrpc_window' => 300,
        'action_mode' => 'observe',
        'throttle_delay' => 3,
        'temp_block_duration' => 3600,
        'trust_admin_ips' => 1,
        'admin_trust_duration' => 86400,
        'incident_auto_resolve' => 21600,
        'notification_cooldown' => 1800
    );

    // Merge current values with defaults
    foreach ($premium_security_defaults as $key => $default_value) {
        $settings[$key] = $security_settings_current[$key] ?? $default_value;
    }
}

// Subtle upgrade link destination (theme handles signup). Fallback to site contact.
$upgrade_url = 'https://buy.stripe.com/3cIdR98A1g3qdKb43C0gw00';

// 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'); ?>" />
        <!-- AJAX nonce for custom events -->
        <input type="hidden" id="sentinel_ajax_nonce" value="<?php echo wp_create_nonce('sentinel_ajax_nonce'); ?>" />

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

            <!-- License & Plan Status -->
            <div class="sentinel-settings-card">
                <div class="sentinel-settings-card-header">
                    <h2 class="sentinel-settings-card-title">
                        <i class="dashicons dashicons-admin-network"></i>
                        License & Plan Status
                    </h2>
                </div>
                <div class="sentinel-settings-card-content">
                    <table class="form-table">
                        <tr>
                            <th scope="row">Current Plan</th>
                            <td>
                                <?php echo sentinel_get_plan_badge(); ?>
                                <?php if (sentinel_is_premium()): ?>
                                    <p class="description">✅ Premium features are active and available.</p>
                                <?php else: ?>
                                    <p class="description">
                                        You're using the free version. <a href="<?php echo esc_url($upgrade_url); ?>"
                                            target="_blank" rel="noopener" style="color: #0073aa;">Upgrade to Sentinel+</a>
                                        to unlock advanced monitoring, custom file paths, custom events, and priority
                                        support.
                                    </p>
                                <?php endif; ?>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="premium_license_main">License Key</label>
                            </th>
                            <td>
                                <input type="text" name="premium_license" id="premium_license_main"
                                    value="<?php echo esc_attr($settings['premium_license']); ?>" class="regular-text"
                                    placeholder="Enter your premium license key">
                                <p class="description">
                                    Enter your premium license key to unlock advanced monitoring, custom file paths, and
                                    priority support.
                                </p>
                            </td>
                        </tr>
                        <tr>
                            <th scope="row">
                                <label for="sentinel_api_key">API Key</label>
                            </th>
                            <td>
                                <div class="sentinel-api-key-container">
                                    <input type="text" id="sentinel_api_key" class="regular-text" readonly
                                        value="<?php echo esc_attr($current_api_key ? 'sent_' . str_repeat('*', 20) . substr($current_api_key, -4) : ''); ?>"
                                        placeholder="No API key generated">
                                    <div class="sentinel-api-key-actions">
                                        <?php if (empty($current_api_key)): ?>
                                            <button type="button" id="generate-api-key" class="button button-secondary">
                                                <i class="dashicons dashicons-plus-alt"></i>
                                                Generate Key
                                            </button>
                                        <?php else: ?>
                                            <button type="button" id="copy-api-key" class="button button-secondary" data-key="<?php echo esc_attr($current_api_key); ?>">
                                                <i class="dashicons dashicons-clipboard"></i>
                                                Copy
                                            </button>
                                            <button type="button" id="regenerate-api-key" class="button button-secondary">
                                                <i class="dashicons dashicons-update"></i>
                                                Regenerate
                                            </button>
                                            <button type="button" id="clear-api-key" class="button button-secondary" style="margin-left: 10px; color: #dc2626; border-color: #dc2626;">
                                                <i class="dashicons dashicons-trash"></i>
                                                Clear Key (Debug)
                                            </button>
                                        <?php endif; ?>
                                        <?php if (!empty($current_api_key)): ?>
                                            <button type="button" id="clear-api-key" class="button button-secondary" style="margin-left: 10px; color: #dc2626; border-color: #dc2626;">
                                                <i class="dashicons dashicons-trash"></i>
                                                Clear Key (Debug)
                                            </button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                                <p class="description">
                                    Use this key to authenticate REST API requests. Include it as an <code>X-Sentinel-API-Key</code> header
                                    or <code>api_key</code> parameter. <strong>Keep this key secure!</strong>
                                </p>
                                <div id="api-key-status" class="sentinel-api-key-status"></div>
                            </td>
                        </tr>
                    </table>
                </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; ?>

                        <?php
                        // Check for database retry queue
                        $retry_queue = get_transient('sentinel_retry_queue');
                        if ($retry_queue): ?>
                            <div
                                style="margin-top: 15px; padding: 10px; background: #e7f3ff; border-left: 4px solid #0073aa;">
                                <h5>⚠️ Queued Failed Logs (<?php echo count($retry_queue); ?> entries)</h5>
                                <p style="margin: 5px 0; font-size: 13px;">
                                    <strong>Status:</strong> <?php echo count($retry_queue); ?> failed log entries are queued for database retry.
                                </p>
                                <p style="margin: 5px 0; font-size: 13px;">
                                    <strong>Next Retry:</strong> <?php
                                                                    $next_retry = wp_next_scheduled('sentinel_retry_database');
                                                                    echo $next_retry ? date('Y-m-d H:i:s', $next_retry) . ' (' . human_time_diff($next_retry) . ')' : 'Not scheduled';
                                                                    ?>
                                </p>
                                <div style="margin-top: 8px;">
                                    <?php foreach (array_slice($retry_queue, -3) as $entry): ?>
                                        <p style="margin: 3px 0; font-size: 11px; color: #666;">
                                            • <?php echo esc_html($entry['event_key']); ?>
                                            (Attempt <?php echo ($entry['attempts'] + 1); ?>/<?php echo $entry['max_attempts']; ?>)
                                            - <?php echo esc_html($entry['timestamp']); ?>
                                        </p>
                                    <?php endforeach; ?>
                                    <?php if (count($retry_queue) > 3): ?>
                                        <p style="margin: 3px 0; font-size: 11px; color: #666;">
                                            <em>... and <?php echo (count($retry_queue) - 3); ?> more entries</em>
                                        </p>
                                    <?php endif; ?>
                                </div>
                                <p style="font-size: 11px; color: #666; margin-top: 10px;">
                                    <em>These entries will be automatically retried every hour when database becomes available.</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>

                            <a href="<?php echo admin_url('admin.php?page=sentinel-settings&action=retry_failed_logs'); ?>"
                                class="button button-secondary" style="margin-left: 10px;">
                                🔄 Retry Failed 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="1"
                                    max="100" 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>

                        <!-- Memory Leak Detection (Premium) -->
                        <tr id="memory_leak_detection_row"
                            style="<?php echo $settings['memory_monitoring_enabled'] ? '' : 'display: none;'; ?>">
                            <th scope="row">
                                <label for="memory_leak_detection_enabled">Memory Leak Detection</label>
                            </th>
                            <td>
                                <label <?php echo !sentinel_is_premium() ? 'class="sentinel-disabled-option"' : ''; ?>>
                                    <input type="checkbox" name="memory_leak_detection_enabled" id="memory_leak_detection_enabled"
                                        <?php echo sentinel_is_premium() ? '' : 'disabled onclick="return false;"'; ?>
                                        <?php checked(sentinel_is_premium() && !empty($settings['memory_leak_detection_enabled'])); ?>>
                                    <span>Enable advanced memory leak detection</span>
                                    <?php if (!sentinel_is_premium()): ?>
                                        <span class="sentinel-premium-indicator" title="Premium feature">●</span>
                                    <?php endif; ?>
                                </label>
                                <p class="description">Detect potential memory leaks by analyzing memory usage patterns across multiple requests. Uses smart filtering to reduce false positives.</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>






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

            <!-- File Monitoring -->
            <div class="sentinel-settings-card">
                <div class="sentinel-settings-card-header">
                    <h2 class="sentinel-settings-card-title">
                        <i class="dashicons dashicons-visibility"></i>
                        File Monitoring
                    </h2>
                </div>
                <div class="sentinel-settings-card-content">
                    <?php if (!sentinel_is_premium()): ?>
                        <div class="sentinel-premium-banner" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 15px; border-radius: 8px; margin-bottom: 20px; text-align: center;">
                            <h3 style="margin: 0 0 10px 0; color: white;">🔒 Unlock Advanced File Monitoring</h3>
                            <p style="margin: 0 0 15px 0; opacity: 0.9;">Get real-time monitoring, custom file paths, theme/plugin detection, and more with Sentinel+</p>
                            <a href="<?php echo esc_url($upgrade_url); ?>" class="button button-primary" target="_blank" rel="noopener" style="background: white; color: #667eea; border: none; padding: 10px 20px; border-radius: 5px; text-decoration: none; font-weight: bold;">
                                Upgrade to Sentinel+ →
                            </a>
                        </div>
                    <?php endif; ?>
                    <table class="form-table">
                        <tr>
                            <th scope="row">
                                <label for="file_monitoring_enabled">Critical File Monitoring</label>
                            </th>
                            <td>
                                <label>
                                    <input type="checkbox" name="file_monitoring_enabled" id="file_monitoring_enabled"
                                        value="1" <?php checked($settings['file_monitoring_enabled']); ?>>
                                    <span>Monitor critical files for changes</span>
                                </label>
                                <p class="description">Files monitored:
                                    <?php
                                    if (class_exists('Sentinel_File_Monitor')) {
                                        echo implode(', ', Sentinel_File_Monitor::get_monitored_files());
                                    } else {
                                        echo 'wp-config.php, .htaccess';
                                    }
                                    ?>
                                </p>
                            </td>
                        </tr>

                        <?php if ($settings['file_monitoring_enabled']): ?>
                            <?php if (sentinel_is_premium()): ?>
                                <tr>
                                    <th scope="row">
                                        <label for="monitor_custom_files">Custom File Monitoring</label>
                                    </th>
                                    <td>
                                        <label>
                                            <input type="checkbox" name="monitor_custom_files" id="monitor_custom_files"
                                                <?php checked(!empty($settings['monitor_custom_files'])); ?>>
                                            <span>Monitor custom file paths</span>
                                        </label>
                                        <p class="description">Monitor additional files beyond the core WordPress files.</p>

                                        <div id="custom-files-options" class="sentinel-custom-files-options">
                                            <h5>Custom File Paths</h5>
                                            <textarea name="custom_file_paths" rows="4"
                                                placeholder="Enter file paths, one per line (e.g., /path/to/important-file.php)"><?php echo esc_textarea($settings['custom_file_paths'] ?? ''); ?></textarea>
                                            <small>Enter absolute or relative paths to monitor additional files.</small>
                                        </div>
                                    </td>
                                </tr>
                            <?php endif; ?>

                            <?php if (sentinel_is_premium()): ?>
                                <tr>
                                    <th scope="row">
                                        <label>Automatic File Detection</label>
                                    </th>
                                    <td>
                                        <!-- Theme Files -->
                                        <p>
                                            <label>
                                                <input type="checkbox" name="monitor_theme_files" id="monitor_theme_files"
                                                    <?php checked(!empty($settings['monitor_theme_files'])); ?>>
                                                <span>Monitor active theme files (functions.php, style.css)</span>
                                            </label>
                                        </p>

                                        <!-- Plugin Files -->
                                        <p>
                                            <label>
                                                <input type="checkbox" name="monitor_plugin_files" id="monitor_plugin_files"
                                                    <?php checked(!empty($settings['monitor_plugin_files'])); ?>>
                                                <span>Monitor critical plugin files</span>
                                            </label>
                                        </p>

                                        <p class="description">Automatically detect and monitor theme and plugin files.</p>
                                    </td>
                                </tr>
                            <?php endif; ?>

                            <?php if (sentinel_is_premium()): ?>
                                <tr>
                                    <th scope="row">
                                        <label for="realtime_monitoring">Real-time Monitoring</label>
                                    </th>
                                    <td>
                                        <label>
                                            <input type="checkbox" name="realtime_monitoring" id="realtime_monitoring"
                                                <?php checked(!empty($settings['realtime_monitoring'])); ?>>
                                            <span>Real-time file monitoring (immediate detection)</span>
                                            <span class="sentinel-resource-warning">(Resource intensive)</span>
                                        </label>
                                        <p class="description">Monitor file changes immediately on admin actions and plugin/theme changes.</p>
                                    </td>
                                </tr>
                            <?php endif; ?>

                            <?php if (sentinel_is_premium()): ?>
                                <tr>
                                    <th scope="row">
                                        <label for="file_monitoring_frequency">Monitoring Frequency</label>
                                    </th>
                                    <td>
                                        <select name="file_monitoring_frequency" id="file_monitoring_frequency">
                                            <option value="hourly" <?php selected($settings['file_monitoring_frequency'] ?? 'daily', 'hourly'); ?>>Every Hour</option>
                                            <option value="twicedaily" <?php selected($settings['file_monitoring_frequency'] ?? 'daily', 'twicedaily'); ?>>Twice Daily</option>
                                            <option value="daily" <?php selected($settings['file_monitoring_frequency'] ?? 'daily', 'daily'); ?>>Daily</option>
                                            <option value="weekly" <?php selected($settings['file_monitoring_frequency'] ?? 'daily', 'weekly'); ?>>Weekly</option>
                                        </select>
                                        <p class="description">How often to check files for changes (in addition to real-time monitoring).</p>
                                    </td>
                                </tr>
                            <?php endif; ?>

                            <tr>
                                <th scope="row">
                                    <label>File Exclusions</label>
                                </th>
                                <td>
                                    <p>
                                        <label>
                                            <input type="checkbox" name="exclude_log_files" id="exclude_log_files"
                                                <?php checked(!empty($settings['exclude_log_files'])); ?>>
                                            <span>Exclude log files (debug.log, error.log, etc.)</span>
                                        </label>
                                    </p>
                                    <p class="description">Recommended to prevent recursive monitoring of log files.</p>

                                    <?php if (sentinel_is_premium()): ?>
                                        <h5>Custom Exclusion Patterns</h5>
                                        <textarea name="custom_exclusions" rows="3"
                                            placeholder="*.log&#10;*.tmp&#10;*.cache"><?php echo esc_textarea($settings['custom_exclusions'] ?? ''); ?></textarea>
                                        <small>Enter file patterns to exclude, one per line. Use * for wildcards.</small>
                                    <?php endif; ?>
                                </td>
                            </tr>

                            <?php if (sentinel_is_premium()): ?>
                                <tr>
                                    <th scope="row">
                                        <label for="file_size_threshold">Alert Threshold</label>
                                    </th>
                                    <td>
                                        <input type="number" name="file_size_threshold" id="file_size_threshold"
                                            value="<?php echo absint($settings['file_size_threshold'] ?? 10); ?>" min="1" max="1000">
                                        <span>bytes minimum change to trigger alert</span>
                                        <p class="description">Ignore very small file changes to reduce noise.</p>
                                    </td>
                                </tr>
                            <?php endif; ?>
                        <?php endif; ?>
                    </table>
                </div>
            </div>

            <!-- Sentinel+ Security Controls -->
            <div class="sentinel-settings-card">
                <div class="sentinel-settings-card-header">
                    <h2 class="sentinel-settings-card-title">
                        <i class="dashicons dashicons-shield-alt"></i>
                        Sentinel+ Security Controls
                    </h2>
                </div>
                <div class="sentinel-settings-card-content">
                    <?php if (!sentinel_is_premium()): ?>
                        <div class="sentinel-premium-banner" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; padding: 15px; border-radius: 8px; margin-bottom: 20px; text-align: center;">
                            <h3 style="margin: 0 0 10px 0; color: white;">🔒 Unlock Advanced Security Controls</h3>
                            <p style="margin: 0 0 15px 0; opacity: 0.9;">Get intelligent brute force detection, automatic threat blocking, and enhanced XML-RPC protection with Sentinel+</p>
                            <a href="<?php echo esc_url($upgrade_url); ?>" class="button button-primary" target="_blank" rel="noopener" style="background: white; color: #667eea; border: none; padding: 10px 20px; border-radius: 5px; text-decoration: none; font-weight: bold;">
                                Upgrade to Sentinel+ →
                            </a>
                        </div>
                    <?php else: ?>
                        <table class="form-table">
                            <tr>
                                <th scope="row">
                                    <label for="action_mode_toggle">Security Response Mode</label>
                                </th>
                                <td>
                                    <div class="sentinel-segmented-toggle" id="action_mode_toggle" role="group" aria-label="Security Response Mode">
                                        <button type="button" class="sentinel-segmented-btn <?php echo ($settings['action_mode'] === 'observe') ? 'active' : ''; ?>" data-value="observe" aria-pressed="<?php echo ($settings['action_mode'] === 'observe') ? 'true' : 'false'; ?>">Observe Only</button>
                                        <button type="button" class="sentinel-segmented-btn <?php echo ($settings['action_mode'] === 'throttle') ? 'active' : ''; ?>" data-value="throttle" aria-pressed="<?php echo ($settings['action_mode'] === 'throttle') ? 'true' : 'false'; ?>">Throttle Threats</button>
                                        <button type="button" class="sentinel-segmented-btn <?php echo ($settings['action_mode'] === 'block') ? 'active' : ''; ?>" data-value="block" aria-pressed="<?php echo ($settings['action_mode'] === 'block') ? 'true' : 'false'; ?>">Block Threats</button>
                                        <div class="slider"></div>
                                    </div>
                                    <input type="hidden" name="action_mode" id="action_mode" value="<?php echo esc_attr($settings['action_mode']); ?>">
                                    <div class="sentinel-segmented-desc">
                                        <span id="action_mode_desc">
                                            <?php
                                            switch ($settings['action_mode']) {
                                                case 'throttle':
                                                    echo 'Add delays to suspicious login attempts to slow down attacks';
                                                    break;
                                                case 'block':
                                                    echo 'Temporarily block attackers when thresholds are exceeded (recommended)';
                                                    break;
                                                default:
                                                    echo 'Log security incidents without taking any automated action';
                                                    break;
                                            }
                                            ?>
                                        </span>
                                    </div>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="bruteforce_threshold">Brute Force Detection</label>
                                </th>
                                <td>
                                    <input type="number" name="bruteforce_threshold" id="bruteforce_threshold"
                                        value="<?php echo esc_attr($settings['bruteforce_threshold']); ?>"
                                        min="3" max="20" class="small-text">
                                    <span>failed attempts within</span>
                                    <select name="bruteforce_window">
                                        <option value="60" <?php selected($settings['bruteforce_window'], 60); ?>>1 minute</option>
                                        <option value="300" <?php selected($settings['bruteforce_window'], 300); ?>>5 minutes</option>
                                        <option value="600" <?php selected($settings['bruteforce_window'], 600); ?>>10 minutes</option>
                                        <option value="1800" <?php selected($settings['bruteforce_window'], 1800); ?>>30 minutes</option>
                                        <option value="3600" <?php selected($settings['bruteforce_window'], 3600); ?>>1 hour</option>
                                    </select>
                                    <p class="description">Trigger security incident when threshold is exceeded.</p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="enumeration_threshold">User Enumeration Detection</label>
                                </th>
                                <td>
                                    <input type="number" name="enumeration_threshold" id="enumeration_threshold"
                                        value="<?php echo esc_attr($settings['enumeration_threshold']); ?>"
                                        min="5" max="50" class="small-text">
                                    <span>enumeration attempts within</span>
                                    <select name="enumeration_window">
                                        <option value="300" <?php selected($settings['enumeration_window'], 300); ?>>5 minutes</option>
                                        <option value="600" <?php selected($settings['enumeration_window'], 600); ?>>10 minutes</option>
                                        <option value="900" <?php selected($settings['enumeration_window'], 900); ?>>15 minutes</option>
                                        <option value="1800" <?php selected($settings['enumeration_window'], 1800); ?>>30 minutes</option>
                                        <option value="3600" <?php selected($settings['enumeration_window'], 3600); ?>>1 hour</option>
                                    </select>
                                    <p class="description">Detect attempts to discover valid usernames.</p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="xmlrpc_threshold">XML-RPC Protection</label>
                                </th>
                                <td>
                                    <input type="number" name="xmlrpc_threshold" id="xmlrpc_threshold"
                                        value="<?php echo esc_attr($settings['xmlrpc_threshold']); ?>"
                                        min="10" max="100" class="small-text">
                                    <span>requests within</span>
                                    <select name="xmlrpc_window">
                                        <option value="300" <?php selected($settings['xmlrpc_window'], 300); ?>>5 minutes</option>
                                        <option value="600" <?php selected($settings['xmlrpc_window'], 600); ?>>10 minutes</option>
                                        <option value="900" <?php selected($settings['xmlrpc_window'], 900); ?>>15 minutes</option>
                                        <option value="1800" <?php selected($settings['xmlrpc_window'], 1800); ?>>30 minutes</option>
                                        <option value="3600" <?php selected($settings['xmlrpc_window'], 3600); ?>>1 hour</option>
                                    </select>
                                    <p class="description">Protect against XML-RPC abuse and attacks.</p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="throttle_delay">Throttle Response Delay</label>
                                </th>
                                <td>
                                    <input type="number" name="throttle_delay" id="throttle_delay"
                                        value="<?php echo esc_attr($settings['throttle_delay']); ?>"
                                        min="1" max="10" class="small-text">
                                    <span>seconds</span>
                                    <p class="description">Delay added to suspicious login attempts when throttling mode is active.</p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="temp_block_duration">Temporary Block Duration</label>
                                </th>
                                <td>
                                    <select name="temp_block_duration" id="temp_block_duration">
                                        <option value="300" <?php selected($settings['temp_block_duration'], 300); ?>>5 minutes</option>
                                        <option value="900" <?php selected($settings['temp_block_duration'], 900); ?>>15 minutes</option>
                                        <option value="1800" <?php selected($settings['temp_block_duration'], 1800); ?>>30 minutes</option>
                                        <option value="3600" <?php selected($settings['temp_block_duration'], 3600); ?>>1 hour</option>
                                        <option value="7200" <?php selected($settings['temp_block_duration'], 7200); ?>>2 hours</option>
                                        <option value="21600" <?php selected($settings['temp_block_duration'], 21600); ?>>6 hours</option>
                                        <option value="86400" <?php selected($settings['temp_block_duration'], 86400); ?>>24 hours</option>
                                    </select>
                                    <p class="description">How long to block detected threats when blocking mode is active.</p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="trust_admin_ips">Admin Trust Mode</label>
                                </th>
                                <td>
                                    <label>
                                        <input type="checkbox" name="trust_admin_ips" id="trust_admin_ips" value="1" <?php checked($settings['trust_admin_ips']); ?>>
                                        Temporarily bypass detection for admin IPs after successful login
                                    </label>
                                    <br><br>
                                    <label for="admin_trust_duration">Trust Duration:</label>
                                    <select name="admin_trust_duration" id="admin_trust_duration">
                                        <option value="3600" <?php selected($settings['admin_trust_duration'], 3600); ?>>1 hour</option>
                                        <option value="7200" <?php selected($settings['admin_trust_duration'], 7200); ?>>2 hours</option>
                                        <option value="21600" <?php selected($settings['admin_trust_duration'], 21600); ?>>6 hours</option>
                                        <option value="43200" <?php selected($settings['admin_trust_duration'], 43200); ?>>12 hours</option>
                                        <option value="86400" <?php selected($settings['admin_trust_duration'], 86400); ?>>24 hours</option>
                                    </select>
                                    <p class="description">Reduces false positives by trusting known admin IPs for a limited time.</p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="incident_auto_resolve">Incident Management</label>
                                </th>
                                <td>
                                    <label for="incident_auto_resolve">Auto-resolve incidents after:</label>
                                    <select name="incident_auto_resolve" id="incident_auto_resolve">
                                        <option value="1800" <?php selected($settings['incident_auto_resolve'], 1800); ?>>30 minutes</option>
                                        <option value="3600" <?php selected($settings['incident_auto_resolve'], 3600); ?>>1 hour</option>
                                        <option value="7200" <?php selected($settings['incident_auto_resolve'], 7200); ?>>2 hours</option>
                                        <option value="21600" <?php selected($settings['incident_auto_resolve'], 21600); ?>>6 hours</option>
                                        <option value="43200" <?php selected($settings['incident_auto_resolve'], 43200); ?>>12 hours</option>
                                        <option value="86400" <?php selected($settings['incident_auto_resolve'], 86400); ?>>24 hours</option>
                                    </select>
                                    <br><br>
                                    <label for="notification_cooldown">Notification cooldown:</label>
                                    <select name="notification_cooldown" id="notification_cooldown">
                                        <option value="300" <?php selected($settings['notification_cooldown'], 300); ?>>5 minutes</option>
                                        <option value="900" <?php selected($settings['notification_cooldown'], 900); ?>>15 minutes</option>
                                        <option value="1800" <?php selected($settings['notification_cooldown'], 1800); ?>>30 minutes</option>
                                        <option value="3600" <?php selected($settings['notification_cooldown'], 3600); ?>>1 hour</option>
                                    </select>
                                    <p class="description">Automatic incident cleanup and notification rate limiting.</p>
                                </td>
                            </tr>
                            <tr>
                                <th scope="row">
                                    <label for="ip_whitelist">IP Allowlist</label>
                                </th>
                                <td>
                                    <textarea name="ip_whitelist" id="ip_whitelist" rows="4" class="large-text"
                                        placeholder="192.168.1.100&#10;10.0.0.0/24&#10;203.0.113.5"><?php echo esc_textarea($settings['ip_allowlist']); ?></textarea>
                                    <p class="description">Enter IP addresses or CIDR ranges that should bypass authentication limits, one per line. Leave blank to disable IP allowlist.</p>
                                </td>
                            </tr>
                        </table>
                    <?php endif; ?>
                </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
    ));
}
?>
