<?php

/**
 * Guard Dog Admin Controller
 * 
 * Manages the admin interface with a modern multi-page architecture.
 * Replaces the monolithic admin-settings approach with organized,
 * feature-specific pages for better user experience.
 *
 * @package GuardDog
 * @since 1.6.0
 */

if (!defined('ABSPATH')) {
    exit; // Exit if accessed directly
}

class Guard_Dog_Admin {

    /**
     * Admin page slugs — consolidated menu structure
     */
    const DASHBOARD_SLUG = 'guard-dog';
    const AUTHENTICATION_SLUG = 'guard-dog-authentication';
    const ACCESS_CONTROL_SLUG = 'guard-dog-access';
    const USERS_SESSIONS_SLUG = 'guard-dog-users-sessions';
    const ACTIVITY_LOG_SLUG = 'guard-dog-logs';
    const APPEARANCE_SLUG = 'guard-dog-appearance';
    const SETTINGS_SLUG = 'guard-dog-settings';

    /**
     * Legacy slugs — kept for settings registration backward compatibility.
     * These are not registered as menu items but are referenced by
     * existing settings groups and option keys.
     */
    const CAPTCHA_SLUG = 'guard-dog-captcha';
    const LOGIN_SECURITY_SLUG = 'guard-dog-login';
    const TEMP_ACCESS_SLUG = 'guard-dog-temp';
    const USER_REGISTRATION_SLUG = 'guard-dog-user-registration';
    const SESSIONS_SLUG = 'guard-dog-sessions';

    /**
     * Page instances
     * @var array
     */
    private $pages = [];

    /**
     * Feature instances
     * @var array
     */
    private $features = [];

    /**
     * Current admin page
     * @var string
     */
    private $current_page = '';

    /**
     * Initialize the admin interface
     *
     * @param array $features Feature class instances
     */
    public function __construct(array $features = []) {
        $this->features = $features;
        $this->init_hooks();
        $this->load_page_classes();
    }

    /**
     * Initialize WordPress hooks
     */
    private function init_hooks(): void {
        // Register screen option filters early (before admin_menu)
        add_filter('set-screen-option', [$this, 'set_screen_option'], 10, 3);
        add_filter('set_screen_option_guard_dog_activity_logs_per_page', [$this, 'set_screen_option_specific'], 10, 3);
        
        add_action('admin_menu', [$this, 'register_admin_pages']);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_admin_assets']);
        add_action('admin_init', [$this, 'handle_page_actions']);
        add_action('admin_init', [$this, 'register_login_security_settings']);
        add_action('admin_init', [$this, 'register_access_control_settings']);
        add_action('admin_init', [$this, 'register_captcha_settings']);
        add_action('admin_init', [$this, 'register_temp_access_settings']);
        add_action('admin_init', [$this, 'register_general_settings']);
        add_action('admin_init', [$this, 'register_activity_log_settings']);
        add_action('admin_init', [$this, 'register_user_registration_settings']);
        add_action('admin_init', [$this, 'register_sessions_settings']);
        add_action('admin_notices', [$this, 'show_debug_warnings']);
        
        // AJAX handlers
        add_action('wp_ajax_guard_dog_search_users', [$this, 'handle_ajax_search_users']);
        add_action('wp_ajax_guard_dog_get_user_suggestions', [$this, 'handle_ajax_get_user_suggestions']);
        add_action('wp_ajax_guard_dog_force_db_update', [$this, 'handle_force_db_update']);
        add_action('wp_ajax_guard_dog_check_ip_reputation', [$this, 'handle_ajax_check_ip_reputation']);
        add_action('wp_ajax_guard_dog_add_ip_to_blacklist', [$this, 'handle_ajax_add_ip_to_blacklist']);
        add_action('wp_ajax_guard_dog_remove_ip_from_blacklist', [$this, 'handle_ajax_remove_ip_from_blacklist']);
        add_action('wp_ajax_guard_dog_add_country_to_blacklist', [$this, 'handle_ajax_add_country_to_blacklist']);
        add_action('wp_ajax_guard_dog_remove_country_from_blacklist', [$this, 'handle_ajax_remove_country_from_blacklist']);
        add_action('wp_ajax_guard_dog_trigger_expiration_check', [$this, 'handle_ajax_trigger_expiration_check']);
    }

    /**
     * Load page class files
     */
    private function load_page_classes() {
        // Core page classes (used directly and as delegates)
        require_once GUARD_DOG_PATH . 'includes/admin/pages/class-dashboard-page.php';
        require_once GUARD_DOG_PATH . 'includes/admin/pages/class-captcha-page.php';
        require_once GUARD_DOG_PATH . 'includes/admin/pages/class-login-security-page.php';
        require_once GUARD_DOG_PATH . 'includes/admin/pages/class-access-control-page.php';
        require_once GUARD_DOG_PATH . 'includes/admin/pages/class-temp-access-page.php';
        require_once GUARD_DOG_PATH . 'includes/admin/pages/class-activity-log-page.php';
        require_once GUARD_DOG_PATH . 'includes/admin/pages/class-settings-page.php';
        require_once GUARD_DOG_PATH . 'includes/admin/pages/class-user-registration-page.php';
        require_once GUARD_DOG_PATH . 'includes/admin/pages/class-sessions-page.php';

        // Consolidated page classes (compose delegate pages above)
        require_once GUARD_DOG_PATH . 'includes/admin/pages/class-authentication-page.php';
        require_once GUARD_DOG_PATH . 'includes/admin/pages/class-users-sessions-page.php';
        require_once GUARD_DOG_PATH . 'includes/admin/pages/class-appearance-page.php';
    }

