<?php

/**
 * Guard Dog Settings Page
 *
 * @package GuardDog
 * @since 1.6.0
 */

if (!defined('ABSPATH')) {
    exit;
}

class Guard_Dog_Settings_Page {
    /**
     * Maximum number of bytes to read from the end of debug.log for the in-page viewer.
     */
    private const DEBUG_LOG_VIEWER_MAX_BYTES = 1048576;

    /**
     * Maximum number of parsed log entries to render in the in-page viewer.
     */
    private const DEBUG_LOG_VIEWER_MAX_ENTRIES = 200;

    /**
     * Feature instances
     * @var array
     */
    private $features;

    /**
     * Current active tab
     * @var string
     */
    private $current_tab;

    /**
     * Available tabs configuration
     * @var array
     */
    private $tabs;

    /**
     * Parsed debug log viewer state for the current request.
     *
     * @var array|null
     */
    private $debug_log_viewer_data = null;

    /**
     * Parsed support report viewer state for the current request.
     *
     * @var array|null
     */
    private $support_report_viewer_data = null;

    /**
     * Constructor
     *
     * @param array $features Feature class instances
     */
    public function __construct(array $features = []) {
        $this->features = $features;
        $this->initialize_tabs();
        $this->determine_current_tab();
    }

    /**
     * Initialize tabs configuration
     */
    private function initialize_tabs(): void {
        $this->tabs = [
            'debug' => [
                'label' => __('Debug Settings', 'guard-dog'),
                'icon' => 'dashicons-admin-tools',
            ],
            'email_provider' => [
                'label' => __('Email Provider', 'guard-dog'),
                'icon' => 'dashicons-email-alt',
            ],
            'data' => [
                'label' => __('Data Management', 'guard-dog'),
                'icon' => 'dashicons-database-remove',
            ],
        ];
    }