    /**
     * Register admin menu pages
     */
    public function register_admin_pages(): void {
        // Main menu page (Dashboard)
        add_menu_page(
            __('Guard Dog Security', 'guard-dog'),
            __('Guard Dog', 'guard-dog'),
            'manage_options',
            self::DASHBOARD_SLUG,
            [$this, 'render_dashboard_page'],
            'dashicons-pets',
            30
        );

        // Submenu pages — consolidated menu structure
        $submenus = [
            [
                'parent' => self::DASHBOARD_SLUG,
                'page_title' => __('Guard Dog Dashboard', 'guard-dog'),
                'menu_title' => __('Dashboard', 'guard-dog'),
                'slug' => self::DASHBOARD_SLUG,
                'callback' => [$this, 'render_dashboard_page']
            ],
            [
                'parent' => self::DASHBOARD_SLUG,
                'page_title' => __('Authentication', 'guard-dog'),
                'menu_title' => __('Authentication', 'guard-dog'),
                'slug' => self::AUTHENTICATION_SLUG,
                'callback' => [$this, 'render_authentication_page']
            ],
            [
                'parent' => self::DASHBOARD_SLUG,
                'page_title' => __('Access Control', 'guard-dog'),
                'menu_title' => __('Access Control', 'guard-dog'),
                'slug' => self::ACCESS_CONTROL_SLUG,
                'callback' => [$this, 'render_access_control_page']
            ],
            [
                'parent' => self::DASHBOARD_SLUG,
                'page_title' => __('Users & Sessions', 'guard-dog'),
                'menu_title' => __('Users & Sessions', 'guard-dog'),
                'slug' => self::USERS_SESSIONS_SLUG,
                'callback' => [$this, 'render_users_sessions_page']
            ],
            [
                'parent' => self::DASHBOARD_SLUG,
                'page_title' => __('Activity Log', 'guard-dog'),
                'menu_title' => __('Activity Log', 'guard-dog'),
                'slug' => self::ACTIVITY_LOG_SLUG,
                'callback' => [$this, 'render_activity_log_page']
            ],
            [
                'parent' => self::DASHBOARD_SLUG,
                'page_title' => __('Appearance', 'guard-dog'),
                'menu_title' => __('Appearance', 'guard-dog'),
                'slug' => self::APPEARANCE_SLUG,
                'callback' => [$this, 'render_appearance_page']
            ],
            [
                'parent' => self::DASHBOARD_SLUG,
                'page_title' => __('Settings', 'guard-dog'),
                'menu_title' => __('Settings', 'guard-dog'),
                'slug' => self::SETTINGS_SLUG,
                'callback' => [$this, 'render_settings_page']
            ]
        ];

        foreach ($submenus as $submenu) {
            add_submenu_page(
                $submenu['parent'],
                $submenu['page_title'],
                $submenu['menu_title'],
                'manage_options',
                $submenu['slug'],
                $submenu['callback']
            );
        }
        
        // Add screen options hook (filters are registered in init_hooks for early registration)
        add_action('load-guard-dog_page_' . self::ACTIVITY_LOG_SLUG, [$this, 'setup_activity_log_page']);
    }

    /**
     * Enqueue admin assets
     */
    public function enqueue_admin_assets($hook_suffix): void {
        // Only load on Guard Dog pages
        if (strpos($hook_suffix, 'guard-dog') === false) {
            return;
        }

        // Enqueue base admin CSS
        wp_enqueue_style(
            'guard-dog-admin',
            GUARD_DOG_URL . 'assets/css/guard-dog-admin.css',
            [],
            GUARD_DOG_VERSION
        );

        // Enqueue shared admin layout CSS
        wp_enqueue_style(
            'guard-dog-admin-layout',
            GUARD_DOG_URL . 'assets/css/guard-dog-admin-layout.css',
            [],
            GUARD_DOG_VERSION
        );

        // Enqueue page-specific CSS based on current page
        $current_page = $this->get_current_page_slug();
        $this->enqueue_page_specific_assets($current_page);

        // Enqueue admin JavaScript
        wp_enqueue_script(
            'guard-dog-admin',
            GUARD_DOG_URL . 'assets/js/guard-dog-admin.js',
            ['jquery', 'wp-util'],
            GUARD_DOG_VERSION,
            true
        );

        // Localize script with admin data
        wp_localize_script('guard-dog-admin', 'guard_dog_admin', [
            'ajaxUrl' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('guard_dog_admin'),
            'currentPage' => $current_page,
            'currentIp' => $this->get_client_ip(),
            'strings' => [
                'confirmClear' => __('Are you sure you want to clear all activity logs?', 'guard-dog'),
                'saving' => __('Saving...', 'guard-dog'),
                'saved' => __('Settings saved successfully!', 'guard-dog'),
                'error' => __('An error occurred. Please try again.', 'guard-dog')
            ]
        ]);

        // Localize script for access control page
        if ($current_page === self::ACCESS_CONTROL_SLUG) {
            wp_localize_script('guard-dog-admin', 'guard_dog_ajax', [
                'nonce' => wp_create_nonce('guard_dog_ajax'),
                'current_ip' => $this->get_client_ip()
            ]);
        }
        
        // Localize temp access and user registration scripts on Users & Sessions page
        if ($current_page === self::USERS_SESSIONS_SLUG) {
            wp_localize_script('guard-dog-' . self::USERS_SESSIONS_SLUG . '-1', 'guard_dog_temp_access', [
                'copyMessage' => __('Link copied to clipboard!', 'guard-dog')
            ]);
            wp_localize_script('guard-dog-' . self::USERS_SESSIONS_SLUG, 'guardDogUserRegistration', [
                'ajaxUrl' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('guard_dog_admin'),
                'strings' => [
                    'confirmSend' => __('This will immediately check all users and send any pending expiration emails. Continue?', 'guard-dog'),
                    'sending' => __('Sending...', 'guard-dog'),
                    'complete' => __('Complete!', 'guard-dog'),
                    'usersChecked' => __('Users checked:', 'guard-dog'),
                    'warningsSent' => __('Warnings sent:', 'guard-dog'),
                    'noticesSent' => __('Notices sent:', 'guard-dog'),
                    'error' => __('Error:', 'guard-dog'),
                    'unknownError' => __('Unknown error', 'guard-dog'),
                    'requestFailed' => __('Request failed. Please try again.', 'guard-dog'),
                    'buttonText' => __('Send Expiration Emails Now', 'guard-dog')
                ]
            ]);
        }
    }

    /**
     * Enqueue page-specific CSS and JS files
     */
    private function enqueue_page_specific_assets(string $current_page): void {
        $page_assets = [
            self::DASHBOARD_SLUG => [
                'css' => 'guard-dog-dashboard-page.css',
                'js' => 'guard-dog-dashboard-page.js'
            ],
            self::AUTHENTICATION_SLUG => [
                'css' => [
                    'guard-dog-login-security-page.css',
                    'guard-dog-captcha-page.css',
                    'guard-dog-captcha.css',
                ],
                'js' => [
                    'guard-dog-login-security-page.js',
                    'guard-dog-captcha-page.js',
                    'guard-dog-authentication-page.js',
                ]
            ],
            self::ACCESS_CONTROL_SLUG => [
                'css' => 'guard-dog-access-control-page.css',
                'js' => 'guard-dog-access-control-page.js'
            ],
            self::USERS_SESSIONS_SLUG => [
                'css' => [
                    'guard-dog-user-registration.css',
                    'guard-dog-temp-access-page.css',
                    'guard-dog-sessions-page.css',
                ],
                'js' => [
                    'guard-dog-users-sessions-page.js',
                    'guard-dog-user-registration-page.js',
                    'guard-dog-temp-access-page.js',
                    'guard-dog-sessions-page.js',
                ]
            ],
            self::ACTIVITY_LOG_SLUG => [
                'css' => 'guard-dog-activity-log-page.css',
                'js' => 'guard-dog-activity-log-page.js'
            ],
            self::APPEARANCE_SLUG => [
                'css' => 'guard-dog-appearance-page.css',
            ],
        ];

        if (isset($page_assets[$current_page])) {
            $assets = $page_assets[$current_page];
            
            // Enqueue CSS files
            if (isset($assets['css'])) {
                $css_files = is_array($assets['css']) ? $assets['css'] : [$assets['css']];
                foreach ($css_files as $index => $css_file) {
                    $handle = 'guard-dog-' . $current_page . ($index > 0 ? '-' . $index : '');
                    
                    // Determine the correct path based on file location
                            if (file_exists(GUARD_DOG_PATH . 'assets/css/' . $css_file)) {
            $css_url = GUARD_DOG_URL . 'assets/css/' . $css_file;
                    } else {
                        $css_url = GUARD_DOG_URL . 'assets/css/' . $css_file;
                    }
                    
                    wp_enqueue_style(
                        $handle,
                        $css_url,
                        ['guard-dog-admin'],
                        GUARD_DOG_VERSION
                    );
                }
            }
            
            // Enqueue JS files
            if (isset($assets['js'])) {
                $js_files = is_array($assets['js']) ? $assets['js'] : [$assets['js']];
                foreach ($js_files as $index => $js_file) {
                    $handle = 'guard-dog-' . $current_page . ($index > 0 ? '-' . $index : '');
                    
                    // Determine the correct path based on file location
                            if (file_exists(GUARD_DOG_PATH . 'assets/js/' . $js_file)) {
            $js_url = GUARD_DOG_URL . 'assets/js/' . $js_file;
                    } else {
                        $js_url = GUARD_DOG_URL . 'assets/js/' . $js_file;
                    }
                    
                    wp_enqueue_script(
                        $handle,
                        $js_url,
                        ['jquery', 'guard-dog-admin'],
                        GUARD_DOG_VERSION,
                        true
                    );
                }
            }
        }
    }

    /**
     * Register login security settings
     */
    public function register_login_security_settings(): void {
        if (class_exists('Guard_Dog_Login_Security_Page')) {
            Guard_Dog_Login_Security_Page::register_settings();
        }
    }

    /**
     * Register access control settings
     */
    public function register_access_control_settings(): void {
        if (class_exists('Guard_Dog_Access_Control_Page')) {
            Guard_Dog_Access_Control_Page::register_settings();
        }
    }

    /**
     * Register captcha settings
     */
    public function register_captcha_settings(): void {
        if (class_exists('Guard_Dog_Captcha_Page')) {
            Guard_Dog_Captcha_Page::register_settings();
        }
    }

    /**
     * Register temporary access settings
     */
    public function register_temp_access_settings(): void {
        if (class_exists('Guard_Dog_Temp_Access_Page')) {
            Guard_Dog_Temp_Access_Page::register_settings();
        }
    }

    public function register_user_registration_settings(): void {
        if (class_exists('Guard_Dog_User_Registration_Page')) {
            Guard_Dog_User_Registration_Page::register_settings();
        }
    }