    /**
     * Determine the current active tab
     */
    private function determine_current_tab(): void {
        // Default tab
        $this->current_tab = 'debug';

        // Only process tab parameter if nonce is valid and parameter exists
        if (isset($_GET['tab']) && isset($_GET['_wpnonce']) && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'guard_dog_settings_tab')) {
            $tab_param = sanitize_text_field(wp_unslash($_GET['tab']));
            if (array_key_exists($tab_param, $this->tabs)) {
                $this->current_tab = $tab_param;
            }
        }
    }

    /**
     * Render the settings page
     */
    public function render(): void {
        // Handle form actions first
        $this->handle_form_actions();
        
        // Render main page with integrated tabs
        $this->render_page_with_tabs();
    }

    /**
     * Render the page with integrated tabbed interface
     */
    private function render_page_with_tabs(): void {
        ?>
        <div class="wrap guard-dog-admin">
            <h1 class="guard-dog-page-title">
                <span class="dashicons dashicons-admin-settings"></span>
                <?php esc_html_e('Settings', 'guard-dog'); ?>
            </h1>
            
            <p class="guard-dog-page-subtitle">
                <?php esc_html_e('Configure global Guard Dog settings, debug options, and maintenance preferences.', 'guard-dog'); ?>
            </p>

            <?php 
            // Display settings messages (success/error notifications)
            settings_errors('guard_dog_debug_settings');
            settings_errors('guard_dog_email_provider_settings');
            settings_errors('guard_dog_data_management');
            
            // Clear the global settings errors to prevent WordPress from auto-displaying them elsewhere
            global $wp_settings_errors;
            unset($wp_settings_errors['guard_dog_data_management']);
            ?>

            <div class="guard-dog-admin-grid">
                <div class="guard-dog-main-content">
                    <?php 
                    // Display health check results if available
                    $this->render_health_check_results();
                    $this->render_support_report_viewer();
                    ?>
                    
                    <!-- Integrated Tabbed Interface -->
                    <div class="guard-dog-tabbed-interface">
                        <nav class="guard-dog-tab-nav">
                            <?php foreach ($this->tabs as $tab_id => $tab_config): ?>
                                <a href="<?php echo esc_url(add_query_arg(['tab' => $tab_id, '_wpnonce' => wp_create_nonce('guard_dog_settings_tab')])); ?>" 
                                   class="guard-dog-tab-link<?php echo esc_attr($this->current_tab === $tab_id ? ' active' : ''); ?>" 
                                   data-tab="<?php echo esc_attr($tab_id); ?>"
                                   data-storage-key="guard_dog_settings_active_tab">
                                    <?php if (isset($tab_config['icon'])): ?>
                                        <span class="dashicons <?php echo esc_attr($tab_config['icon']); ?>"></span>
                                    <?php endif; ?>
                                    <?php echo esc_html($tab_config['label']); ?>
                                </a>
                            <?php endforeach; ?>
                        </nav>

                        <div class="guard-dog-tab-content">
                            <?php foreach ($this->tabs as $tab_id => $tab_config): ?>
                                <div id="<?php echo esc_attr($tab_id); ?>" 
                                     class="guard-dog-tab-panel<?php echo esc_attr($this->current_tab === $tab_id ? ' active' : ''); ?>">
                                    <?php $this->render_tab_content($tab_id); ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <div class="guard-dog-sidebar">
                    <?php $this->render_system_info(); ?>
                    <?php $this->render_tools(); ?>
                </div>
            </div>
        </div>
        <?php
        
        // Enqueue scripts and styles for this page
        $this->enqueue_settings_assets();
    }

    /**
     * Render content for a specific tab
     *
     * @param string $tab_id The tab identifier
     */
    private function render_tab_content(string $tab_id): void {
        switch ($tab_id) {
            case 'debug':
                $this->render_debug_tab();
                break;
            case 'email_provider':
                $this->render_email_provider_tab();
                break;
            case 'data':
                $this->render_data_management_tab();
                break;
            default:
                ?>
                <p><?php esc_html_e('Invalid tab selected.', 'guard-dog'); ?></p>
                <?php
                break;
        }
    }

    /**
     * Render the debug tab content
     */
    private function render_debug_tab(): void {
        ?>
        <h3>
            <span class="dashicons dashicons-admin-tools"></span>
            <?php esc_html_e('Debug Settings', 'guard-dog'); ?>
        </h3>

        <p><?php esc_html_e('Configure debug logging options for troubleshooting and development.', 'guard-dog'); ?></p>

        <?php $this->render_debug_log_viewer(); ?>

        <form method="post" action="options.php" class="guard-dog-debug-form">
            <?php 
            settings_fields('guard_dog_debug_settings');
            do_settings_sections('guard_dog_debug_settings');
            ?>
            
            <?php submit_button(__('Save Debug Settings', 'guard-dog'), 'primary', 'submit', false, ['id' => 'submit-debug']); ?>
        </form>
        <?php
    }

    /**
     * Render the email provider tab content
     */
    private function render_email_provider_tab(): void {
        ?>
        <h3>
            <span class="dashicons dashicons-email-alt"></span>
            <?php esc_html_e('Email Provider Configuration', 'guard-dog'); ?>
        </h3>

        <p><?php esc_html_e('Configure your email service provider for sending two-factor authentication codes and other security notifications.', 'guard-dog'); ?></p>

        <form method="post" action="options.php" class="guard-dog-email-provider-form">
            <?php 
            settings_fields('guard_dog_email_provider_settings');
            ?>
            <input type="hidden" name="guard_dog_email_provider_settings[__submitted]" value="1" />
            <input type="hidden" name="guard_dog_email_provider_global_override" value="0" />
            <?php
            do_settings_sections('guard_dog_email_provider_settings');
            ?>
            
            <?php submit_button(__('Save Email Provider Settings', 'guard-dog'), 'primary', 'submit', false, ['id' => 'submit-email-provider']); ?>
        </form>
        <?php
    }

    /**
     * Render the data management tab content
     */
    private function render_data_management_tab(): void {
        ?>
        <h3>
            <span class="dashicons dashicons-database-remove"></span>
            <?php esc_html_e('Data Management', 'guard-dog'); ?>
        </h3>

        <p><?php esc_html_e('Manage your Guard Dog data and settings. Use these tools carefully as they cannot be undone.', 'guard-dog'); ?></p>

        <div class="guard-dog-info-box">
            <h4>ℹ️ <?php esc_html_e('Advanced Data Management', 'guard-dog'); ?></h4>
            <p><?php esc_html_e('For more advanced data management including export, cleanup, and log retention settings, visit the', 'guard-dog'); ?> 
            <a href="<?php echo esc_url(admin_url('admin.php?page=guard-dog-logs&tab=export')); ?>"><?php esc_html_e('Activity Log → Export & Cleanup', 'guard-dog'); ?></a> <?php esc_html_e('section.', 'guard-dog'); ?></p>
        </div>

        <div class="guard-dog-data-management-grid">
            <div>
                <form method="post" class="guard-dog-inline-form">
                    <?php wp_nonce_field('guard_dog_settings_action', 'guard_dog_nonce'); ?>
                    <input type="hidden" name="guard_dog_action" value="clear_logs">
                    <button type="submit" class="button guard-dog-data-management-button guard-dog-clear-logs-btn">
                        <?php esc_html_e('Clear All Logs', 'guard-dog'); ?>
                    </button>
                </form>
                <p class="description guard-dog-data-management-description">
                    <?php esc_html_e('Remove all activity logs immediately', 'guard-dog'); ?>
                </p>
            </div>
            
            <div>
                <form method="post" class="guard-dog-inline-form">
                    <?php wp_nonce_field('guard_dog_settings_action', 'guard_dog_nonce'); ?>
                    <input type="hidden" name="guard_dog_action" value="reset_lockouts">
                    <button type="submit" class="button guard-dog-data-management-button guard-dog-reset-lockouts-btn">
                        <?php esc_html_e('Reset Lockouts', 'guard-dog'); ?>
                    </button>
                </form>
                <p class="description guard-dog-data-management-description">
                    <?php esc_html_e('Clear all IP lockouts immediately', 'guard-dog'); ?>
                </p>
            </div>
            
            <div>
                <form method="post" class="guard-dog-inline-form">
                    <?php wp_nonce_field('guard_dog_settings_action', 'guard_dog_nonce'); ?>
                    <input type="hidden" name="guard_dog_action" value="export_settings">
                    <button type="submit" class="button guard-dog-data-management-button">
                        <?php esc_html_e('Export Settings', 'guard-dog'); ?>
                    </button>
                </form>
                <p class="description guard-dog-data-management-description">
                    <?php esc_html_e('Download configuration backup', 'guard-dog'); ?>
                </p>
            </div>
        </div>

        <div class="guard-dog-warning-box">
            <h4>⚠️ <?php esc_html_e('Reset All Settings', 'guard-dog'); ?></h4>
            <p><?php esc_html_e('This will restore all Guard Dog settings to their default values. This action cannot be undone.', 'guard-dog'); ?></p>
            <form method="post" class="guard-dog-inline-form">
                <?php wp_nonce_field('guard_dog_settings_action', 'guard_dog_nonce'); ?>
                <input type="hidden" name="guard_dog_action" value="reset_settings">
                <button type="submit" class="button button-secondary guard-dog-reset-button guard-dog-reset-all-settings-btn">
                    <?php esc_html_e('Reset All Settings', 'guard-dog'); ?>
                </button>
            </form>
        </div>
        <?php
    }

    /**
     * Handle form actions (data management tools)
     */
    private function handle_form_actions(): void {
        // Prevent multiple processing of the same request
        static $processed = false;
        if ($processed) {
            return;
        }
        
        if (!isset($_POST['guard_dog_action']) || !isset($_POST['guard_dog_nonce'])) {
            return;
        }

        // Mark as processed to prevent duplicate execution
        $processed = true;
        
        // Verify nonce first - use WordPress recommended pattern
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['guard_dog_nonce'])), 'guard_dog_settings_action')) {
            add_settings_error('guard_dog_data_management', 'invalid_nonce_' . time(), __('Security check failed. Please try again.', 'guard-dog'), 'error');
            return;
        }

        if (!current_user_can('manage_options')) {
            add_settings_error('guard_dog_data_management', 'permission_denied_' . time(), __('You do not have permission to perform this action.', 'guard-dog'), 'error');
            return;
        }

        // Now safe to access POST data after nonce validation
        $action = sanitize_text_field(wp_unslash($_POST['guard_dog_action']));

        switch ($action) {
            case 'clear_logs':
                $this->handle_clear_logs();
                break;
            case 'reset_lockouts':
                $this->handle_reset_lockouts();
                break;
            case 'export_settings':
                $this->handle_export_settings();
                break;
            case 'reset_settings':
                $this->handle_reset_settings();
                break;
            case 'run_health_check':
                $this->run_health_check();
                break;
            case 'view_debug_log':
                $this->view_debug_log();
                break;
            case 'generate_support_report':
                $this->generate_support_report();
                break;
            default:
                add_settings_error('guard_dog_data_management', 'invalid_action_' . time(), __('Invalid action specified.', 'guard-dog'), 'error');
                break;
        }
    }

    /**
     * Handle clearing all logs
     */
    private function handle_clear_logs(): void {
        global $wpdb;
        
        $table_name = $wpdb->prefix . 'guard_dog_logs';
        
        // Check if table exists first
        // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        // Table name is constructed from $wpdb->prefix which is WordPress-controlled, not user input
        // Direct database queries are necessary for administrative functions like clearing logs
        // Table name is escaped using esc_sql() for additional security
        $escaped_table_name = esc_sql($table_name);
        if ($wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $table_name)) !== $table_name) {
            add_settings_error('guard_dog_data_management', 'clear_logs_no_table_' . time(), __('Activity log table does not exist.', 'guard-dog'), 'error');
            return;
        }
        
        $result = $wpdb->query("TRUNCATE TABLE `{$escaped_table_name}`");
        // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
        
        if ($result !== false) {
            // Log the action
            Guard_Dog()->activity_log->add_log_entry('settings_action', [
                'username' => wp_get_current_user()->user_login,
                'user_id' => get_current_user_id(),
                'details' => [
                    'action' => 'logs_cleared',
                    'cleared_by' => wp_get_current_user()->user_login,
                ]
            ]);
            
            add_settings_error('guard_dog_data_management', 'clear_logs_success_' . time(), __('All activity logs have been cleared successfully.', 'guard-dog'), 'success');
        } else {
            add_settings_error('guard_dog_data_management', 'clear_logs_failed_' . time(), __('Failed to clear activity logs.', 'guard-dog'), 'error');
        }
    }

    /**
     * Handle resetting all lockouts
     */
    private function handle_reset_lockouts(): void {
        try {
            // Clear all lockout-related options
            $lockout_options = [
                'guard_dog_ip_lockouts',
                'guard_dog_username_lockouts',
                'guard_dog_failed_attempts',
            ];
            
            foreach ($lockout_options as $option) {
                delete_option($option);
            }
            
            // Log the action
            Guard_Dog()->activity_log->add_log_entry('settings_action', [
                'username' => wp_get_current_user()->user_login,
                'user_id' => get_current_user_id(),
                'details' => [
                    'action' => 'lockouts_reset',
                    'reset_by' => wp_get_current_user()->user_login,
                ]
            ]);
            
            add_settings_error('guard_dog_data_management', 'reset_lockouts_success_' . time(), __('All lockouts have been reset successfully.', 'guard-dog'), 'success');
        } catch (Exception $e) {
            Guard_Dog()->debug->error('Failed to reset lockouts', 'settings', [
                'error' => $e->getMessage(),
                'user_id' => get_current_user_id(),
            ]);
            
            add_settings_error('guard_dog_data_management', 'reset_lockouts_failed_' . time(), __('Failed to reset lockouts. Please try again.', 'guard-dog'), 'error');
        }
    }

    /**
     * Handle exporting settings
     */
    private function handle_export_settings(): void {
        try {
            // Get all Guard Dog options
            global $wpdb;
            // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
            // Direct database query is necessary for settings export functionality
            $options = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE %s",
                    'guard_dog_%'
                )
            );
            // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
            
            // Prepare export data
            $export_data = [
                'export_date' => current_time('mysql'),
                'site_url' => get_site_url(),
                'guard_dog_version' => GUARD_DOG_VERSION,
                'settings' => [],
            ];
            
            foreach ($options as $option) {
                $export_data['settings'][$option->option_name] = $this->redact_sensitive_export_data(
                    maybe_unserialize($option->option_value),
                    $option->option_name
                );
            }
            
            // Generate JSON file
            $json_data = wp_json_encode($export_data, JSON_PRETTY_PRINT);
            
            if ($json_data === false) {
                throw new Exception('Failed to encode settings data');
            }
            
            // Set headers for download
            $filename = 'guard-dog-settings-' . gmdate('Y-m-d-H-i-s') . '.json';
            
            header('Content-Type: application/json');
            header('Content-Disposition: attachment; filename="' . esc_attr($filename) . '"');
            header('Content-Length: ' . strlen($json_data));
            header('Cache-Control: no-cache, must-revalidate');
            header('Pragma: no-cache');

            // phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped
            // wp_json_encode() properly escapes JSON output and prevents XSS.
            // This is safe JSON data export, not HTML output.
            // The JSON format requires specific escaping rules that are handled by wp_json_encode().
            echo $json_data;
            // phpcs:enable WordPress.Security.EscapeOutput.OutputNotEscaped
            exit;
            
        } catch (Exception $e) {
            Guard_Dog()->debug->error('Failed to export settings', 'settings', [
                'error' => $e->getMessage(),
                'user_id' => get_current_user_id(),
            ]);
            
            add_settings_error('guard_dog_data_management', 'export_settings_failed_' . time(), __('Failed to export settings. Please try again.', 'guard-dog'), 'error');
        }
    }

    /**
     * Redact secrets from exported settings and support reports.
     *
     * @param mixed  $value Data to redact.
     * @param string $key Current key or option name.
     * @return mixed Redacted data.
     */
    private function redact_sensitive_export_data($value, string $key = '') {
        if ($this->is_sensitive_export_key($key)) {
            return empty($value) ? $value : '[REDACTED]';
        }

        if (is_array($value)) {
            $redacted = [];
            foreach ($value as $child_key => $child_value) {
                $redacted[$child_key] = $this->redact_sensitive_export_data($child_value, (string) $child_key);
            }
            return $redacted;
        }

        if (is_object($value)) {
            $redacted = clone $value;
            foreach (get_object_vars($redacted) as $child_key => $child_value) {
                $redacted->{$child_key} = $this->redact_sensitive_export_data($child_value, (string) $child_key);
            }
            return $redacted;
        }

        return $value;
    }

    /**
     * Check whether a settings/export key should be redacted.
     *
     * @param string $key Key or option name.
     * @return bool True when the key likely contains a secret.
     */
    private function is_sensitive_export_key(string $key): bool {
        $key = strtolower($key);
        $sensitive_markers = [
            'access_token',
            'api_key',
            'apikey',
            'authorization',
            'bearer',
            'client_secret',
            'cookie',
            'key_file',
            'password',
            'private_key',
            'refresh_token',
            'secret',
            'token',
        ];

        foreach ($sensitive_markers as $marker) {
            if (strpos($key, $marker) !== false) {
                return true;
            }
        }

        return false;
    }

    /**
     * Handle resetting all settings
     */
    private function handle_reset_settings(): void {
        try {
            // Get all Guard Dog options
            global $wpdb;
            // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
            // Direct database query is necessary for settings reset functionality
            $options = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE %s",
                    'guard_dog_%'
                )
            );
            // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
            
            // Delete all Guard Dog options
            foreach ($options as $option) {
                delete_option($option->option_name);
            }
            
            // Clear activity log table
            $table_name = $wpdb->prefix . 'guard_dog_logs';
            // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
            // TRUNCATE TABLE requires table name interpolation - this is safe as it's constructed from wpdb->prefix
            // Direct database query is necessary for settings reset functionality
            // Table name is escaped using esc_sql() for additional security
            $escaped_table_name = esc_sql($table_name);
            $wpdb->query("TRUNCATE TABLE `{$escaped_table_name}`");
            // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
            
            // Clear user meta for 2FA and other Guard Dog data
            // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.SlowDBQuery.slow_db_query_meta_key
            // Direct database query is necessary for settings reset functionality
            // Meta key pattern matching is required for bulk deletion of plugin-specific user meta
            $wpdb->delete(
                $wpdb->usermeta,
                ['meta_key' => 'guard_dog_%'],
                ['%s']
            );
            // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching,WordPress.DB.SlowDBQuery.slow_db_query_meta_key
            
            // Log the action
            Guard_Dog()->activity_log->add_log_entry('settings_action', [
                'username' => wp_get_current_user()->user_login,
                'user_id' => get_current_user_id(),
                'details' => [
                    'action' => 'all_settings_reset',
                    'reset_by' => wp_get_current_user()->user_login,
                ]
            ]);
            
            add_settings_error('guard_dog_data_management', 'reset_settings_success_' . time(), __('All Guard Dog settings have been reset to defaults. The plugin will now use default configuration.', 'guard-dog'), 'success');
            
        } catch (Exception $e) {
            Guard_Dog()->debug->error('Failed to reset all settings', 'settings', [
                'error' => $e->getMessage(),
                'user_id' => get_current_user_id(),
            ]);
            
            add_settings_error('guard_dog_data_management', 'reset_settings_failed_' . time(), __('Failed to reset settings. Please try again.', 'guard-dog'), 'error');
        }
    }

    public static function register_settings(): void {
        // Register debug settings (separate group for debug tab)
        register_setting('guard_dog_debug_settings', 'guard_dog_debug_enabled', [
            'type' => 'boolean',
            'sanitize_callback' => function($input) {
                return !empty($input);
            },
            'default' => false,
        ]);
        
        register_setting('guard_dog_debug_settings', 'guard_dog_debug_level', [
            'type' => 'string',
            'sanitize_callback' => function($input) {
                $valid_levels = ['error', 'warning', 'info', 'debug'];
                return in_array($input, $valid_levels, true) ? $input : 'error';
            },
            'default' => 'error',
        ]);

        // Register email provider settings
        register_setting('guard_dog_email_provider_settings', 'guard_dog_email_provider', [
            'type' => 'string',
            'sanitize_callback' => function($input) {
                if (!isset($_POST['guard_dog_email_provider']) && ((string) $input) === '') {
                    return get_option('guard_dog_email_provider', '');
                }

                return sanitize_key((string) $input);
            },
            'default' => '',
        ]);
        
        register_setting('guard_dog_email_provider_settings', 'guard_dog_email_provider_global_override', [
            'type' => 'boolean',
            'sanitize_callback' => function($input) {
                return !empty($input);
            },
            'default' => false,
        ]);

        register_setting('guard_dog_email_provider_settings', 'guard_dog_email_provider_settings', [
            'type' => 'array',
            'sanitize_callback' => function($input) {
                $has_submitted_settings = isset($_POST['guard_dog_email_provider_settings']) && is_array($_POST['guard_dog_email_provider_settings']);

                if (!is_array($input)) {
                    return get_option('guard_dog_email_provider_settings', []);
                }

                $form_submitted = isset($input['__submitted']) && (string) $input['__submitted'] === '1';
                if ($form_submitted) {
                    unset($input['__submitted']);
                    $has_submitted_settings = true;
                }

                // Preserve settings when another settings group submits without this payload.
                // Allow programmatic update_option() calls (e.g., OAuth callback) with array input.
                if (!$has_submitted_settings && $input === []) {
                    return get_option('guard_dog_email_provider_settings', []);
                }

                $existing_settings = get_option('guard_dog_email_provider_settings', []);
                $provider = isset($_POST['guard_dog_email_provider'])
                    ? sanitize_key((string) wp_unslash($_POST['guard_dog_email_provider']))
                    : sanitize_key((string) get_option('guard_dog_email_provider', ''));

                if ($has_submitted_settings && $input === []) {
                    return [];
                }

                if (class_exists('Guard_Dog_Email_Provider')) {
                    return Guard_Dog_Email_Provider::sanitize_provider_settings($provider, $input, $existing_settings);
                }

                $sanitized = [];
                foreach ($input as $key => $value) {
                    $sanitized[sanitize_text_field((string) $key)] = sanitize_text_field((string) $value);
                }

                return $sanitized;
            },
            'default' => [],
        ]);

        // Add settings sections and fields
        self::add_settings_sections();
        
        // Add AJAX handlers
        add_action('wp_ajax_guard_dog_test_email_provider', [self::class, 'ajax_test_email_provider']);
        add_action('wp_ajax_guard_dog_google_oauth_start', [self::class, 'ajax_google_oauth_start']);
        add_action('wp_ajax_guard_dog_google_oauth_callback', [self::class, 'ajax_google_oauth_callback']);
        add_action('wp_ajax_guard_dog_google_oauth_disconnect', [self::class, 'ajax_google_oauth_disconnect']);
        add_action('wp_ajax_guard_dog_google_alias_preflight', [self::class, 'ajax_google_alias_preflight']);
        add_action('wp_ajax_guard_dog_google_aliases_list', [self::class, 'ajax_google_aliases_list']);
    }

    /**
     * Add settings sections and fields
     */
    public static function add_settings_sections(): void {
        // Add debug settings section (to debug settings group)
        add_settings_section(
            'guard_dog_debug_section',
            '',
            '__return_empty_string',
            'guard_dog_debug_settings'
        );

        // Add debug enabled field
        add_settings_field(
            'guard_dog_debug_enabled',
            __('Enable Debug Logging', 'guard-dog'),
            [self::class, 'render_debug_enabled_field'],
            'guard_dog_debug_settings',
            'guard_dog_debug_section'
        );

        // Add debug level field
        add_settings_field(
            'guard_dog_debug_level',
            __('Debug Level', 'guard-dog'),
            [self::class, 'render_debug_level_field'],
            'guard_dog_debug_settings',
            'guard_dog_debug_section'
        );

        // Add email provider settings section
        add_settings_section(
            'guard_dog_email_provider_section',
            '',
            '__return_empty_string',
            'guard_dog_email_provider_settings'
        );

        // Add email provider field
        add_settings_field(
            'guard_dog_email_provider',
            __('Email Provider', 'guard-dog'),
            [self::class, 'render_email_provider_field'],
            'guard_dog_email_provider_settings',
            'guard_dog_email_provider_section'
        );

    }

    /**
     * Render section descriptions
     */
    public static function render_data_section_description(): void {
        ?>
        <p><?php esc_html_e('Configure data retention and management settings.', 'guard-dog'); ?></p>
        <?php
    }

    /**
     * Render field methods
     */
    public static function render_debug_enabled_field(): void {
        $enabled = get_option('guard_dog_debug_enabled', false);
        ?>
        <input type="checkbox" name="guard_dog_debug_enabled" value="1" <?php checked($enabled, true); ?> />
        <p class="description"><?php esc_html_e('Enable debug logging for troubleshooting.', 'guard-dog'); ?></p>
        <?php
    }

    public static function render_debug_level_field(): void {
        $level = get_option('guard_dog_debug_level', 'error');
        ?>
        <select name="guard_dog_debug_level">
            <option value="error" <?php selected($level, 'error'); ?>><?php esc_html_e('Error', 'guard-dog'); ?></option>
            <option value="warning" <?php selected($level, 'warning'); ?>><?php esc_html_e('Warning', 'guard-dog'); ?></option>
            <option value="info" <?php selected($level, 'info'); ?>><?php esc_html_e('Info', 'guard-dog'); ?></option>
            <option value="debug" <?php selected($level, 'debug'); ?>><?php esc_html_e('Debug', 'guard-dog'); ?></option>
        </select>

        <p class="description"><?php esc_html_e('Minimum level of debug messages to log.', 'guard-dog'); ?></p>
        <?php
    }

    public static function render_log_retention_field(): void {
        $retention = get_option('guard_dog_log_retention_days', 30);
        ?>
        <input type="number" name="guard_dog_log_retention_days" value="<?php echo esc_attr($retention); ?>" min="1" max="365" class="small-text" />
        <p class="description"><?php esc_html_e('Number of days to keep log entries (1-365).', 'guard-dog'); ?></p>
        <?php
    }

    public static function render_max_log_entries_field(): void {
        $max_entries = get_option('guard_dog_max_log_entries', 10000);
        ?>
        <input type="number" name="guard_dog_max_log_entries" value="<?php echo esc_attr($max_entries); ?>" min="100" max="100000" class="small-text" />
        <p class="description"><?php esc_html_e('Maximum number of log entries to store (100-100000).', 'guard-dog'); ?></p>
        <?php
    }

    /**
     * AJAX handler to test email provider configuration
     */
    public static function ajax_test_email_provider(): void {
        // Check if user has permission first
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'guard-dog')], 403);
        }

        // Check if nonce is present before accessing it
        if (!isset($_POST['nonce'])) {
            wp_send_json_error(['message' => __('Security verification failed.', 'guard-dog')], 403);
        }

        // Verify nonce before processing any POST data
        $nonce = sanitize_text_field(wp_unslash($_POST['nonce']));
        if (!wp_verify_nonce($nonce, 'guard_dog_test_email_provider')) {
            wp_send_json_error(['message' => __('Security verification failed.', 'guard-dog')], 403);
        }

        // Prevent duplicate requests by checking for recent test emails
        $last_test_time = get_transient('guard_dog_last_email_test_' . get_current_user_id());
        if ($last_test_time && (time() - $last_test_time) < 3) {
            wp_send_json_error(['message' => __('Please wait a few seconds before sending another test email.', 'guard-dog')], 429);
        }
        
        // Set transient to prevent duplicate requests
        set_transient('guard_dog_last_email_test_' . get_current_user_id(), time(), 10);
        
        // Log the request for debugging (now safe to access POST data)
        if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
            Guard_Dog()->debug->info('Email provider test request received', 'email_provider', [
                'user_id' => get_current_user_id()
            ]);
        }

        $test_email = sanitize_email(wp_unslash($_POST['test_email'] ?? ''));
        if (empty($test_email)) {
            if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
                Guard_Dog()->debug->warning('Empty test email provided', 'email_provider', [
                    'test_email' => $test_email
                ]);
            }
            wp_send_json_error(['message' => __('Please provide a valid email address.', 'guard-dog')], 400);
        }

        // Get email provider instance
        $email_provider = null;
        if (function_exists('Guard_Dog') && isset(Guard_Dog()->features['email_provider'])) {
            $email_provider = Guard_Dog()->features['email_provider'];
            if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
                Guard_Dog()->debug->info('Using email provider from Guard Dog features', 'email_provider');
            }
        } elseif (class_exists('Guard_Dog_Email_Provider')) {
            $email_provider = new Guard_Dog_Email_Provider();
            if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
                Guard_Dog()->debug->info('Created new email provider instance', 'email_provider');
            }
        }

        if (!$email_provider) {
            if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
                Guard_Dog()->debug->error('Email provider not available', 'email_provider');
            }
            wp_send_json_error(['message' => __('Email provider not available.', 'guard-dog')], 500);
        }

        // Test the configuration
        if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
            Guard_Dog()->debug->info('Testing email provider configuration', 'email_provider', [
                'test_email' => $test_email
            ]);
        }
        
        $result = $email_provider->test_configuration($test_email);

        if ($result['success']) {
            if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
                Guard_Dog()->debug->info('Email provider test successful', 'email_provider', [
                    'test_email' => $test_email
                ]);
            }
            wp_send_json_success([
                // Translators: %s is the email address where the test email was sent.
                'message' => sprintf(esc_html__('Test email sent successfully to %s. Please check your inbox.', 'guard-dog'), esc_html($test_email))
            ]);
        } else {
            if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
                Guard_Dog()->debug->error('Email provider test failed', 'email_provider', [
                    'test_email' => $test_email,
                    'error' => $result['message']
                ]);
            }
            wp_send_json_error([
                'message' => $result['message']
            ], 400);
        }
    }

    /**
     * Build Settings -> Email Provider tab URL with nonce.
     *
     * @param array $extra_args Additional query args.
     * @return string
     */
    private static function get_email_provider_tab_url(array $extra_args = []): string {
        $args = array_merge([
            'page' => 'guard-dog-settings',
            'tab' => 'email_provider',
            '_wpnonce' => wp_create_nonce('guard_dog_settings_tab'),
        ], $extra_args);

        return add_query_arg($args, admin_url('admin.php'));
    }

    /**
     * Google OAuth callback URL used in Google Cloud Console.
     *
     * @return string
     */
    private static function get_google_oauth_callback_url(): string {
        return admin_url('admin-ajax.php?action=guard_dog_google_oauth_callback');
    }

    /**
     * Build a stable fingerprint for the current Google OAuth configuration.
     *
     * @param array $settings Google email provider settings.
     * @return string
     */
    private static function get_google_oauth_config_fingerprint(array $settings): string {
        $client_id = trim((string) ($settings['google_oauth_client_id'] ?? ''));
        $client_secret = class_exists('Guard_Dog_Email_Provider')
            ? Guard_Dog_Email_Provider::decrypt_sensitive_value((string) ($settings['google_oauth_client_secret'] ?? ''))
            : (string) ($settings['google_oauth_client_secret'] ?? '');
        $auth_mode = sanitize_key((string) ($settings['google_auth_mode'] ?? ''));

        if ($client_id === '' || $client_secret === '') {
            return '';
        }

        return hash('sha256', 'google|' . $auth_mode . '|' . $client_id . '|' . $client_secret);
    }

    /**
     * Start Google OAuth connect flow from settings.
     *
     * @return void
     */
    public static function ajax_google_oauth_start(): void {
        if (!current_user_can('manage_options')) {
            wp_safe_redirect(self::get_email_provider_tab_url(['guard_dog_google_oauth_status' => 'permission_denied']));
            exit;
        }

        $nonce = isset($_GET['_wpnonce']) ? sanitize_text_field(wp_unslash($_GET['_wpnonce'])) : '';
        if (!wp_verify_nonce($nonce, 'guard_dog_google_oauth_start')) {
            wp_safe_redirect(self::get_email_provider_tab_url(['guard_dog_google_oauth_status' => 'invalid_nonce']));
            exit;
        }

        $provider = sanitize_key((string) get_option('guard_dog_email_provider', ''));
        if ($provider !== 'google') {
            wp_safe_redirect(self::get_email_provider_tab_url(['guard_dog_google_oauth_status' => 'provider_mismatch']));
            exit;
        }

        $settings = get_option('guard_dog_email_provider_settings', []);
        if (!is_array($settings)) {
            wp_safe_redirect(self::get_email_provider_tab_url(['guard_dog_google_oauth_status' => 'missing_credentials']));
            exit;
        }

        $mode = sanitize_key((string) ($settings['google_auth_mode'] ?? ''));
        if ($mode === '') {
            $mode = !empty($settings['google_app_password']) ? 'app_password' : 'oauth';
        }
        if ($mode !== 'oauth') {
            wp_safe_redirect(self::get_email_provider_tab_url(['guard_dog_google_oauth_status' => 'oauth_mode_required']));
            exit;
        }

        $client_id = trim((string) ($settings['google_oauth_client_id'] ?? ''));
        $client_secret = class_exists('Guard_Dog_Email_Provider')
            ? Guard_Dog_Email_Provider::decrypt_sensitive_value((string) ($settings['google_oauth_client_secret'] ?? ''))
            : (string) ($settings['google_oauth_client_secret'] ?? '');
        if ($client_id === '' || $client_secret === '') {
            wp_safe_redirect(self::get_email_provider_tab_url(['guard_dog_google_oauth_status' => 'missing_credentials']));
            exit;
        }

        $state = wp_generate_password(48, false, false);
        set_transient('guard_dog_google_oauth_state_' . $state, [
            'user_id' => get_current_user_id(),
            'created_at' => time(),
            'config_hash' => self::get_google_oauth_config_fingerprint($settings),
        ], 10 * MINUTE_IN_SECONDS);

        $params = [
            'client_id' => $client_id,
            'redirect_uri' => self::get_google_oauth_callback_url(),
            'response_type' => 'code',
            'scope' => 'https://www.googleapis.com/auth/gmail.send https://www.googleapis.com/auth/gmail.settings.basic',
            'access_type' => 'offline',
            'include_granted_scopes' => 'true',
            'prompt' => 'consent',
            'state' => $state,
        ];

        $auth_url = 'https://accounts.google.com/o/oauth2/v2/auth?' . http_build_query($params, '', '&', PHP_QUERY_RFC3986);
        wp_redirect($auth_url);
        exit;
    }

    /**
     * Handle Google OAuth callback and persist refresh token.
     *
     * @return void
     */
    public static function ajax_google_oauth_callback(): void {
        $state = isset($_GET['state']) ? sanitize_text_field(wp_unslash($_GET['state'])) : '';
        if ($state === '') {
            wp_safe_redirect(self::get_email_provider_tab_url(['guard_dog_google_oauth_status' => 'invalid_state']));
            exit;
        }

        $state_key = 'guard_dog_google_oauth_state_' . $state;
        $state_data = get_transient($state_key);
        delete_transient($state_key);
        if (!is_array($state_data) || empty($state_data['user_id'])) {
            wp_safe_redirect(self::get_email_provider_tab_url(['guard_dog_google_oauth_status' => 'invalid_state']));
            exit;
        }

        if (!is_user_logged_in() || (int) get_current_user_id() !== (int) $state_data['user_id']) {
            wp_safe_redirect(self::get_email_provider_tab_url(['guard_dog_google_oauth_status' => 'invalid_state']));
            exit;
        }

        if (!current_user_can('manage_options')) {
            wp_safe_redirect(self::get_email_provider_tab_url(['guard_dog_google_oauth_status' => 'permission_denied']));
            exit;
        }

        $error = isset($_GET['error']) ? sanitize_key(wp_unslash($_GET['error'])) : '';
        if ($error !== '') {
            wp_safe_redirect(self::get_email_provider_tab_url([
                'guard_dog_google_oauth_status' => 'oauth_denied',
                'guard_dog_google_oauth_error' => $error,
            ]));
            exit;
        }

        $code = isset($_GET['code']) ? sanitize_text_field(wp_unslash($_GET['code'])) : '';
        if ($code === '') {
            wp_safe_redirect(self::get_email_provider_tab_url(['guard_dog_google_oauth_status' => 'missing_code']));
            exit;
        }

        $settings = get_option('guard_dog_email_provider_settings', []);
        if (!is_array($settings)) {
            wp_safe_redirect(self::get_email_provider_tab_url(['guard_dog_google_oauth_status' => 'missing_credentials']));
            exit;
        }

        $client_id = trim((string) ($settings['google_oauth_client_id'] ?? ''));
        $client_secret = class_exists('Guard_Dog_Email_Provider')
            ? Guard_Dog_Email_Provider::decrypt_sensitive_value((string) ($settings['google_oauth_client_secret'] ?? ''))
            : (string) ($settings['google_oauth_client_secret'] ?? '');
        if ($client_id === '' || $client_secret === '') {
            wp_safe_redirect(self::get_email_provider_tab_url(['guard_dog_google_oauth_status' => 'missing_credentials']));
            exit;
        }

        $expected_config_hash = isset($state_data['config_hash']) ? (string) $state_data['config_hash'] : '';
        if ($expected_config_hash !== '') {
            $current_config_hash = self::get_google_oauth_config_fingerprint($settings);
            if ($current_config_hash === '' || !hash_equals($expected_config_hash, $current_config_hash)) {
                wp_safe_redirect(self::get_email_provider_tab_url(['guard_dog_google_oauth_status' => 'settings_changed']));
                exit;
            }
        }

        $response = wp_remote_post('https://oauth2.googleapis.com/token', [
            'timeout' => 30,
            'body' => [
                'code' => $code,
                'client_id' => $client_id,
                'client_secret' => $client_secret,
                'redirect_uri' => self::get_google_oauth_callback_url(),
                'grant_type' => 'authorization_code',
            ],
        ]);

        if (is_wp_error($response)) {
            wp_safe_redirect(self::get_email_provider_tab_url(['guard_dog_google_oauth_status' => 'token_exchange_failed']));
            exit;
        }

        $status = wp_remote_retrieve_response_code($response);
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        if ($status < 200 || $status >= 300 || !is_array($data)) {
            wp_safe_redirect(self::get_email_provider_tab_url(['guard_dog_google_oauth_status' => 'token_exchange_failed']));
            exit;
        }

        $refresh_token = isset($data['refresh_token']) ? sanitize_text_field((string) $data['refresh_token']) : '';
        if ($refresh_token === '') {
            $existing_refresh_token = class_exists('Guard_Dog_Email_Provider')
                ? Guard_Dog_Email_Provider::decrypt_sensitive_value((string) ($settings['google_oauth_refresh_token'] ?? ''))
                : (string) ($settings['google_oauth_refresh_token'] ?? '');

            if ($existing_refresh_token !== '') {
                $refresh_token = $existing_refresh_token;
            }
        }

        if ($refresh_token === '') {
            wp_safe_redirect(self::get_email_provider_tab_url(['guard_dog_google_oauth_status' => 'no_refresh_token']));
            exit;
        }

        if (class_exists('Guard_Dog_Email_Provider')) {
            $settings['google_oauth_client_secret'] = Guard_Dog_Email_Provider::encrypt_sensitive_value($client_secret);
            $settings['google_oauth_refresh_token'] = Guard_Dog_Email_Provider::encrypt_sensitive_value($refresh_token);
        } else {
            $settings['google_oauth_client_secret'] = $client_secret;
            $settings['google_oauth_refresh_token'] = $refresh_token;
        }
        $settings['google_auth_mode'] = 'oauth';

        update_option('guard_dog_email_provider_settings', $settings);

        $access_token = isset($data['access_token']) ? sanitize_text_field((string) $data['access_token']) : '';
        $expires_in = isset($data['expires_in']) ? max(120, (int) $data['expires_in']) : 3600;
        if ($access_token !== '') {
            $cache_key = 'guard_dog_google_oauth_access_' . md5($client_id . '|' . $refresh_token);
            set_transient($cache_key, [
                'token' => $access_token,
                'expires_at' => time() + $expires_in,
            ], max(60, $expires_in - 30));
        }

        wp_safe_redirect(self::get_email_provider_tab_url(['guard_dog_google_oauth_status' => 'connected']));
        exit;
    }

    /**
     * Disconnect Google OAuth for email provider.
     *
     * @return void
     */
    public static function ajax_google_oauth_disconnect(): void {
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'guard-dog')], 403);
        }

        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        if (!wp_verify_nonce($nonce, 'guard_dog_google_oauth_disconnect')) {
            wp_send_json_error(['message' => __('Security verification failed.', 'guard-dog')], 403);
        }

        $settings = get_option('guard_dog_email_provider_settings', []);
        if (!is_array($settings)) {
            $settings = [];
        }

        $client_id = trim((string) ($settings['google_oauth_client_id'] ?? ''));
        $existing_refresh_token = class_exists('Guard_Dog_Email_Provider')
            ? Guard_Dog_Email_Provider::decrypt_sensitive_value((string) ($settings['google_oauth_refresh_token'] ?? ''))
            : (string) ($settings['google_oauth_refresh_token'] ?? '');
        if ($client_id !== '' && $existing_refresh_token !== '') {
            $cache_key = 'guard_dog_google_oauth_access_' . md5($client_id . '|' . $existing_refresh_token);
            delete_transient($cache_key);
        }

        unset($settings['google_oauth_refresh_token']);
        update_option('guard_dog_email_provider_settings', $settings);

        wp_send_json_success([
            'message' => __('Google OAuth disconnected successfully.', 'guard-dog'),
        ]);
    }

    /**
     * Check whether configured From email exists in Gmail sendAs aliases.
     *
     * @return void
     */
    public static function ajax_google_alias_preflight(): void {
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'guard-dog')], 403);
        }

        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        if (!wp_verify_nonce($nonce, 'guard_dog_google_alias_preflight')) {
            wp_send_json_error(['message' => __('Security verification failed.', 'guard-dog')], 403);
        }

        $provider = sanitize_key((string) get_option('guard_dog_email_provider', ''));
        if ($provider !== 'google') {
            wp_send_json_error(['message' => __('Google provider is not selected.', 'guard-dog')], 400);
        }

        $from_email = sanitize_email(wp_unslash($_POST['from_email'] ?? ''));
        $email_provider = null;
        if (function_exists('Guard_Dog') && isset(Guard_Dog()->features['email_provider'])) {
            $email_provider = Guard_Dog()->features['email_provider'];
        } elseif (class_exists('Guard_Dog_Email_Provider')) {
            $email_provider = new Guard_Dog_Email_Provider();
        }

        if (!$email_provider || !method_exists($email_provider, 'get_google_send_as_aliases')) {
            wp_send_json_error(['message' => __('Email provider is not available.', 'guard-dog')], 500);
        }

        $aliases_result = $email_provider->get_google_send_as_aliases();
        if (empty($aliases_result['success'])) {
            wp_send_json_error(['message' => $aliases_result['message'] ?? __('Google alias preflight failed.', 'guard-dog')], 400);
        }

        $aliases = isset($aliases_result['aliases']) && is_array($aliases_result['aliases']) ? $aliases_result['aliases'] : [];
        $matched_alias = null;
        if (!empty($from_email)) {
            $target = strtolower($from_email);
            foreach ($aliases as $alias) {
                if (strtolower((string) ($alias['email'] ?? '')) === $target) {
                    $matched_alias = $alias;
                    break;
                }
            }
        }

        if ($matched_alias) {
            $status = $matched_alias['verification_status'] ?? 'unknown';
            $is_verified = in_array($status, ['accepted', 'verified'], true);
            wp_send_json_success([
                'message' => $is_verified
                    ? __('From email alias is available and verified in Gmail send-as settings.', 'guard-dog')
                    : __('From email alias exists but is not verified yet in Gmail send-as settings.', 'guard-dog'),
                'match' => $matched_alias,
                'alias_count' => count($aliases),
                'aliases' => $aliases,
            ]);
        }

        wp_send_json_success([
            'message' => __('From email alias was not found in Gmail send-as settings.', 'guard-dog'),
            'match' => null,
            'alias_count' => count($aliases),
            'aliases' => $aliases,
        ]);
    }

    /**
     * Fetch Gmail send-as aliases for alias picker dropdown.
     *
     * @return void
     */
    public static function ajax_google_aliases_list(): void {
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('Permission denied.', 'guard-dog')], 403);
        }

        $nonce = isset($_POST['nonce']) ? sanitize_text_field(wp_unslash($_POST['nonce'])) : '';
        if (!wp_verify_nonce($nonce, 'guard_dog_google_aliases_list')) {
            wp_send_json_error(['message' => __('Security verification failed.', 'guard-dog')], 403);
        }

        $provider = sanitize_key((string) get_option('guard_dog_email_provider', ''));
        if ($provider !== 'google') {
            wp_send_json_error(['message' => __('Google provider is not selected.', 'guard-dog')], 400);
        }

        $email_provider = null;
        if (function_exists('Guard_Dog') && isset(Guard_Dog()->features['email_provider'])) {
            $email_provider = Guard_Dog()->features['email_provider'];
        } elseif (class_exists('Guard_Dog_Email_Provider')) {
            $email_provider = new Guard_Dog_Email_Provider();
        }

        if (!$email_provider || !method_exists($email_provider, 'get_google_send_as_aliases')) {
            wp_send_json_error(['message' => __('Email provider is not available.', 'guard-dog')], 500);
        }

        $aliases_result = $email_provider->get_google_send_as_aliases();
        if (empty($aliases_result['success'])) {
            wp_send_json_error([
                'message' => $aliases_result['message'] ?? __('Failed to load Gmail aliases.', 'guard-dog'),
            ], 400);
        }

        $aliases = isset($aliases_result['aliases']) && is_array($aliases_result['aliases'])
            ? $aliases_result['aliases']
            : [];
        $aliases = array_values(array_filter($aliases, static function ($alias) {
            $status = sanitize_key((string) ($alias['verification_status'] ?? ''));

            return in_array($status, ['accepted', 'verified'], true);
        }));

        $settings = get_option('guard_dog_email_provider_settings', []);
        if (!is_array($settings)) {
            $settings = [];
        }

        $current_from_email = sanitize_email((string) ($settings['google_from_email'] ?? ''));
        $current_from_name = sanitize_text_field((string) ($settings['google_from_name'] ?? ''));

        wp_send_json_success([
            'message' => __('Gmail aliases loaded successfully.', 'guard-dog'),
            'aliases' => $aliases,
            'alias_count' => count($aliases),
            'current_from_email' => $current_from_email,
            'current_from_name' => $current_from_name,
        ]);
    }

    public static function render_email_provider_field(): void {
        $current_provider = get_option('guard_dog_email_provider', '');
        $email_provider = null;
        $available_providers = [];
        
        if (function_exists('Guard_Dog') && isset(Guard_Dog()->features['email_provider'])) {
            $email_provider = Guard_Dog()->features['email_provider'];
            $available_providers = $email_provider->get_available_providers();
        } elseif (class_exists('Guard_Dog_Email_Provider')) {
            $email_provider = new Guard_Dog_Email_Provider();
            $available_providers = $email_provider->get_available_providers();
        }
        
        ?>
        <select name="guard_dog_email_provider" id="guard_dog_email_provider">
            <option value=""><?php esc_html_e('Select Email Provider', 'guard-dog'); ?></option>
            
            <?php if (!empty($available_providers)): ?>
                <?php foreach ($available_providers as $provider_key => $provider_config): ?>
                    <option value="<?php echo esc_attr($provider_key); ?>"<?php echo esc_attr(selected($current_provider, $provider_key, false)); ?>>
                        <?php echo esc_html($provider_config['name']); ?>
                    </option>
                <?php endforeach; ?>
            <?php endif; ?>
        </select>
        <p class="description"><?php esc_html_e('Select your email service provider for sending 2FA codes.', 'guard-dog'); ?></p>
        
        <?php
        // Show provider configuration UI for immediate provider switching.
        if (!empty($available_providers) && $email_provider):
            $active_provider = (!empty($current_provider) && isset($available_providers[$current_provider]))
                ? $current_provider
                : '';

            $provider_settings = method_exists($email_provider, 'get_provider_settings')
                ? $email_provider->get_provider_settings()
                : [];
            if (!is_array($provider_settings)) {
                $provider_settings = [];
            }

            $google_auth_mode = sanitize_key((string) ($provider_settings['google_auth_mode'] ?? ''));
            if ($google_auth_mode === '' && !empty($provider_settings['google_app_password'])) {
                $google_auth_mode = 'app_password';
            }

            $google_refresh_token = class_exists('Guard_Dog_Email_Provider')
                ? Guard_Dog_Email_Provider::decrypt_sensitive_value((string) ($provider_settings['google_oauth_refresh_token'] ?? ''))
                : (string) ($provider_settings['google_oauth_refresh_token'] ?? '');
            $google_oauth_connected = $google_refresh_token !== '';
            $current_google_from_email = sanitize_email((string) ($provider_settings['google_from_email'] ?? ''));
            $current_google_from_name = sanitize_text_field((string) ($provider_settings['google_from_name'] ?? ''));
            $current_google_alias_label = $current_google_from_email;
            if ($current_google_alias_label !== '' && $current_google_from_name !== '') {
                $current_google_alias_label .= ' - ' . $current_google_from_name;
            }

            $google_oauth_status = isset($_GET['guard_dog_google_oauth_status'])
                ? sanitize_key(wp_unslash($_GET['guard_dog_google_oauth_status']))
                : '';

            $google_oauth_status_map = [
                'connected' => ['type' => 'success', 'message' => __('Google OAuth connected successfully.', 'guard-dog')],
                'oauth_denied' => ['type' => 'warning', 'message' => __('Google OAuth authorization was canceled.', 'guard-dog')],
                'missing_code' => ['type' => 'error', 'message' => __('Google OAuth callback did not include an authorization code.', 'guard-dog')],
                'invalid_state' => ['type' => 'error', 'message' => __('Google OAuth state validation failed. Please try connecting again.', 'guard-dog')],
                'missing_credentials' => ['type' => 'error', 'message' => __('Google OAuth Client ID and Client Secret are required before connecting.', 'guard-dog')],
                'oauth_mode_required' => ['type' => 'warning', 'message' => __('Switch Google authentication mode to OAuth before connecting.', 'guard-dog')],
                'provider_mismatch' => ['type' => 'warning', 'message' => __('Google provider must be selected before connecting OAuth.', 'guard-dog')],
                'settings_changed' => ['type' => 'error', 'message' => __('Google OAuth settings changed before the callback completed. Please reconnect and try again.', 'guard-dog')],
                'token_exchange_failed' => ['type' => 'error', 'message' => __('Google OAuth token exchange failed. Please verify your Google Cloud credentials and redirect URI.', 'guard-dog')],
                'no_refresh_token' => ['type' => 'error', 'message' => __('Google did not return a refresh token. Reconnect with OAuth consent and offline access enabled.', 'guard-dog')],
                'invalid_nonce' => ['type' => 'error', 'message' => __('Security check failed while starting Google OAuth.', 'guard-dog')],
                'permission_denied' => ['type' => 'error', 'message' => __('You do not have permission to manage Google OAuth settings.', 'guard-dog')],
            ];
            ?>
            <div id="email-provider-config"
                 class="guard-dog-email-provider-config"
                 <?php echo $active_provider === '' ? 'style="display:none;"' : ''; ?>>
                <?php
                $active_provider_name = $active_provider !== ''
                    ? $available_providers[$active_provider]['name']
                    : __('Email Provider', 'guard-dog');
                ?>
                <h4 id="guard-dog-provider-config-heading"><?php echo esc_html($active_provider_name . ' ' . __('Configuration', 'guard-dog')); ?></h4>
                <?php if ($active_provider === 'google' && $google_oauth_status !== '' && isset($google_oauth_status_map[$google_oauth_status])): ?>
                    <?php $status_notice = $google_oauth_status_map[$google_oauth_status]; ?>
                    <div class="notice notice-<?php echo esc_attr($status_notice['type']); ?> inline guard-dog-provider-context"
                         data-provider="google">
                        <p><?php echo esc_html($status_notice['message']); ?></p>
                    </div>
                <?php endif; ?>
                <table class="form-table">
                    <?php
                    // Email provider form rendering - output is trusted HTML from internal class
                    // Use wp_kses with form-specific allowed tags since this is trusted internal output
                    $allowed_form_tags = [
                        'tr' => [
                            'class' => [],
                            'style' => [],
                            'data-provider' => [],
                        ],
                        'th' => ['scope' => []],
                        'td' => [],
                        'label' => ['for' => []],
                        'span' => ['class' => []],
                        'input' => [
                            'type' => [],
                            'id' => [],
                            'name' => [],
                            'value' => [],
                            'class' => [],
                            'required' => []
                        ],
                        'select' => [
                            'id' => [],
                            'name' => [],
                            'required' => []
                        ],
                        'option' => [
                            'value' => [],
                            'selected' => []
                        ],
                        'p' => ['class' => []]
                    ];
                    foreach ($available_providers as $provider_key => $provider_config) {
                        $is_provider_active = ($provider_key === $active_provider);
                        $row_class = 'guard-dog-provider-row guard-dog-provider-row-' . sanitize_html_class($provider_key);
                        $row_style = $is_provider_active ? '' : 'display:none;';
                        echo wp_kses($email_provider->render_provider_form($provider_key, $row_class, $row_style), $allowed_form_tags);
                    }
                    ?>

                    <?php if (isset($available_providers['google'])): ?>
                        <tr class="guard-dog-google-oauth-controls guard-dog-provider-row guard-dog-provider-row-google"
                            data-provider="google"
                            <?php echo $active_provider === 'google' ? '' : 'style="display:none;"'; ?>>
                            <th scope="row"><?php esc_html_e('Google OAuth Connection', 'guard-dog'); ?></th>
                            <td>
                                <?php
                                $oauth_connect_url = wp_nonce_url(
                                    admin_url('admin-ajax.php?action=guard_dog_google_oauth_start'),
                                    'guard_dog_google_oauth_start'
                                );
                                ?>
                                <a href="<?php echo esc_url($oauth_connect_url); ?>"
                                   id="guard-dog-google-oauth-connect"
                                   class="button button-secondary">
                                    <?php esc_html_e('Connect Google Account', 'guard-dog'); ?>
                                </a>
                                <button type="button"
                                        id="guard-dog-google-oauth-disconnect"
                                        class="button button-secondary"
                                        data-nonce="<?php echo esc_attr(wp_create_nonce('guard_dog_google_oauth_disconnect')); ?>">
                                    <?php esc_html_e('Disconnect OAuth', 'guard-dog'); ?>
                                </button>
                                <p class="description">
                                    <?php esc_html_e('Status:', 'guard-dog'); ?>
                                    <strong>
                                        <?php echo esc_html($google_oauth_connected ? __('Connected', 'guard-dog') : __('Not Connected', 'guard-dog')); ?>
                                    </strong>
                                </p>
                                <p class="description">
                                    <?php esc_html_e('Connect saves your current Google settings first, then starts the OAuth handshake.', 'guard-dog'); ?>
                                </p>
                                <p class="description">
                                    <?php esc_html_e('Add this callback URL to your Google OAuth Client redirect URIs:', 'guard-dog'); ?>
                                    <code><?php echo esc_html(self::get_google_oauth_callback_url()); ?></code>
                                </p>
                                <div class="guard-dog-google-help">
                                    <button type="button"
                                            class="button button-secondary button-small guard-dog-google-help-toggle"
                                            aria-expanded="true"
                                            aria-controls="guard-dog-google-oauth-help-panel"
                                            data-show-label="<?php echo esc_attr__('Show Google OAuth setup help', 'guard-dog'); ?>"
                                            data-hide-label="<?php echo esc_attr__('Hide Google OAuth setup help', 'guard-dog'); ?>">
                                        <?php esc_html_e('Hide Google OAuth setup help', 'guard-dog'); ?>
                                    </button>
                                    <div id="guard-dog-google-oauth-help-panel" class="guard-dog-google-help-panel notice notice-info inline">
                                        <p><strong><?php esc_html_e('What are the Client ID and Client Secret?', 'guard-dog'); ?></strong></p>
                                        <p><?php esc_html_e('These are credentials Google gives your site so it can ask permission to send email from your Google account. They are not your Google password.', 'guard-dog'); ?></p>
                                        <ol style="margin-left: 1.5em;">
                                            <li><?php esc_html_e('In Google Cloud Console, create or choose a project and enable the Gmail API.', 'guard-dog'); ?></li>
                                            <li><?php esc_html_e('Create an OAuth 2.0 Client ID for a Web application.', 'guard-dog'); ?></li>
                                            <li><?php esc_html_e('Paste the Client ID and Client Secret into the fields above.', 'guard-dog'); ?></li>
                                            <li><?php esc_html_e('Add the callback URL shown here to the Authorized redirect URIs list in Google Cloud Console.', 'guard-dog'); ?></li>
                                            <li><?php esc_html_e('Save your settings, then click Connect Google Account and sign in to the mailbox that should send email.', 'guard-dog'); ?></li>
                                        </ol>
                                        <p><?php esc_html_e('Guard Dog fills in the refresh token automatically after you connect. You usually do not need to paste one manually.', 'guard-dog'); ?></p>
                                    </div>
                                </div>
                                <button type="button"
                                        id="guard-dog-google-alias-preflight"
                                        class="button button-secondary"
                                        data-nonce="<?php echo esc_attr(wp_create_nonce('guard_dog_google_alias_preflight')); ?>">
                                    <?php esc_html_e('Validate From Alias', 'guard-dog'); ?>
                                </button>
                                <p class="description"><?php esc_html_e('Checks whether the configured From email exists in Gmail send-as aliases for the connected account.', 'guard-dog'); ?></p>
                                <div class="guard-dog-google-alias-picker">
                                    <p>
                                        <button type="button"
                                                id="guard-dog-google-aliases-load"
                                                class="button button-secondary"
                                                data-nonce="<?php echo esc_attr(wp_create_nonce('guard_dog_google_aliases_list')); ?>">
                                            <?php esc_html_e('Load Gmail Aliases', 'guard-dog'); ?>
                                        </button>
                                    </p>
                                    <p>
                                        <select id="guard-dog-google-alias-select"
                                                class="regular-text"
                                                data-current-email="<?php echo esc_attr($current_google_from_email); ?>"
                                                data-current-name="<?php echo esc_attr($current_google_from_name); ?>">
                                            <?php if ($current_google_from_email !== ''): ?>
                                                <option value="<?php echo esc_attr($current_google_from_email); ?>" selected>
                                                    <?php
                                                    /* translators: %s is the saved Gmail alias label. */
                                                    echo esc_html(sprintf(__('Saved alias: %s', 'guard-dog'), $current_google_alias_label));
                                                    ?>
                                                </option>
                                            <?php else: ?>
                                                <option value=""><?php esc_html_e('Select a Gmail alias', 'guard-dog'); ?></option>
                                            <?php endif; ?>
                                        </select>
                                        <button type="button"
                                                id="guard-dog-google-alias-apply"
                                                class="button button-secondary"
                                                disabled>
                                            <?php esc_html_e('Use Selected Alias', 'guard-dog'); ?>
                                        </button>
                                    </p>
                                    <p class="description"><?php esc_html_e('Loads aliases from Gmail Send mail as and applies the selected alias to From Email (and From Name when available). The saved alias shown here reflects your current From Email setting after you save.', 'guard-dog'); ?></p>
                                </div>
                                <div id="guard-dog-google-oauth-result"></div>
                                <div id="guard-dog-google-alias-preflight-result"></div>
                                <div id="guard-dog-google-aliases-result"></div>
                            </td>
                        </tr>
                    <?php endif; ?>
                    
                    <!-- Global Email Override Setting -->
                    <tr>
                        <th scope="row">
                            <label for="guard_dog_email_provider_global_override">
                                <?php esc_html_e('Use for All WordPress Emails', 'guard-dog'); ?>
                            </label>
                        </th>
                        <td>
                            <?php
                            $global_override = get_option('guard_dog_email_provider_global_override', false);
                            ?>
                            <input type="checkbox" 
                                   id="guard_dog_email_provider_global_override" 
                                   name="guard_dog_email_provider_global_override" 
                                   value="1" 
                                   <?php checked($global_override); ?> />
                            <label for="guard_dog_email_provider_global_override">
                                <?php esc_html_e('Use Guard Dog Email Provider for all WordPress emails', 'guard-dog'); ?>
                            </label>
                            <p class="description">
                                <?php esc_html_e('This will replace WordPress\'s default email sending with your configured Guard Dog email provider. Ensure your provider is properly configured and tested.', 'guard-dog'); ?>
                            </p>
                            <?php if ($global_override): ?>
                                <p class="description" style="color: green;">
                                    <strong><?php esc_html_e('Status:', 'guard-dog'); ?></strong> <?php esc_html_e('Global override: Enabled', 'guard-dog'); ?>
                                </p>
                            <?php else: ?>
                                <p class="description">
                                    <strong><?php esc_html_e('Status:', 'guard-dog'); ?></strong> <?php esc_html_e('Global override: Disabled', 'guard-dog'); ?>
                                </p>
                            <?php endif; ?>
                        </td>
                    </tr>
                </table>
                
                <!-- Add test configuration section -->
                <div id="email-provider-test" class="guard-dog-email-provider-test">
                    <h5><?php esc_html_e('Test Configuration', 'guard-dog'); ?></h5>
                    <p><?php esc_html_e('Send a test email to verify your configuration is working correctly.', 'guard-dog'); ?></p>
                    <table class="form-table">
                        <tr>
                            <th scope="row"><label for="test_email"><?php esc_html_e('Test Email Address', 'guard-dog'); ?></label></th>
                            <td>
                                <input type="email" id="test_email" name="test_email" value="<?php echo esc_attr(get_option('admin_email')); ?>" class="regular-text" />
                                <p class="description"><?php esc_html_e('Enter an email address to send a test email to.', 'guard-dog'); ?></p>
                            </td>
                        </tr>
                    </table>
                    <button type="button" id="test-email-provider" class="button button-secondary"><?php esc_html_e('Send Test Email', 'guard-dog'); ?></button>
                    <div id="test-email-result"></div>
                </div>
            </div>
            <?php
        endif;
    }

    public function view_debug_log(): void {
        try {
            $wordpress_debug_log = WP_CONTENT_DIR . '/debug.log';
            $this->current_tab = 'debug';

            if (!file_exists($wordpress_debug_log)) {
                $this->add_admin_notice(
                    __('WordPress debug log not found. Debug logging may not be enabled.', 'guard-dog'),
                    'warning'
                );
                return;
            }

            $this->debug_log_viewer_data = $this->build_debug_log_viewer_data($wordpress_debug_log);
            
        } catch (Exception $e) {
            Guard_Dog()->debug->error('Failed to view debug log', 'settings', [
                'error' => $e->getMessage(),
                'user_id' => get_current_user_id(),
            ]);
            
            $this->add_admin_notice(
                __('Failed to load the debug log viewer. Please try again.', 'guard-dog'),
                'error'
            );
        }
    }

    /**
     * Render the parsed debug log viewer when requested from the Tools sidebar.
     */
    private function render_debug_log_viewer(): void {
        if (!is_array($this->debug_log_viewer_data)) {
            return;
        }

        $viewer = $this->debug_log_viewer_data;
        ?>
        <div class="guard-dog-debug-log-viewer">
            <div class="guard-dog-debug-log-viewer__header">
                <div>
                    <h4><?php esc_html_e('Debug Log Viewer', 'guard-dog'); ?></h4>
                    <p>
                        <?php
                        printf(
                            /* translators: 1: number of entries shown, 2: total parsed entries */
                            esc_html__('Showing %1$d most recent parsed entries out of %2$d found in the loaded log segment.', 'guard-dog'),
                            (int) ($viewer['displayed_entry_count'] ?? 0),
                            (int) ($viewer['parsed_entry_count'] ?? 0)
                        );
                        ?>
                    </p>
                </div>
                <div class="guard-dog-debug-log-viewer__meta">
                    <span><strong><?php esc_html_e('File:', 'guard-dog'); ?></strong> <code><?php echo esc_html((string) ($viewer['path'] ?? '')); ?></code></span>
                    <span><strong><?php esc_html_e('Size:', 'guard-dog'); ?></strong> <?php echo esc_html(size_format((int) ($viewer['size_bytes'] ?? 0))); ?></span>
                    <span><strong><?php esc_html_e('Updated:', 'guard-dog'); ?></strong> <?php echo esc_html((string) ($viewer['modified_at'] ?? __('Unknown', 'guard-dog'))); ?></span>
                </div>
            </div>

            <?php if (!empty($viewer['truncated'])): ?>
                <div class="notice notice-warning inline">
                    <p><?php esc_html_e('This viewer loads the tail end of a large debug.log file so the page stays usable. Older entries may be omitted.', 'guard-dog'); ?></p>
                </div>
            <?php endif; ?>

            <div class="guard-dog-debug-log-summary">
                <div class="guard-dog-debug-log-summary__item">
                    <span class="guard-dog-debug-log-summary__label"><?php esc_html_e('Guard Dog Entries', 'guard-dog'); ?></span>
                    <strong><?php echo esc_html((string) ($viewer['summary']['guard_dog_entries'] ?? 0)); ?></strong>
                </div>
                <div class="guard-dog-debug-log-summary__item">
                    <span class="guard-dog-debug-log-summary__label"><?php esc_html_e('WordPress / PHP Entries', 'guard-dog'); ?></span>
                    <strong><?php echo esc_html((string) ($viewer['summary']['wordpress_entries'] ?? 0)); ?></strong>
                </div>
                <div class="guard-dog-debug-log-summary__item">
                    <span class="guard-dog-debug-log-summary__label"><?php esc_html_e('Errors', 'guard-dog'); ?></span>
                    <strong><?php echo esc_html((string) ($viewer['summary']['levels']['error'] ?? 0)); ?></strong>
                </div>
                <div class="guard-dog-debug-log-summary__item">
                    <span class="guard-dog-debug-log-summary__label"><?php esc_html_e('Warnings', 'guard-dog'); ?></span>
                    <strong><?php echo esc_html((string) ($viewer['summary']['levels']['warning'] ?? 0)); ?></strong>
                </div>
            </div>

            <?php if (empty($viewer['entries'])): ?>
                <div class="guard-dog-debug-log-empty">
                    <p><?php esc_html_e('The debug log file exists, but there were no readable entries in the loaded segment.', 'guard-dog'); ?></p>
                </div>
            <?php else: ?>
                <div class="guard-dog-debug-log-entries">
                    <?php foreach ($viewer['entries'] as $entry): ?>
                        <?php
                        $level = sanitize_html_class((string) ($entry['level'] ?? 'info'));
                        $source = sanitize_html_class((string) ($entry['source'] ?? 'raw'));
                        ?>
                        <article class="guard-dog-debug-log-entry guard-dog-debug-log-entry--<?php echo esc_attr($level); ?> guard-dog-debug-log-entry--<?php echo esc_attr($source); ?>">
                            <div class="guard-dog-debug-log-entry__header">
                                <div class="guard-dog-debug-log-entry__badges">
                                    <span class="guard-dog-debug-log-badge guard-dog-debug-log-badge--<?php echo esc_attr($level); ?>">
                                        <?php echo esc_html(strtoupper((string) ($entry['level_label'] ?? strtoupper($level)))); ?>
                                    </span>
                                    <span class="guard-dog-debug-log-badge guard-dog-debug-log-badge--source">
                                        <?php echo esc_html((string) ($entry['source_label'] ?? __('Raw', 'guard-dog'))); ?>
                                    </span>
                                    <?php if (!empty($entry['component'])): ?>
                                        <span class="guard-dog-debug-log-entry__component"><?php echo esc_html((string) $entry['component']); ?></span>
                                    <?php endif; ?>
                                </div>
                                <?php if (!empty($entry['timestamp'])): ?>
                                    <time class="guard-dog-debug-log-entry__timestamp"><?php echo esc_html((string) $entry['timestamp']); ?></time>
                                <?php endif; ?>
                            </div>

                            <?php if (!empty($entry['message'])): ?>
                                <pre class="guard-dog-debug-log-entry__message"><?php echo esc_html((string) $entry['message']); ?></pre>
                            <?php endif; ?>

                            <?php if (!empty($entry['context'])): ?>
                                <div class="guard-dog-debug-log-entry__context-label"><?php esc_html_e('Context', 'guard-dog'); ?></div>
                                <pre class="guard-dog-debug-log-entry__context"><?php echo esc_html((string) $entry['context']); ?></pre>
                            <?php endif; ?>
                        </article>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
        <?php
    }

    /**
     * Build parsed data for the in-page debug log viewer.
     *
     * @param string $log_path Absolute debug.log path.
     * @return array
     */
    private function build_debug_log_viewer_data(string $log_path): array {
        $size_bytes = (int) filesize($log_path);
        $modified_timestamp = filemtime($log_path);
        $excerpt = $this->read_debug_log_excerpt($log_path, self::DEBUG_LOG_VIEWER_MAX_BYTES);
        $parsed_entries = $this->parse_debug_log_entries($excerpt['content']);
        $displayed_entries = array_slice($parsed_entries, -self::DEBUG_LOG_VIEWER_MAX_ENTRIES);
        $displayed_entries = array_reverse($displayed_entries);

        $summary = [
            'guard_dog_entries' => 0,
            'wordpress_entries' => 0,
            'levels' => [
                'error' => 0,
                'warning' => 0,
                'info' => 0,
                'debug' => 0,
            ],
        ];

        foreach ($displayed_entries as $entry) {
            if (($entry['source'] ?? '') === 'guard_dog') {
                $summary['guard_dog_entries']++;
            } else {
                $summary['wordpress_entries']++;
            }

            $level = (string) ($entry['level'] ?? 'info');
            if (!isset($summary['levels'][$level])) {
                $summary['levels'][$level] = 0;
            }
            $summary['levels'][$level]++;
        }

        return [
            'path' => $log_path,
            'size_bytes' => $size_bytes,
            'modified_at' => $modified_timestamp ? wp_date('Y-m-d H:i:s', $modified_timestamp) : __('Unknown', 'guard-dog'),
            'truncated' => !empty($excerpt['truncated']),
            'parsed_entry_count' => count($parsed_entries),
            'displayed_entry_count' => count($displayed_entries),
            'entries' => $displayed_entries,
            'summary' => $summary,
        ];
    }

    /**
     * Read an excerpt from the tail end of debug.log.
     *
     * @param string $log_path Absolute path to debug.log.
     * @param int $max_bytes Maximum bytes to load.
     * @return array{content:string,truncated:bool}
     */
    private function read_debug_log_excerpt(string $log_path, int $max_bytes): array {
        $size_bytes = (int) filesize($log_path);

        if ($size_bytes <= $max_bytes) {
            $content = file_get_contents($log_path);
            if ($content === false) {
                throw new Exception('Failed to read debug log file');
            }

            return [
                'content' => (string) $content,
                'truncated' => false,
            ];
        }

        $offset = max(0, $size_bytes - $max_bytes);
        $content = file_get_contents($log_path, false, null, $offset);
        if ($content === false) {
            throw new Exception('Failed to read debug log excerpt');
        }

        $content = (string) $content;
        $first_newline = strpos($content, "\n");
        if ($first_newline !== false) {
            $content = substr($content, $first_newline + 1);
        }

        return [
            'content' => $content,
            'truncated' => true,
        ];
    }

    /**
     * Parse raw debug.log text into grouped entries.
     *
     * @param string $content Raw log text.
     * @return array
     */
    private function parse_debug_log_entries(string $content): array {
        if ($content === '') {
            return [];
        }

        $lines = preg_split('/\r\n|\n|\r/', $content);
        if (!is_array($lines)) {
            return [];
        }

        $entries = [];
        $current_entry = '';

        foreach ($lines as $line) {
            $line = (string) $line;
            if ($line === '' && $current_entry === '') {
                continue;
            }

            if ($this->is_debug_log_entry_start($line)) {
                if ($current_entry !== '') {
                    $entries[] = $this->normalize_debug_log_entry($current_entry);
                }

                $current_entry = $line;
                continue;
            }

            if ($current_entry === '') {
                $current_entry = $line;
                continue;
            }

            $current_entry .= "\n" . $line;
        }

        if ($current_entry !== '') {
            $entries[] = $this->normalize_debug_log_entry($current_entry);
        }

        return array_values(array_filter($entries, static function ($entry) {
            return is_array($entry) && !empty($entry['message']);
        }));
    }

    /**
     * Determine whether a line starts a new debug log entry.
     *
     * @param string $line Raw line.
     * @return bool
     */
    private function is_debug_log_entry_start(string $line): bool {
        if (preg_match('/^\[Guard Dog\] \[\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\] \[[A-Z]+\] \[[^\]]+\]/', $line) === 1) {
            return true;
        }

        return preg_match('/^\[\d{2}-[A-Za-z]{3}-\d{4} \d{2}:\d{2}:\d{2}(?: [^\]]+)?\]/', $line) === 1;
    }

    /**
     * Normalize a parsed debug log entry into structured metadata.
     *
     * @param string $raw_entry Raw grouped log entry.
     * @return array
     */
    private function normalize_debug_log_entry(string $raw_entry): array {
        $raw_entry = trim($raw_entry);
        $message = $raw_entry;
        $context = '';
        $timestamp = '';
        $level = 'info';
        $level_label = 'INFO';
        $component = '';
        $source = 'raw';
        $source_label = __('Raw', 'guard-dog');

        if (preg_match('/^\[Guard Dog\] \[(?<timestamp>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2})\] \[(?<level>[A-Z]+)\] \[(?<component>[^\]]+)\] (?<message>[\s\S]*)$/', $raw_entry, $matches) === 1) {
            $timestamp = (string) ($matches['timestamp'] ?? '');
            $component = sanitize_text_field((string) ($matches['component'] ?? ''));
            $source = 'guard_dog';
            $source_label = __('Guard Dog', 'guard-dog');
            $level_label = strtoupper((string) ($matches['level'] ?? 'INFO'));
            $level = strtolower($level_label);
            $message = (string) ($matches['message'] ?? '');

            $context_marker = strpos($message, ' Context: ');
            if ($context_marker !== false) {
                $context = trim(substr($message, $context_marker + 10));
                $message = trim(substr($message, 0, $context_marker));
            }
        } elseif (preg_match('/^\[(?<timestamp>\d{2}-[A-Za-z]{3}-\d{4} \d{2}:\d{2}:\d{2}(?: [^\]]+)?)\] (?<message>[\s\S]*)$/', $raw_entry, $matches) === 1) {
            $timestamp = (string) ($matches['timestamp'] ?? '');
            $message = (string) ($matches['message'] ?? '');
            $source = 'wordpress';
            $source_label = __('WordPress / PHP', 'guard-dog');
            $level = $this->infer_generic_debug_log_level($message);
            $level_label = strtoupper($level);
        }

        return [
            'timestamp' => $timestamp,
            'level' => $level,
            'level_label' => $level_label,
            'component' => $component,
            'source' => $source,
            'source_label' => $source_label,
            'message' => trim($message),
            'context' => trim($context),
            'raw' => $raw_entry,
        ];
    }

    /**
     * Infer a reasonable level label for non-Guard-Dog log entries.
     *
     * @param string $message Log message body.
     * @return string
     */
    private function infer_generic_debug_log_level(string $message): string {
        $message = strtolower($message);

        if (strpos($message, 'fatal error') !== false || strpos($message, 'uncaught') !== false || strpos($message, 'php error') !== false) {
            return 'error';
        }

        if (strpos($message, 'warning') !== false) {
            return 'warning';
        }

        if (strpos($message, 'notice') !== false || strpos($message, 'deprecated') !== false || strpos($message, 'strict standards') !== false) {
            return 'info';
        }

        return 'debug';
    }

    public function run_health_check(): void {
        try {
            $health_report = [];
            
            // Check database tables
            global $wpdb;
            $activity_log_table = $wpdb->prefix . 'guard_dog_logs';
            // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
            // SHOW TABLES and COUNT(*) queries require table name interpolation - safe as constructed from wpdb->prefix
            // Direct database queries are necessary for health check functionality
            // Table names are validated and escaped for additional security
            $escaped_table_name = esc_sql($activity_log_table);
            $health_report['database'] = [
                'activity_log_table_exists' => $wpdb->get_var($wpdb->prepare("SHOW TABLES LIKE %s", $activity_log_table)) === $activity_log_table,
                'activity_log_table_count' => $wpdb->get_var("SELECT COUNT(*) FROM `{$escaped_table_name}`") ?? 0,
            ];
            // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
            
            // Check file permissions
            $upload_dir = wp_upload_dir();
            $wordpress_debug_log = WP_CONTENT_DIR . '/debug.log';
            $health_report['files'] = [
                'wordpress_debug_log_exists' => file_exists($wordpress_debug_log),
                'wordpress_debug_log_readable' => file_exists($wordpress_debug_log) ? is_readable($wordpress_debug_log) : false,
                'upload_dir_writable' => wp_is_writable($upload_dir['basedir']),
            ];
            
            // Check WordPress configuration
            $health_report['wordpress'] = [
                'wp_debug' => defined('WP_DEBUG') && WP_DEBUG,
                'wp_debug_log' => defined('WP_DEBUG_LOG') && WP_DEBUG_LOG,
                'wp_debug_display' => defined('WP_DEBUG_DISPLAY') && WP_DEBUG_DISPLAY,
            ];
            
            // Check Guard Dog configuration
            $health_report['guard_dog'] = [
                'debug_enabled' => get_option('guard_dog_debug_enabled', false),
                'debug_level' => get_option('guard_dog_debug_level', 'error'),
                'captcha_provider' => get_option('guard_dog_captcha_provider', 'none'),
                'login_attempts_enabled' => get_option('guard_dog_login_attempts_enabled', false),
                'two_factor_enabled' => get_option('guard_dog_two_factor_enabled', false),
            ];
            
            // Check PHP configuration
            $health_report['php'] = [
                'version' => PHP_VERSION,
                'memory_limit' => ini_get('memory_limit'),
                'max_execution_time' => ini_get('max_execution_time'),
                'upload_max_filesize' => ini_get('upload_max_filesize'),
                'post_max_size' => ini_get('post_max_size'),
            ];
            
            // Log the health check
            Guard_Dog()->activity_log->add_log_entry('health_check', [
                'username' => wp_get_current_user()->user_login,
                'user_id' => get_current_user_id(),
                'details' => $health_report
            ]);
            
            // Store health report in transient for display
            set_transient('guard_dog_health_report', $health_report, 300); // 5 minutes
            
            $this->add_admin_notice(
                __('Health check completed successfully. Check the results below.', 'guard-dog'),
                'success'
            );
            
        } catch (Exception $e) {
            Guard_Dog()->debug->error('Failed to run health check', 'settings', [
                'error' => $e->getMessage(),
                'user_id' => get_current_user_id(),
            ]);
            
            $this->add_admin_notice(
                __('Failed to run health check. Please try again.', 'guard-dog'),
                'error'
            );
        }
    }

    public function generate_support_report(): void {
        try {
            // $_SERVER['SERVER_SOFTWARE'] is a trusted server environment variable that doesn't require unslashing
            $server_software = sanitize_text_field(wp_unslash($_SERVER['SERVER_SOFTWARE'] ?? 'Unknown'));
            
            $report_data = [
                'report_date' => current_time('mysql'),
                'site_url' => get_site_url(),
                'guard_dog_version' => GUARD_DOG_VERSION,
                'wordpress_version' => get_bloginfo('version'),
                'php_version' => PHP_VERSION,
                'server_software' => $server_software,
                'mysql_version' => $GLOBALS['wpdb']->db_version(),
                'active_theme' => wp_get_theme()->get('Name'),
                'active_plugins' => get_option('active_plugins', []),
                'guard_dog_settings' => [],
                'system_info' => [],
            ];
            
            // Get all Guard Dog settings
            global $wpdb;
            // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
            // Direct database query is necessary for support report generation
            $options = $wpdb->get_results(
                $wpdb->prepare(
                    "SELECT option_name, option_value FROM {$wpdb->options} WHERE option_name LIKE %s",
                    'guard_dog_%'
                )
            );
            // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
            
            foreach ($options as $option) {
                $report_data['guard_dog_settings'][$option->option_name] = $this->redact_sensitive_export_data(
                    maybe_unserialize($option->option_value),
                    $option->option_name
                );
            }
            
            // Get system information
            $report_data['system_info'] = [
                'memory_limit' => ini_get('memory_limit'),
                'max_execution_time' => ini_get('max_execution_time'),
                'upload_max_filesize' => ini_get('upload_max_filesize'),
                'post_max_size' => ini_get('post_max_size'),
                'wp_debug' => defined('WP_DEBUG') && WP_DEBUG,
                'wp_debug_log' => defined('WP_DEBUG_LOG') && WP_DEBUG_LOG,
                'wp_debug_display' => defined('WP_DEBUG_DISPLAY') && WP_DEBUG_DISPLAY,
            ];
            
            // Get recent activity log entries (last 50)
            $activity_log_table = $wpdb->prefix . 'guard_dog_logs';
            $recent_logs = [];
            // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
            // Direct database query is necessary here so the report can gracefully handle a missing activity log table.
            $activity_log_table_exists = $wpdb->get_var(
                $wpdb->prepare(
                    'SHOW TABLES LIKE %s',
                    $activity_log_table
                )
            ) === $activity_log_table;
            // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching

            if ($activity_log_table_exists) {
                // phpcs:disable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
                // SELECT query requires table name interpolation - safe as constructed from wpdb->prefix
                // Direct database query is necessary for support report generation
                // Table names are validated and sanitized, then escaped with esc_sql() for Plugin Check compliance
                $escaped_table_name = esc_sql($activity_log_table);
                $recent_logs = $wpdb->get_results(
                    "SELECT * FROM $escaped_table_name ORDER BY timestamp DESC LIMIT 50"
                );
                // phpcs:enable WordPress.DB.PreparedSQL.InterpolatedNotPrepared,WordPress.DB.DirectDatabaseQuery.DirectQuery,WordPress.DB.DirectDatabaseQuery.NoCaching
            }

            $report_data['recent_activity_logs'] = $this->redact_sensitive_export_data($recent_logs, 'recent_activity_logs');
            
            $json_data = wp_json_encode($report_data, JSON_PRETTY_PRINT);
            if ($json_data === false) {
                throw new Exception('Failed to encode support report data');
            }

            $this->support_report_viewer_data = $this->build_support_report_viewer_data($report_data, $json_data);
            
        } catch (Exception $e) {
            Guard_Dog()->debug->error('Failed to generate support report', 'settings', [
                'error' => $e->getMessage(),
                'user_id' => get_current_user_id(),
            ]);
            
            $this->add_admin_notice(
                __('Failed to generate support report. Please try again.', 'guard-dog'),
                'error'
            );
        }
    }

    /**
     * Render the in-page support report viewer when requested from the Tools sidebar.
     */
    private function render_support_report_viewer(): void {
        if (!is_array($this->support_report_viewer_data)) {
            return;
        }

        $viewer = $this->support_report_viewer_data;
        ?>
        <div class="guard-dog-support-report">
            <div class="guard-dog-support-report__header">
                <div>
                    <h3>
                        <span class="dashicons dashicons-media-document"></span>
                        <?php esc_html_e('Support Report', 'guard-dog'); ?>
                    </h3>
                    <p><?php esc_html_e('Fresh troubleshooting snapshot, rendered inside the settings page instead of dumping raw JSON into it.', 'guard-dog'); ?></p>
                </div>
                <div class="guard-dog-support-report__meta">
                    <span><strong><?php esc_html_e('Generated:', 'guard-dog'); ?></strong> <?php echo esc_html((string) ($viewer['generated_at'] ?? __('Unknown', 'guard-dog'))); ?></span>
                    <span><strong><?php esc_html_e('Suggested filename:', 'guard-dog'); ?></strong> <code><?php echo esc_html((string) ($viewer['filename'] ?? '')); ?></code></span>
                </div>
            </div>

            <div class="guard-dog-support-report__summary">
                <div class="guard-dog-support-report__summary-item">
                    <span class="guard-dog-support-report__summary-label"><?php esc_html_e('Active Plugins', 'guard-dog'); ?></span>
                    <strong><?php echo esc_html((string) ($viewer['summary']['active_plugin_count'] ?? 0)); ?></strong>
                </div>
                <div class="guard-dog-support-report__summary-item">
                    <span class="guard-dog-support-report__summary-label"><?php esc_html_e('Guard Dog Settings', 'guard-dog'); ?></span>
                    <strong><?php echo esc_html((string) ($viewer['summary']['guard_dog_setting_count'] ?? 0)); ?></strong>
                </div>
                <div class="guard-dog-support-report__summary-item">
                    <span class="guard-dog-support-report__summary-label"><?php esc_html_e('Recent Activity Entries', 'guard-dog'); ?></span>
                    <strong><?php echo esc_html((string) ($viewer['summary']['recent_activity_count'] ?? 0)); ?></strong>
                </div>
                <div class="guard-dog-support-report__summary-item">
                    <span class="guard-dog-support-report__summary-label"><?php esc_html_e('JSON Size', 'guard-dog'); ?></span>
                    <strong><?php echo esc_html(size_format((int) ($viewer['json_size_bytes'] ?? 0))); ?></strong>
                </div>
            </div>

            <div class="guard-dog-support-report__grid">
                <section class="guard-dog-support-report__section">
                    <h4><?php esc_html_e('Environment Snapshot', 'guard-dog'); ?></h4>
                    <div class="guard-dog-support-report__facts">
                        <?php foreach (($viewer['overview'] ?? []) as $label => $value): ?>
                            <div class="guard-dog-support-report__fact">
                                <span class="guard-dog-support-report__fact-label"><?php echo esc_html((string) $label); ?></span>
                                <span class="guard-dog-support-report__fact-value"><?php echo esc_html($this->format_support_report_value($value)); ?></span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </section>

                <section class="guard-dog-support-report__section">
                    <h4><?php esc_html_e('System Flags', 'guard-dog'); ?></h4>
                    <div class="guard-dog-support-report__facts">
                        <?php foreach (($viewer['system_info'] ?? []) as $label => $value): ?>
                            <div class="guard-dog-support-report__fact">
                                <span class="guard-dog-support-report__fact-label"><?php echo esc_html(ucwords(str_replace('_', ' ', (string) $label))); ?></span>
                                <span class="guard-dog-support-report__fact-value"><?php echo esc_html($this->format_support_report_value($value)); ?></span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </section>
            </div>

            <?php if (!empty($viewer['active_plugins'])): ?>
                <details class="guard-dog-support-report__details">
                    <summary>
                        <?php
                        printf(
                            /* translators: %d: number of active plugins */
                            esc_html__('Active Plugins (%d)', 'guard-dog'),
                            (int) count($viewer['active_plugins'])
                        );
                        ?>
                    </summary>
                    <ul class="guard-dog-support-report__plugin-list">
                        <?php foreach ($viewer['active_plugins'] as $plugin_file): ?>
                            <li><code><?php echo esc_html((string) $plugin_file); ?></code></li>
                        <?php endforeach; ?>
                    </ul>
                </details>
            <?php endif; ?>

            <details class="guard-dog-support-report__details">
                <summary><?php esc_html_e('Guard Dog Settings Snapshot', 'guard-dog'); ?></summary>
                <pre class="guard-dog-support-report__code"><?php echo esc_html((string) ($viewer['guard_dog_settings_json'] ?? '')); ?></pre>
            </details>

            <section class="guard-dog-support-report__section">
                <h4><?php esc_html_e('Recent Activity', 'guard-dog'); ?></h4>
                <?php if (empty($viewer['recent_logs'])): ?>
                    <div class="guard-dog-support-report__empty">
                        <p><?php esc_html_e('No recent Guard Dog activity log entries were available for this report.', 'guard-dog'); ?></p>
                    </div>
                <?php else: ?>
                    <div class="guard-dog-support-report__activity">
                        <?php foreach ($viewer['recent_logs'] as $entry): ?>
                            <article class="guard-dog-support-report__activity-entry">
                                <div class="guard-dog-support-report__activity-header">
                                    <strong><?php echo esc_html((string) ($entry['event_label'] ?? __('Unknown Event', 'guard-dog'))); ?></strong>
                                    <?php if (!empty($entry['timestamp'])): ?>
                                        <time><?php echo esc_html((string) $entry['timestamp']); ?></time>
                                    <?php endif; ?>
                                </div>
                                <div class="guard-dog-support-report__activity-meta">
                                    <?php if (!empty($entry['username'])): ?>
                                        <span><?php printf(esc_html__('User: %s', 'guard-dog'), esc_html((string) $entry['username'])); ?></span>
                                    <?php endif; ?>
                                    <?php if (!empty($entry['ip_address'])): ?>
                                        <span><?php printf(esc_html__('IP: %s', 'guard-dog'), esc_html((string) $entry['ip_address'])); ?></span>
                                    <?php endif; ?>
                                    <?php if (!empty($entry['event_type'])): ?>
                                        <span><code><?php echo esc_html((string) $entry['event_type']); ?></code></span>
                                    <?php endif; ?>
                                </div>
                                <?php if (!empty($entry['details'])): ?>
                                    <pre class="guard-dog-support-report__code"><?php echo esc_html((string) $entry['details']); ?></pre>
                                <?php endif; ?>
                            </article>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </section>

            <details class="guard-dog-support-report__details">
                <summary><?php esc_html_e('Raw JSON Support Report', 'guard-dog'); ?></summary>
                <pre class="guard-dog-support-report__code"><?php echo esc_html((string) ($viewer['json'] ?? '')); ?></pre>
            </details>
        </div>
        <?php
    }

    /**
     * Build structured data for the in-page support report viewer.
     *
     * @param array  $report_data Raw support report payload.
     * @param string $json_data Pretty-printed JSON payload.
     * @return array
     */
    private function build_support_report_viewer_data(array $report_data, string $json_data): array {
        $active_plugins = [];
        foreach ((array) ($report_data['active_plugins'] ?? []) as $plugin_file) {
            if (!is_string($plugin_file) || $plugin_file === '') {
                continue;
            }

            $active_plugins[] = $plugin_file;
        }

        $guard_dog_settings = is_array($report_data['guard_dog_settings'] ?? null)
            ? $report_data['guard_dog_settings']
            : [];

        $guard_dog_settings_json = wp_json_encode($guard_dog_settings, JSON_PRETTY_PRINT);
        if ($guard_dog_settings_json === false) {
            $guard_dog_settings_json = __('Unable to encode Guard Dog settings for display.', 'guard-dog');
        }

        $recent_logs = is_array($report_data['recent_activity_logs'] ?? null)
            ? $report_data['recent_activity_logs']
            : [];

        return [
            'filename' => 'guard-dog-support-report-' . gmdate('Y-m-d-H-i-s') . '.json',
            'generated_at' => (string) ($report_data['report_date'] ?? current_time('mysql')),
            'json' => $json_data,
            'json_size_bytes' => strlen($json_data),
            'summary' => [
                'active_plugin_count' => count($active_plugins),
                'guard_dog_setting_count' => count($guard_dog_settings),
                'recent_activity_count' => count($recent_logs),
            ],
            'overview' => [
                __('Site URL', 'guard-dog') => (string) ($report_data['site_url'] ?? ''),
                __('Guard Dog Version', 'guard-dog') => (string) ($report_data['guard_dog_version'] ?? ''),
                __('WordPress Version', 'guard-dog') => (string) ($report_data['wordpress_version'] ?? ''),
                __('PHP Version', 'guard-dog') => (string) ($report_data['php_version'] ?? ''),
                __('MySQL Version', 'guard-dog') => (string) ($report_data['mysql_version'] ?? ''),
                __('Active Theme', 'guard-dog') => (string) ($report_data['active_theme'] ?? ''),
                __('Server Software', 'guard-dog') => (string) ($report_data['server_software'] ?? ''),
            ],
            'system_info' => is_array($report_data['system_info'] ?? null) ? $report_data['system_info'] : [],
            'active_plugins' => $active_plugins,
            'guard_dog_settings_json' => (string) $guard_dog_settings_json,
            'recent_logs' => $this->normalize_support_report_logs($recent_logs),
        ];
    }

    /**
     * Normalize recent activity log rows for the support report viewer.
     *
     * @param array $recent_logs Raw database rows.
     * @return array
     */
    private function normalize_support_report_logs(array $recent_logs): array {
        $entries = [];

        foreach ($recent_logs as $log_entry) {
            $row = is_object($log_entry) ? get_object_vars($log_entry) : (array) $log_entry;
            $event_type = sanitize_text_field((string) ($row['event_type'] ?? ''));

            $entries[] = [
                'timestamp' => sanitize_text_field((string) ($row['timestamp'] ?? '')),
                'event_type' => $event_type,
                'event_label' => class_exists('Guard_Dog_Activity_Log')
                    ? Guard_Dog_Activity_Log::get_event_label($event_type)
                    : ($event_type !== '' ? ucwords(str_replace('_', ' ', $event_type)) : __('Unknown Event', 'guard-dog')),
                'username' => sanitize_text_field((string) ($row['username'] ?? '')),
                'ip_address' => sanitize_text_field((string) ($row['ip_address'] ?? '')),
                'details' => $this->format_support_report_log_details($row['details'] ?? ''),
            ];
        }

        return $entries;
    }

    /**
     * Format a support report value for display in key/value sections.
     *
     * @param mixed $value Raw value.
     * @return string
     */
    private function format_support_report_value($value): string {
        if (is_bool($value)) {
            return $value ? __('Enabled', 'guard-dog') : __('Disabled', 'guard-dog');
        }

        if ($value === null || $value === '') {
            return __('Not set', 'guard-dog');
        }

        if (is_array($value) || is_object($value)) {
            $json_value = wp_json_encode($value, JSON_PRETTY_PRINT);
            return $json_value !== false
                ? (string) $json_value
                : __('Unable to encode value.', 'guard-dog');
        }

        return (string) $value;
    }

    /**
     * Format activity log details for the support report viewer.
     *
     * @param mixed $details Raw details payload.
     * @return string
     */
    private function format_support_report_log_details($details): string {
        if ($details === null || $details === '') {
            return '';
        }

        if (is_array($details) || is_object($details)) {
            $json_value = wp_json_encode($details, JSON_PRETTY_PRINT);
            return $json_value !== false ? (string) $json_value : '';
        }

        if (is_string($details)) {
            $decoded_details = json_decode($details, true);
            if (json_last_error() === JSON_ERROR_NONE) {
                $json_value = wp_json_encode($decoded_details, JSON_PRETTY_PRINT);
                return $json_value !== false ? (string) $json_value : $details;
            }

            return $details;
        }

        return (string) $details;
    }

    private function add_admin_notice(string $message, string $type = 'info'): void {
        // Add notice to WordPress admin notices
        add_action('admin_notices', function() use ($message, $type) {
            $class = 'notice notice-' . $type;
            printf('<div class="%1$s"><p>%2$s</p></div>', esc_attr($class), esc_html($message));
        });
    }

    /**
     * Render system information sidebar
     */
    private function render_system_info(): void {
        global $wp_version;

        $system_info = [
            'WordPress Version' => $wp_version,
            'PHP Version' => PHP_VERSION,
            'MySQL Version' => $GLOBALS['wpdb']->db_version(),
            'Guard Dog Version' => GUARD_DOG_VERSION,
            'Memory Limit' => WP_MEMORY_LIMIT,
            'Max Upload Size' => size_format(wp_max_upload_size()),
            'Server Software' => sanitize_text_field(wp_unslash($_SERVER['SERVER_SOFTWARE'] ?? 'Unknown')),
            'PHP Extensions' => implode(', ', get_loaded_extensions())
        ];
        ?>
        <div class="guard-dog-card">
            <h3>
                <span class="dashicons dashicons-info"></span>
                <?php esc_html_e('System Information', 'guard-dog'); ?>
            </h3>
            
            <div>
                <?php foreach ($system_info as $label => $value): ?>
                    <div class="guard-dog-info-item">
                        <span class="guard-dog-info-label"><?php echo esc_html($label); ?></span>
                        <span class="guard-dog-info-value"><?php echo esc_html($value); ?></span>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php
    }

    /**
     * Render tools sidebar
     */
    private function render_tools(): void {
        ?>
        <div class="guard-dog-card">
            <h3>
                <span class="dashicons dashicons-hammer"></span>
                <?php esc_html_e('Tools', 'guard-dog'); ?>
            </h3>
            
            <div>
                <form method="post" class="guard-dog-inline-form">
                    <?php wp_nonce_field('guard_dog_settings_action', 'guard_dog_nonce'); ?>
                    <input type="hidden" name="guard_dog_action" value="view_debug_log">
                    <button type="submit" class="button guard-dog-tools-button">
                        <?php esc_html_e('View Debug Log', 'guard-dog'); ?>
                    </button>
                </form>
                
                <form method="post" class="guard-dog-inline-form">
                    <?php wp_nonce_field('guard_dog_settings_action', 'guard_dog_nonce'); ?>
                    <input type="hidden" name="guard_dog_action" value="run_health_check">
                    <button type="submit" class="button guard-dog-tools-button">
                        <?php esc_html_e('Run Health Check', 'guard-dog'); ?>
                    </button>
                </form>
                
                <form method="post" class="guard-dog-inline-form">
                    <?php wp_nonce_field('guard_dog_settings_action', 'guard_dog_nonce'); ?>
                    <input type="hidden" name="guard_dog_action" value="generate_support_report">
                    <button type="submit" class="button guard-dog-tools-button guard-dog-tools-button-last">
                        <?php esc_html_e('Generate Support Report', 'guard-dog'); ?>
                    </button>
                </form>
            </div>
        </div>
        <?php
    }

    /**
     * Render health check results
     */
    private function render_health_check_results(): void {
        $health_report = get_transient('guard_dog_health_report');

        if (!$health_report) {
            return;
        }

        // Clear the transient after displaying
        delete_transient('guard_dog_health_report');
        ?>
        <div class="guard-dog-health-check-results">
            <h3>
                <span class="dashicons dashicons-heart"></span>
                <?php esc_html_e('Health Check Results', 'guard-dog'); ?>
            </h3>
            
            <div class="guard-dog-health-grid">
                <!-- Database Status -->
                <div class="guard-dog-health-section">
                    <h4><?php esc_html_e('Database Status', 'guard-dog'); ?></h4>
                    <ul>
                        <li>
                            <span class="dashicons <?php echo esc_attr($health_report['database']['activity_log_table_exists'] ? 'dashicons-yes-alt' : 'dashicons-no-alt'); ?>"></span>
                            <?php esc_html_e('Activity Log Table:', 'guard-dog'); ?>
                            <?php echo $health_report['database']['activity_log_table_exists'] ? esc_html__('Exists', 'guard-dog') : esc_html__('Missing', 'guard-dog'); ?>
                        </li>
                        <li>
                            <span class="dashicons dashicons-chart-bar"></span>
                            <?php esc_html_e('Log Entries:', 'guard-dog'); ?>
                            <?php echo esc_html($health_report['database']['activity_log_table_count']); ?>
                        </li>
                    </ul>
                </div>
                
                <!-- File System Status -->
                <div class="guard-dog-health-section">
                    <h4><?php esc_html_e('File System Status', 'guard-dog'); ?></h4>
                    <ul>
                        <li>
                            <span class="dashicons <?php echo esc_attr($health_report['files']['wordpress_debug_log_exists'] ? 'dashicons-yes-alt' : 'dashicons-no-alt'); ?>"></span>
                            <?php esc_html_e('WordPress Debug Log:', 'guard-dog'); ?>
                            <?php echo $health_report['files']['wordpress_debug_log_exists'] ? esc_html__('Exists', 'guard-dog') : esc_html__('Missing', 'guard-dog'); ?>
                        </li>
                        <li>
                            <span class="dashicons <?php echo esc_attr($health_report['files']['upload_dir_writable'] ? 'dashicons-yes-alt' : 'dashicons-no-alt'); ?>"></span>
                            <?php esc_html_e('Upload Directory:', 'guard-dog'); ?>
                            <?php echo $health_report['files']['upload_dir_writable'] ? esc_html__('Writable', 'guard-dog') : esc_html__('Not Writable', 'guard-dog'); ?>
                        </li>
                    </ul>
                </div>
                
                <!-- WordPress Configuration -->
                <div class="guard-dog-health-section">
                    <h4><?php esc_html_e('WordPress Configuration', 'guard-dog'); ?></h4>
                    <ul>
                        <li>
                            <span class="dashicons <?php echo esc_attr($health_report['wordpress']['wp_debug'] ? 'dashicons-yes-alt' : 'dashicons-no-alt'); ?>"></span>
                            <?php esc_html_e('WP_DEBUG:', 'guard-dog'); ?>
                            <?php echo $health_report['wordpress']['wp_debug'] ? esc_html__('Enabled', 'guard-dog') : esc_html__('Disabled', 'guard-dog'); ?>
                        </li>
                        <li>
                            <span class="dashicons <?php echo esc_attr($health_report['wordpress']['wp_debug_log'] ? 'dashicons-yes-alt' : 'dashicons-no-alt'); ?>"></span>
                            <?php esc_html_e('WP_DEBUG_LOG:', 'guard-dog'); ?>
                            <?php echo $health_report['wordpress']['wp_debug_log'] ? esc_html__('Enabled', 'guard-dog') : esc_html__('Disabled', 'guard-dog'); ?>
                        </li>
                    </ul>
                </div>
                
                <!-- Guard Dog Configuration -->
                <div class="guard-dog-health-section">
                    <h4><?php esc_html_e('Guard Dog Configuration', 'guard-dog'); ?></h4>
                    <ul>
                        <li>
                            <span class="dashicons <?php echo esc_attr($health_report['guard_dog']['debug_enabled'] ? 'dashicons-yes-alt' : 'dashicons-no-alt'); ?>"></span>
                            <?php esc_html_e('Debug Logging:', 'guard-dog'); ?>
                            <?php echo $health_report['guard_dog']['debug_enabled'] ? esc_html__('Enabled', 'guard-dog') : esc_html__('Disabled', 'guard-dog'); ?>
                        </li>
                        <li>
                            <span class="dashicons dashicons-admin-tools"></span>
                            <?php esc_html_e('Debug Level:', 'guard-dog'); ?>
                            <?php echo esc_html(ucfirst($health_report['guard_dog']['debug_level'])); ?>
                        </li>
                        <li>
                            <span class="dashicons dashicons-shield"></span>
                            <?php esc_html_e('CAPTCHA Provider:', 'guard-dog'); ?>
                            <?php echo esc_html(ucfirst($health_report['guard_dog']['captcha_provider'])); ?>
                        </li>
                    </ul>
                </div>
                
                <!-- PHP Configuration -->
                <div class="guard-dog-health-section">
                    <h4><?php esc_html_e('PHP Configuration', 'guard-dog'); ?></h4>
                    <ul>
                        <li>
                            <span class="dashicons dashicons-info"></span>
                            <?php esc_html_e('PHP Version:', 'guard-dog'); ?>
                            <?php echo esc_html($health_report['php']['version']); ?>
                        </li>
                        <li>
                            <span class="dashicons dashicons-performance"></span>
                            <?php esc_html_e('Memory Limit:', 'guard-dog'); ?>
                            <?php echo esc_html($health_report['php']['memory_limit']); ?>
                        </li>
                        <li>
                            <span class="dashicons dashicons-clock"></span>
                            <?php esc_html_e('Max Execution Time:', 'guard-dog'); ?>
                            <?php echo esc_html($health_report['php']['max_execution_time']); ?>s
                        </li>
                    </ul>
                </div>
            </div>
            
            <div class="guard-dog-health-actions">
                <button type="button" class="button guard-dog-dismiss-health-check">
                    <?php esc_html_e('Dismiss', 'guard-dog'); ?>
                </button>
            </div>
        </div>
        <?php
    }

    /**
     * Enqueue scripts and styles for the settings page
     */
    private function enqueue_settings_assets(): void {
        // Only enqueue on the settings page
        if (!$this->is_settings_page()) {
            return;
        }

        $settings_js_path = GUARD_DOG_PATH . 'assets/js/guard-dog-settings-page.js';
        $settings_js_version = GUARD_DOG_VERSION;
        if (file_exists($settings_js_path)) {
            $settings_js_version .= '.' . (string) filemtime($settings_js_path);
        }

        wp_enqueue_script(
            'guard-dog-settings-page',
            GUARD_DOG_URL . 'assets/js/guard-dog-settings-page.js',
            ['jquery'],
            $settings_js_version,
            true
        );

        wp_enqueue_style(
            'guard-dog-settings-page',
            GUARD_DOG_URL . 'assets/css/guard-dog-settings-page.css',
            [],
            GUARD_DOG_VERSION
        );

        // Localize script with AJAX data
        wp_localize_script('guard-dog-settings-page', 'guard_dog_settings', [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('guard_dog_test_email_provider'),
            'googleOAuthDisconnectNonce' => wp_create_nonce('guard_dog_google_oauth_disconnect'),
            'googleAliasPreflightNonce' => wp_create_nonce('guard_dog_google_alias_preflight'),
            'googleAliasListNonce' => wp_create_nonce('guard_dog_google_aliases_list'),
            'strings' => [
                'sending' => __('Sending...', 'guard-dog'),
                'sendTestEmail' => __('Send Test Email', 'guard-dog'),
                'pleaseEnterEmail' => __('Please enter a test email address.', 'guard-dog'),
                'sendingTestEmail' => __('Sending test email...', 'guard-dog'),
                'networkError' => __('Network error. Please try again.', 'guard-dog'),
                'anErrorOccurred' => __('An error occurred.', 'guard-dog'),
                'savingSettingsBeforeOAuth' => __('Saving Google settings before connecting...', 'guard-dog'),
                'disconnectingOAuth' => __('Disconnecting OAuth...', 'guard-dog'),
                'checkingAlias' => __('Checking alias configuration...', 'guard-dog'),
                'loadingAliases' => __('Loading Gmail aliases...', 'guard-dog'),
                'fromEmailRequired' => __('Please enter a valid From email address first.', 'guard-dog'),
                'providerConfigSuffix' => __('Configuration', 'guard-dog'),
                'providerConfigFallback' => __('Email Provider Configuration', 'guard-dog'),
                'noAliasesFound' => __('No Gmail aliases were returned for this account.', 'guard-dog'),
                'aliasesLoaded' => __('Gmail aliases loaded.', 'guard-dog'),
                'selectAliasPrompt' => __('Select a Gmail alias', 'guard-dog'),
                'selectAliasFirst' => __('Select an alias first.', 'guard-dog'),
                'savedAliasLabel' => __('saved alias', 'guard-dog'),
                'aliasApplied' => __('Selected alias applied to From Email.', 'guard-dog'),
                'oauthDisconnected' => __('Google OAuth disconnected.', 'guard-dog'),
                'oauthDisconnectFailed' => __('Failed to disconnect Google OAuth.', 'guard-dog'),
                'aliasLoadFailed' => __('Failed to load Gmail aliases.', 'guard-dog'),
            ]
        ]);
    }

    /**
     * Check if current page is the settings page
     */
    private function is_settings_page(): bool {
        return isset($_GET['page']) && sanitize_text_field(wp_unslash($_GET['page'])) === 'guard-dog-settings';
    }
}