    /**
     * Register session management settings.
     *
     * @since 1.9.1
     */
    public function register_sessions_settings(): void {
        register_setting('guard_dog_sessions_settings', 'guard_dog_sessions_enabled', [
            'type' => 'boolean',
            'default' => true,
            'sanitize_callback' => 'rest_sanitize_boolean'
        ]);
        register_setting('guard_dog_sessions_settings', 'guard_dog_sessions_max_per_user', [
            'type' => 'integer',
            'default' => 5,
            'sanitize_callback' => 'absint'
        ]);
        register_setting('guard_dog_sessions_settings', 'guard_dog_sessions_timeout_minutes', [
            'type' => 'integer',
            'default' => 60,
            'sanitize_callback' => 'absint'
        ]);
        register_setting('guard_dog_sessions_settings', 'guard_dog_sessions_detect_ip_shift', [
            'type' => 'boolean',
            'default' => true,
            'sanitize_callback' => 'rest_sanitize_boolean'
        ]);
        register_setting('guard_dog_sessions_settings', 'guard_dog_sessions_detect_geo_anomaly', [
            'type' => 'boolean',
            'default' => true,
            'sanitize_callback' => 'rest_sanitize_boolean'
        ]);
        register_setting('guard_dog_sessions_settings', 'guard_dog_sessions_notify_user', [
            'type' => 'boolean',
            'default' => false,
            'sanitize_callback' => 'rest_sanitize_boolean'
        ]);

        // IP Reputation settings (login-time and session-time)
        register_setting('guard_dog_sessions_settings', 'guard_dog_ip_reputation_login_enabled', [
            'type' => 'boolean',
            'default' => true,
            'sanitize_callback' => 'rest_sanitize_boolean'
        ]);
        register_setting('guard_dog_sessions_settings', 'guard_dog_ip_reputation_login_threshold', [
            'type' => 'integer',
            'default' => 80,
            'sanitize_callback' => function( $value ) {
                $value = absint( $value );
                return max( 0, min( 100, $value ) ); // Clamp to 0-100
            }
        ]);
        register_setting('guard_dog_sessions_settings', 'guard_dog_ip_reputation_session_enabled', [
            'type' => 'boolean',
            'default' => true,
            'sanitize_callback' => 'rest_sanitize_boolean'
        ]);
        register_setting('guard_dog_sessions_settings', 'guard_dog_ip_reputation_session_threshold', [
            'type' => 'integer',
            'default' => 90,
            'sanitize_callback' => function( $value ) {
                $value = absint( $value );
                return max( 0, min( 100, $value ) ); // Clamp to 0-100
            }
        ]);
        register_setting('guard_dog_sessions_settings', 'guard_dog_ipinfo_token', [
            'type' => 'string',
            'default' => '',
            'sanitize_callback' => function( $value ) {
                return is_string( $value ) ? sanitize_text_field( trim( $value ) ) : '';
            }
        ]);
        register_setting('guard_dog_sessions_settings', 'guard_dog_ip_reputation_disable_geo', [
            'type' => 'boolean',
            'default' => false,
            'sanitize_callback' => 'rest_sanitize_boolean'
        ]);

        // Reverse proxy / load balancer settings.
        register_setting( 'guard_dog_sessions_settings', 'guard_dog_ip_detection_method', array(
            'type'              => 'string',
            'default'           => 'auto',
            'sanitize_callback' => function ( $value ) {
                $allowed = array( 'auto', 'cloudflare', 'x_forwarded_for', 'x_real_ip', 'remote_addr' );
                return in_array( $value, $allowed, true ) ? $value : 'auto';
            },
        ) );
        register_setting( 'guard_dog_sessions_settings', 'guard_dog_trusted_proxy_ips', array(
            'type'              => 'string',
            'default'           => '',
            'sanitize_callback' => function ( $value ) {
                if ( ! is_string( $value ) ) {
                    return '';
                }
                $lines = explode( "\n", $value );
                $valid = array();
                foreach ( $lines as $line ) {
                    $line = trim( sanitize_text_field( $line ) );
                    if ( empty( $line ) ) {
                        continue;
                    }
                    if ( strpos( $line, '/' ) !== false ) {
                        list( $ip, $mask ) = explode( '/', $line, 2 );
                        if ( filter_var( $ip, FILTER_VALIDATE_IP ) && is_numeric( $mask ) ) {
                            $mask_int = (int) $mask;
                            $max_bits = filter_var( $ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 ) ? 32 : 128;
                            if ( $mask_int >= 0 && $mask_int <= $max_bits ) {
                                $valid[] = $line;
                            }
                        }
                    } elseif ( filter_var( $line, FILTER_VALIDATE_IP ) ) {
                        $valid[] = $line;
                    }
                }
                // Reset the cached proxy list so subsequent calls use the new value.
                if ( class_exists( 'Guard_Dog_Utils' ) && method_exists( 'Guard_Dog_Utils', 'reset_trusted_proxy_cache' ) ) {
                    Guard_Dog_Utils::reset_trusted_proxy_cache();
                }
                return implode( "\n", $valid );
            },
        ) );
    }

    /**
     * Register general settings
     */
    public function register_general_settings(): void {
        if (class_exists('Guard_Dog_Settings_Page')) {
            Guard_Dog_Settings_Page::register_settings();
        }
    }

    /**
     * Register activity log settings
     */
    public function register_activity_log_settings(): void {
        if (class_exists('Guard_Dog_Activity_Log_Page')) {
            Guard_Dog_Activity_Log_Page::register_settings();
        }
    }

    /**
     * Handle page actions
     */
    public function handle_page_actions(): void {
        // Handle database update action
        if (isset($_GET['guard_dog_action']) && sanitize_text_field(wp_unslash($_GET['guard_dog_action'])) === 'update_db') {
            if (current_user_can('manage_options') && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'] ?? '')), 'guard_dog_update_db')) {
                global $guard_dog_db;
                if (isset($guard_dog_db)) {
                    $guard_dog_db->force_update();
                    add_settings_error('guard_dog_admin', 'db_updated', __('Database tables updated successfully.', 'guard-dog'), 'updated');
                }
            }
        }

        // Handle other page-specific actions
        $current_page = $this->get_current_page_slug();

        switch ($current_page) {
            case self::AUTHENTICATION_SLUG:
                $this->handle_captcha_actions();
                $this->handle_login_security_actions();
                break;
            case self::USERS_SESSIONS_SLUG:
                $this->handle_temp_access_actions();
                break;
        }
    }

    /**
     * Get current page slug
     *
     * This method only reads the page parameter for navigation purposes,
     * not for processing form data. Nonce verification is not required here.
     */
    private function get_current_page_slug(): string {
        return sanitize_text_field(wp_unslash($_GET['page'] ?? ''));
    }

    /**
     * Show debug configuration warnings on Guard Dog admin pages
     */
    public function show_debug_warnings(): void {
        // Only show on Guard Dog pages
        $current_page = $this->get_current_page_slug();
        if (empty($current_page) || strpos($current_page, 'guard-dog') !== 0) {
            return;
        }

        // Get debug instance and check if warning should be shown
        if (class_exists('Guard_Dog_Debug')) {
            $debug = Guard_Dog_Debug::instance();
            
            if ($debug->should_show_debug_warning()) {
                $wordpress_status = $debug->get_wordpress_debug_status();
                ?>
                <div class="notice notice-warning is-dismissible">
                    <h4><?php esc_html_e('Guard Dog Debug Configuration Issue', 'guard-dog'); ?></h4>
                    <p>
                        <?php esc_html_e('Guard Dog debug logging is enabled, but WordPress debugging is not properly configured.', 'guard-dog'); ?>
                    </p>
                    <p>
                        <strong><?php esc_html_e('Current Status:', 'guard-dog'); ?></strong><br>
                        • WP_DEBUG: <?php echo wp_kses_post($wordpress_status['WP_DEBUG'] ? '<span class="guard-dog-status-enabled">Enabled</span>' : '<span class="guard-dog-status-disabled">Disabled</span>'); ?><br>
                        • WP_DEBUG_LOG: <?php echo wp_kses_post($wordpress_status['WP_DEBUG_LOG'] ? '<span class="guard-dog-status-enabled">Enabled</span>' : '<span class="guard-dog-status-disabled">Disabled</span>'); ?>
                    </p>
                    <?php if (!$wordpress_status['is_logging_enabled']): ?>
                    <p>
                        <strong><?php esc_html_e('To enable Guard Dog logging, add these lines to your wp-config.php file:', 'guard-dog'); ?></strong><br>
                        <code>define('WP_DEBUG', true);</code><br>
                        <code>define('WP_DEBUG_LOG', true);</code>
                    </p>
                    <p>
                        <?php printf(
                            // Translators: %s is the path to the debug log file.
                            esc_html__('Debug logs will be written to: %s', 'guard-dog'),
                            '<code>' . esc_html($wordpress_status['debug_log_path']) . '</code>'
                        ); ?>
                    </p>
                    <?php endif; ?>
                    <p>
                        <a href="<?php echo esc_url(admin_url('admin.php?page=' . self::SETTINGS_SLUG)); ?>" class="button button-secondary">
                            <?php esc_html_e('Manage Debug Settings', 'guard-dog'); ?>
                        </a>
                    </p>
                </div>
                <?php
            }
        }
    }

    /**
     * Page rendering methods — consolidated menu structure
     */
    public function render_dashboard_page(): void {
        if (class_exists('Guard_Dog_Dashboard_Page')) {
            $page = new Guard_Dog_Dashboard_Page($this->features);
            $page->render();
        }
    }

    public function render_authentication_page(): void {
        if (class_exists('Guard_Dog_Authentication_Page')) {
            $page = new Guard_Dog_Authentication_Page($this->features);
            $page->render();
        }
    }

    public function render_access_control_page(): void {
        if (class_exists('Guard_Dog_Access_Control_Page')) {
            $page = new Guard_Dog_Access_Control_Page($this->features);
            $page->render();
        }
    }

    public function render_users_sessions_page(): void {
        if (class_exists('Guard_Dog_Users_Sessions_Page')) {
            $temp_access_handler = $this->features['temp_access'] ?? null;
            $session_manager = $this->features['session_manager'] ?? null;
            $page = new Guard_Dog_Users_Sessions_Page($this->features, $temp_access_handler, $session_manager);
            $page->render();
        }
    }

    public function render_activity_log_page(): void {
        if (class_exists('Guard_Dog_Activity_Log_Page')) {
            $page = new Guard_Dog_Activity_Log_Page($this->features);
            $page->render();
        }
    }

    public function render_appearance_page(): void {
        if (class_exists('Guard_Dog_Appearance_Page')) {
            $page = new Guard_Dog_Appearance_Page($this->features);
            $page->render();
        }
    }

    public function render_settings_page(): void {
        if (class_exists('Guard_Dog_Settings_Page')) {
            $page = new Guard_Dog_Settings_Page($this->features);
            $page->render();
        }
    }

    /**
     * Setup activity log page screen options and hooks.
     *
     * @since 1.8.0
     */
    public function setup_activity_log_page(): void {
        $option = 'per_page';
        $args = [
            'label' => __('Activity Logs', 'guard-dog'),
            'default' => 20,
            'option' => 'guard_dog_activity_logs_per_page'
        ];
        add_screen_option($option, $args);
    }

    /**
     * Handle saving of screen options (generic filter).
     *
     * @since 1.8.0
     * @param mixed $screen_option Screen option value. Default false for non-standard options.
     * @param string $option The option name.
     * @param mixed $value The number of rows per page.
     * @return mixed Screen option value to save, or false to skip saving.
     */
    public function set_screen_option($screen_option, $option, $value) {
        // Handle the generic set-screen-option filter (for options ending with _page)
        if ($option === 'guard_dog_activity_logs_per_page') {
            $value = (int) $value;
            // Validate value range (WordPress standard is 1-999)
            if ($value < 1 || $value > 999) {
                return false; // Invalid value, skip saving
            }
            return $value;
        }
        
        return $screen_option;
    }

    /**
     * Handle saving of screen options (specific dynamic filter).
     *
     * This is called by the set_screen_option_{$option} filter.
     * WordPress passes: $screen_option (false), $option (option name), $value (the value to save)
     * We need to return the value to save, or false to skip saving.
     *
     * @since 1.8.0
     * @param mixed $screen_option Screen option value. Default false for non-standard options.
     * @param string $option The option name.
     * @param mixed $value The number of rows per page.
     * @return mixed Screen option value to save, or false to skip saving.
     */
    public function set_screen_option_specific($screen_option, $option, $value) {
        // This filter is specifically for guard_dog_activity_logs_per_page
        // Validate and return the value to save
        $value = (int) $value;
        // Validate value range (WordPress standard is 1-999)
        if ($value < 1 || $value > 999) {
            return false; // Invalid value, skip saving
        }
        // Return the validated value for WordPress to save
        return $value;
    }

    /**
     * Action handlers for each page
     */
    private function handle_captcha_actions(): void {
        // Register CAPTCHA settings
        if (class_exists('Guard_Dog_Captcha_Page')) {
            Guard_Dog_Captcha_Page::register_settings();
        }
    }

    private function handle_login_security_actions(): void {
        // Register login security settings
        if (class_exists('Guard_Dog_Login_Security_Page')) {
            Guard_Dog_Login_Security_Page::register_settings();
        }
    }

    private function handle_temp_access_actions(): void {
        // Handle temporary access actions
        if (class_exists('Guard_Dog_Temp_Access_Page')) {
            $page = new Guard_Dog_Temp_Access_Page($this->features['temp_access']);
            $page->register_settings();
        }
    }

    private function handle_settings_actions(): void {
        // Register general settings
        if (class_exists('Guard_Dog_Settings_Page')) {
            Guard_Dog_Settings_Page::register_settings();
        }
        
        // Settings page handles its own form actions internally
    }

    /**
     * Handle AJAX user search
     */
    public function handle_ajax_search_users(): void {
        // Fail early if nonce is missing or invalid - use WordPress recommended pattern
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'guard_dog_admin')) {
            wp_die('Security check failed');
        }

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('You do not have sufficient permissions', 'guard-dog')], 403);
        }

        $search_term = sanitize_text_field(wp_unslash($_POST['search'] ?? ''));
        
        if (strlen($search_term) < 2) {
            wp_send_json_error(['message' => __('Search term too short', 'guard-dog')]);
        }

        $users = get_users([
            'search' => "*{$search_term}*",
            'search_columns' => ['user_login', 'user_email', 'display_name'],
            'number' => 10,
            'fields' => ['ID', 'user_login', 'display_name', 'user_email']
        ]);

        $results = [];
        foreach ($users as $user) {
            $results[] = [
                'id' => $user->ID,
                'login' => $user->user_login,
                'display_name' => $user->display_name,
                'email' => $user->user_email,
                'label' => sprintf('%s (%s)', $user->display_name, $user->user_login)
            ];
        }

        wp_send_json_success($results);
    }

    /**
     * Handle AJAX user suggestions for access control
     */
    public function handle_ajax_get_user_suggestions(): void {
        // Fail early if nonce is missing or invalid - use WordPress recommended pattern
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'guard_dog_ajax')) {
            wp_die('Security check failed');
        }

        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('You do not have sufficient permissions', 'guard-dog')], 403);
        }

        $query = sanitize_text_field(wp_unslash($_POST['query'] ?? ''));
        
        if (strlen($query) < 2) {
            wp_send_json_error(['message' => __('Query too short', 'guard-dog')]);
        }

        $users = get_users([
            'search' => "*{$query}*",
            'search_columns' => ['user_login', 'display_name'],
            'number' => 10,
            'fields' => ['user_login', 'display_name']
        ]);

        $results = [];
        foreach ($users as $user) {
            $results[] = [
                'user_login' => $user->user_login,
                'display_name' => $user->display_name
            ];
        }

        wp_send_json_success($results);
    }

    /**
     * Handle AJAX force database update
     */
    public function handle_force_db_update(): void {
        // Fail early if nonce is missing or invalid - use WordPress recommended pattern
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'guard_dog_admin')) {
            wp_die('Security check failed');
        }

        if (!current_user_can('manage_options')) {
            wp_die('You do not have sufficient permissions to access this page.');
        }

        global $guard_dog_db;
        if (isset($guard_dog_db)) {
            $guard_dog_db->force_update();
            wp_send_json_success(['message' => __('Database tables updated successfully.', 'guard-dog')]);
        } else {
            wp_send_json_error(['message' => __('Guard Dog database class not found.', 'guard-dog')]);
        }
    }

    /**
     * Handle AJAX IP reputation check
     */
    public function handle_ajax_check_ip_reputation(): void {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'guard_dog_admin')) {
            wp_send_json_error(['message' => __('Security check failed', 'guard-dog')]);
        }

        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('You do not have sufficient permissions', 'guard-dog')]);
        }

        // Get IP address
        $ip_address = isset($_POST['ip_address']) ? sanitize_text_field(wp_unslash($_POST['ip_address'])) : '';
        
        if (empty($ip_address) || !filter_var($ip_address, FILTER_VALIDATE_IP)) {
            wp_send_json_error(['message' => __('Invalid IP address', 'guard-dog')]);
        }

        // Check reputation
        if (!isset(Guard_Dog()->features['ip_reputation'])) {
            wp_send_json_error(['message' => __('IP reputation checker not available', 'guard-dog')]);
        }

        $reputation_checker = Guard_Dog()->features['ip_reputation'];
        $result = $reputation_checker->check_ip_reputation($ip_address);

        if ($result['success']) {
            wp_send_json_success($result);
        } else {
            wp_send_json_error($result);
        }
    }

    /**
     * Handle AJAX add IP to blacklist
     */
    public function handle_ajax_add_ip_to_blacklist(): void {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'guard_dog_admin')) {
            wp_send_json_error(['message' => __('Security check failed', 'guard-dog')]);
            return;
        }

        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('You do not have sufficient permissions', 'guard-dog')]);
            return;
        }

        // Get IP address
        $ip_address = isset($_POST['ip_address']) ? sanitize_text_field(wp_unslash($_POST['ip_address'])) : '';
        
        if (empty($ip_address) || !filter_var($ip_address, FILTER_VALIDATE_IP)) {
            wp_send_json_error(['message' => __('Invalid IP address', 'guard-dog')]);
            return;
        }

        // Get expiration days (default 30)
        $expiration_days = isset($_POST['expiration_days']) ? absint($_POST['expiration_days']) : 30;
        
        // Get access control instance
        $access_control = Guard_Dog()->features['access_control'] ?? null;
        if (!$access_control) {
            wp_send_json_error(['message' => __('Access control feature is not available.', 'guard-dog')]);
            return;
        }

        // Check if IP is already in blacklist
        $active_blacklist = $access_control->get_active_blacklist();
        if (in_array($ip_address, $active_blacklist, true)) {
            wp_send_json_error(['message' => __('IP address is already in the blacklist', 'guard-dog')]);
            return;
        }

        // Determine source and reason
        $source = isset($_POST['source']) ? sanitize_text_field(wp_unslash($_POST['source'])) : 'manual';
        $reason = '';
        
        if ($source === 'ip_reputation_check' || isset($_POST['abuse_confidence'])) {
            // From IP reputation check modal
            $abuse_confidence = isset($_POST['abuse_confidence']) ? absint($_POST['abuse_confidence']) : 0;
            $reason = sprintf(
            		// Translators: %d is abuse confidence score.
					__('Added via IP reputation check (confidence: %d%%)', 'guard-dog'), $abuse_confidence);
            $source = 'ip_reputation_check';
        } else {
            // Manual addition from admin page
            $reason = isset($_POST['reason']) ? sanitize_text_field(wp_unslash($_POST['reason'])) : __('Manually added to blacklist', 'guard-dog');
            $source = 'manual';
        }
        
        try {
            $success = $access_control->add_ip_to_blacklist($ip_address, $expiration_days, $reason, $source);
        } catch (Exception $e) {
            if (Guard_Dog()->debug && Guard_Dog()->debug->is_enabled()) {
                Guard_Dog()->debug->error('Add IP to blacklist: Exception: ' . $e->getMessage());
            }
            wp_send_json_error(['message' => __('Error adding IP to blacklist: ', 'guard-dog') . $e->getMessage()]);
            return;
        }

        if (!$success) {
            wp_send_json_error(['message' => __('Failed to add IP address to blacklist.', 'guard-dog')]);
            return;
        }

        // Log the action
        if (Guard_Dog()->activity_log) {
            Guard_Dog()->activity_log->add_log_entry('ip_added_to_blacklist', [
                'ip_address' => $ip_address,
                'details' => [
                    'expiration_days' => $expiration_days,
                    'source' => $source,
                    'reason' => $reason,
                ]
            ]);
        }

        $expiration_message = $expiration_days > 0 
            ? sprintf(
	        		// Translators: %d is the number of blacklist days remaining.
					__(' for %d days', 'guard-dog'), $expiration_days)
            : __(' permanently', 'guard-dog');

        wp_send_json_success([
            // Translators: %1$s is the IP address, %2$s is the expiration message.
            'message' => sprintf(__('IP address %1$s has been added to the blacklist%2$s.', 'guard-dog'), $ip_address, $expiration_message),
            'ip_address' => $ip_address,
        ]);
    }

    /**
     * Handle AJAX request to remove IP from blacklist
     *
     * @since 1.8.45
     * @return void
     */
    public function handle_ajax_remove_ip_from_blacklist(): void {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'guard_dog_admin')) {
            wp_send_json_error(['message' => __('Security check failed', 'guard-dog')]);
            return;
        }

        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('You do not have sufficient permissions', 'guard-dog')]);
            return;
        }

        // Get IP address
        $ip_address = isset($_POST['ip_address']) ? sanitize_text_field(wp_unslash($_POST['ip_address'])) : '';
        
        if (empty($ip_address) || !filter_var($ip_address, FILTER_VALIDATE_IP)) {
            wp_send_json_error(['message' => __('Invalid IP address', 'guard-dog')]);
            return;
        }

        // Get access control instance
        $access_control = Guard_Dog()->features['access_control'] ?? null;
        if (!$access_control) {
            wp_send_json_error(['message' => __('Access control feature is not available.', 'guard-dog')]);
            return;
        }

        // Remove IP from blacklist
        $success = $access_control->remove_ip_from_blacklist($ip_address);

        if (!$success) {
            wp_send_json_error(['message' => __('Failed to remove IP address from blacklist.', 'guard-dog')]);
            return;
        }

        // Log the action
        if (Guard_Dog()->activity_log) {
            Guard_Dog()->activity_log->add_log_entry('ip_removed_from_blacklist', [
                'ip_address' => $ip_address,
                'details' => []
            ]);
        }

        wp_send_json_success([
            // Translators: %s is the IP address.
            'message' => sprintf(__('IP address %s has been removed from the blacklist.', 'guard-dog'), $ip_address),
            'ip_address' => $ip_address,
        ]);
    }

    /**
     * Handle AJAX request to add country to blacklist
     *
     * @since 1.8.48
     * @return void
     */
    public function handle_ajax_add_country_to_blacklist(): void {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'guard_dog_admin')) {
            wp_send_json_error(['message' => __('Security check failed', 'guard-dog')]);
            return;
        }

        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('You do not have sufficient permissions', 'guard-dog')]);
            return;
        }

        // Get country code
        $country_code = isset($_POST['country_code']) ? strtoupper(trim(sanitize_text_field(wp_unslash($_POST['country_code'])))) : '';
        
        // Validate country code (ISO 3166-1 alpha-2)
        if (empty($country_code) || strlen($country_code) !== 2 || !ctype_alpha($country_code)) {
            wp_send_json_error(['message' => __('Invalid country code. Please use ISO 3166-1 alpha-2 format (e.g., CN, SG).', 'guard-dog')]);
            return;
        }

        // Get expiration days
        $expiration_days = isset($_POST['expiration_days']) ? absint($_POST['expiration_days']) : 0;
        
        // Get reason
        $reason = isset($_POST['reason']) ? sanitize_text_field(wp_unslash($_POST['reason'])) : '';
        $source = isset($_POST['source']) ? sanitize_text_field(wp_unslash($_POST['source'])) : 'manual';

        // Get access control instance
        $access_control = Guard_Dog()->features['access_control'] ?? null;
        if (!$access_control) {
            wp_send_json_error(['message' => __('Access control feature is not available.', 'guard-dog')]);
            return;
        }

        try {
            $success = $access_control->add_country_to_blacklist($country_code, $expiration_days, $reason, $source);
        } catch (Exception $e) {
            if (Guard_Dog()->debug && Guard_Dog()->debug->is_enabled()) {
                Guard_Dog()->debug->error('Add country to blacklist: Exception: ' . $e->getMessage());
            }
            wp_send_json_error(['message' => __('Error adding country to blacklist: ', 'guard-dog') . $e->getMessage()]);
            return;
        }

        if (!$success) {
            wp_send_json_error(['message' => __('Failed to add country to blacklist.', 'guard-dog')]);
            return;
        }

        // Log the action
        if (Guard_Dog()->activity_log) {
            Guard_Dog()->activity_log->add_log_entry('country_added_to_blacklist', [
                'country_code' => $country_code,
                'details' => [
                    'expiration_days' => $expiration_days,
                    'source' => $source,
                    'reason' => $reason,
                ]
            ]);
        }

        $expiration_message = $expiration_days > 0 
            ? sprintf(
                // Translators: %d is the number of days.
                __(' for %d days', 'guard-dog'), $expiration_days)
            : __(' permanently', 'guard-dog');

        wp_send_json_success([
            // Translators: %1$s is the country code, %2$s is the expiration message.
            'message' => sprintf(__('Country %1$s has been added to the blacklist%2$s.', 'guard-dog'), $country_code, $expiration_message),
            'country_code' => $country_code,
        ]);
    }

    /**
     * Handle AJAX request to remove country from blacklist
     *
     * @since 1.8.48
     * @return void
     */
    public function handle_ajax_remove_country_from_blacklist(): void {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'guard_dog_admin')) {
            wp_send_json_error(['message' => __('Security check failed', 'guard-dog')]);
            return;
        }

        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('You do not have sufficient permissions', 'guard-dog')]);
            return;
        }

        // Get country code
        $country_code = isset($_POST['country_code']) ? strtoupper(trim(sanitize_text_field(wp_unslash($_POST['country_code'])))) : '';
        
        if (empty($country_code) || strlen($country_code) !== 2 || !ctype_alpha($country_code)) {
            wp_send_json_error(['message' => __('Invalid country code', 'guard-dog')]);
            return;
        }

        // Get access control instance
        $access_control = Guard_Dog()->features['access_control'] ?? null;
        if (!$access_control) {
            wp_send_json_error(['message' => __('Access control feature is not available.', 'guard-dog')]);
            return;
        }

        // Remove country from blacklist
        $success = $access_control->remove_country_from_blacklist($country_code);

        if (!$success) {
            wp_send_json_error(['message' => __('Failed to remove country from blacklist.', 'guard-dog')]);
            return;
        }

        // Log the action
        if (Guard_Dog()->activity_log) {
            Guard_Dog()->activity_log->add_log_entry('country_removed_from_blacklist', [
                'country_code' => $country_code,
                'details' => []
            ]);
        }

        wp_send_json_success([
            // Translators: %s is the country code.
            'message' => sprintf(__('Country %s has been removed from the blacklist.', 'guard-dog'), $country_code),
            'country_code' => $country_code,
        ]);
    }

    /**
     * Get client IP address.
     *
     * Delegates to Guard_Dog_Utils for centralized, proxy-aware IP detection.
     *
     * @since 1.9.33 Consolidated to use Guard_Dog_Utils::get_client_ip().
     * @return string The client IP address.
     */
    private function get_client_ip(): string {
        if ( class_exists( 'Guard_Dog_Utils' ) && method_exists( 'Guard_Dog_Utils', 'get_client_ip' ) ) {
            $ip = Guard_Dog_Utils::get_client_ip();
            if ( $ip ) {
                return $ip;
            }
        }

        return isset( $_SERVER['REMOTE_ADDR'] )
            ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) )
            : '0.0.0.0';
    }

    /**
     * Handle AJAX trigger expiration check
     *
     * @since 1.9.1
     */
    public function handle_ajax_trigger_expiration_check(): void {
        // Verify nonce
        if (!isset($_POST['nonce']) || !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['nonce'])), 'guard_dog_admin')) {
            wp_send_json_error(['message' => __('Security check failed', 'guard-dog')]);
            return;
        }

        // Check permissions
        if (!current_user_can('manage_options')) {
            wp_send_json_error(['message' => __('You do not have sufficient permissions', 'guard-dog')]);
            return;
        }

        // Get password policy feature
        $password_policy = Guard_Dog()->features['password_policy'] ?? null;
        if (!$password_policy) {
            wp_send_json_error(['message' => __('Password policy feature not available', 'guard-dog')]);
            return;
        }

        // Trigger the check
        $results = $password_policy->manual_trigger_expiration_check();

        if ($results['triggered']) {
            wp_send_json_success($results);
        } else {
            wp_send_json_error([
                'message' => implode(', ', $results['errors']),
            ]);
        }
    }
} 
