<?php

/**
 * Guard Dog Access Control Page
 *
 * @package GuardDog
 * @since 1.6.0
 */

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

class Guard_Dog_Access_Control_Page {

    private $features;

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

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

    public function __construct(array $features = []) {
        $this->features = $features;
        $this->initialize_tabs();
        $this->determine_current_tab();
        $this->register_settings();
    }

    /**
     * Initialize tabs configuration
     */
    private function initialize_tabs(): void {
        $this->tabs = [
            'site_wide' => [
                'label' => __('Site-Wide Access Control', 'guard-dog'),
                'icon' => 'dashicons-shield-alt',
            ],
            'ip_management' => [
                'label' => __('IP Address Management', 'guard-dog'),
                'icon' => 'dashicons-networking',
            ],
            'country_management' => [
                'label' => __('Country Management', 'guard-dog'),
                'icon' => 'dashicons-admin-site-alt3',
            ],
            'user_management' => [
                'label' => __('User Management', 'guard-dog'),
                'icon' => 'dashicons-admin-users',
            ],
            'user_enumeration' => [
                'label' => __('User Enumeration', 'guard-dog'),
                'icon' => 'dashicons-hidden',
            ],
        ];
    }

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

        // 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_access_control_tab')) {
            $tab_param = sanitize_text_field(wp_unslash($_GET['tab']));
            if (array_key_exists($tab_param, $this->tabs)) {
                $this->current_tab = $tab_param;
            }
        }
    }

    public function render(): void {
        ?>
        <div class="wrap guard-dog-admin">
            <h1 class="guard-dog-page-title">
                <span class="dashicons dashicons-groups"></span>
                <?php esc_html_e('Access Control', 'guard-dog'); ?>
            </h1>

            <p class="guard-dog-page-subtitle">
                <?php esc_html_e('Manage IP address access control and user restrictions to secure your WordPress site.', 'guard-dog'); ?>
            </p>

            <?php
            // Display settings messages (success/error notifications)
            settings_errors('guard_dog_site_wide_settings');
            settings_errors('guard_dog_ip_management_settings');
            settings_errors('guard_dog_country_management_settings');
            settings_errors('guard_dog_user_management_settings');
            settings_errors('guard_dog_user_enumeration_settings');
            ?>

            <div class="guard-dog-admin-grid">
                <div class="guard-dog-main-content">
                    <!-- 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_access_control_tab')])); ?>"
                                   class="guard-dog-tab-link<?php echo esc_attr($this->current_tab === $tab_id ? ' active' : ''); ?>"
                                   data-tab="<?php echo esc_attr($tab_id); ?>">
                                    <?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 $this->render_all_tab_panels(); ?>
                        </div>
                    </div>
                </div>

                <div class="guard-dog-sidebar">
                    <?php $this->render_access_control_help(); ?>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Render all tab panels with proper wrapper structure
     */
    private function render_all_tab_panels(): void {
        foreach ($this->tabs as $tab_id => $tab_config) {
            $is_active = $this->current_tab === $tab_id;
            $active_class = $is_active ? ' active' : '';
            ?>
            <div id="<?php echo esc_attr($tab_id); ?>" class="guard-dog-tab-panel<?php echo esc_attr($active_class); ?>">
                <?php
                switch ($tab_id) {
                    case 'site_wide':
                        $this->render_site_wide_tab();
                        break;
                    case 'ip_management':
                        $this->render_ip_management_tab();
                        break;
                    case 'country_management':
                        $this->render_country_management_tab();
                        break;
                    case 'user_management':
                        $this->render_user_management_tab();
                        break;
                    case 'user_enumeration':
                        $this->render_user_enumeration_tab();
                        break;
                }
                ?>
            </div>
            <?php
        }
    }

    /**
     * Render Site-Wide Access Control tab
     */
    private function render_site_wide_tab(): void {
        ?>
        <h3>
            <span class="dashicons dashicons-shield-alt"></span>
            <?php esc_html_e('Site-Wide Access Control', 'guard-dog'); ?>
        </h3>

        <p><?php esc_html_e('Configure global access control settings for your entire site.', 'guard-dog'); ?></p>

        <form method="post" action="options.php" class="guard-dog-site-wide-form">
            <?php
            settings_fields('guard_dog_site_wide_settings');
            do_settings_sections('guard_dog_site_wide_settings');
            ?>
            <?php
            $site_wide_ip_whitelist = class_exists('Guard_Dog_Access_Control')
                ? Guard_Dog_Access_Control::sanitize_ip_whitelist(get_option('guard_dog_ip_whitelist', ''))
                : get_option('guard_dog_ip_whitelist', '');
            ?>
            <textarea name="guard_dog_ip_whitelist"
                      id="guard-dog-site-wide-ip-whitelist"
                      class="guard-dog-hidden-field"
                      aria-hidden="true"
                      hidden><?php echo esc_textarea($site_wide_ip_whitelist); ?></textarea>

            <div class="guard-dog-security-notice">
                <h4>⚠️ <?php esc_html_e('Important Security Notice', 'guard-dog'); ?></h4>
                <ul>
                    <li><?php esc_html_e('Site-wide blocking will prevent access to ALL pages including login and admin', 'guard-dog'); ?></li>
                    <li><?php esc_html_e('Make sure your current IP is in the whitelist before enabling this feature', 'guard-dog'); ?></li>
                    <li><?php esc_html_e('Keep emergency access methods available (FTP, hosting panel)', 'guard-dog'); ?></li>
                    <li><?php esc_html_e('Test access control changes carefully to avoid locking yourself out', 'guard-dog'); ?></li>
                </ul>
            </div>

            <?php submit_button(__('Save Site-Wide Settings', 'guard-dog'), 'primary', 'submit', false, ['id' => 'submit-site-wide']); ?>
        </form>
        <?php
    }

    /**
     * Render IP Address Management tab
     */
    private function render_ip_management_tab(): void {
        ?>
        <h3>
            <span class="dashicons dashicons-networking"></span>
            <?php esc_html_e('IP Address Management', 'guard-dog'); ?>
        </h3>

        <p><?php esc_html_e('Control which IP addresses can access your site. Supports IPv4, IPv6, and CIDR notation.', 'guard-dog'); ?></p>

        <form method="post" action="options.php" class="guard-dog-ip-management-form">
            <?php
            settings_fields('guard_dog_ip_management_settings');
            do_settings_sections('guard_dog_ip_management_settings');
            ?>

            <div class="guard-dog-info-box">
                <h4><?php esc_html_e('Supported Formats', 'guard-dog'); ?></h4>
                <ul>
                    <li><strong>IPv4:</strong> <code>192.168.1.100</code></li>
                    <li><strong>IPv4 CIDR:</strong> <code>192.168.1.0/24</code> (entire subnet)</li>
                    <li><strong>IPv6:</strong> <code>2603:6011:2500:d354:a1e4:3762:561d:dc8e</code></li>
                    <li><strong>IPv6 CIDR:</strong> <code>2001:db8::/32</code> (entire subnet)</li>
                </ul>
            </div>

            <?php submit_button(__('Save IP Settings', 'guard-dog'), 'primary', 'submit', false, ['id' => 'submit-ip-management']); ?>
        </form>
        <?php
    }

    /**
     * Render Country Management tab
     */
    private function render_country_management_tab(): void {
        ?>
        <h3>
            <span class="dashicons dashicons-admin-site-alt3"></span>
            <?php esc_html_e('Country Management', 'guard-dog'); ?>
        </h3>

        <p><?php esc_html_e('Block access from specific countries based on IP geolocation. Supports expiration dates like IP blacklist.', 'guard-dog'); ?></p>

        <form method="post" action="options.php" class="guard-dog-country-management-form">
            <?php
            settings_fields('guard_dog_country_management_settings');
            do_settings_sections('guard_dog_country_management_settings');
            ?>

            <div class="guard-dog-info-box">
                <h4><?php esc_html_e('How It Works', 'guard-dog'); ?></h4>
                <ul>
                    <li><?php esc_html_e('Countries are identified using IP geolocation', 'guard-dog'); ?></li>
                    <li><strong><?php esc_html_e('Country Codes:', 'guard-dog'); ?></strong> <?php esc_html_e('Use ISO 3166-1 alpha-2 format (e.g., CN for China, SG for Singapore)', 'guard-dog'); ?></li>
                    <li><?php esc_html_e('Expired entries are automatically removed', 'guard-dog'); ?></li>
                    <li><?php esc_html_e('Country detection is cached for 24 hours to minimize API calls', 'guard-dog'); ?></li>
                </ul>
            </div>

            <?php submit_button(__('Save Country Settings', 'guard-dog'), 'primary', 'submit', false, ['id' => 'submit-country-management']); ?>
        </form>
        <?php
    }

    /**
     * Render User Management tab
     */
    private function render_user_management_tab(): void {
        ?>
        <h3>
            <span class="dashicons dashicons-admin-users"></span>
            <?php esc_html_e('User Management', 'guard-dog'); ?>
        </h3>

        <p><?php esc_html_e('Control which users can access your site based on their username.', 'guard-dog'); ?></p>

        <form method="post" action="options.php" class="guard-dog-user-management-form">
            <?php
            settings_fields('guard_dog_user_management_settings');
            do_settings_sections('guard_dog_user_management_settings');
            ?>

            <?php submit_button(__('Save User Settings', 'guard-dog'), 'primary', 'submit', false, ['id' => 'submit-user-management']); ?>
        </form>
        <?php
    }

    /**
     * Render User Enumeration Protection tab
     *
     * Moved from Login Security page. Protects against attacks that
     * try to discover valid usernames through various WordPress endpoints.
     */
    private function render_user_enumeration_tab(): void {
        $enum_enabled = get_option('guard_dog_enum_enabled', false);
        $bypass_roles = get_option('guard_dog_enum_bypass_roles', ['administrator']);
        $auto_block_enabled = get_option('guard_dog_enum_auto_block_enabled', true);
        $auto_block_threshold = get_option('guard_dog_enum_auto_block_threshold', 20);
        $auto_block_window = get_option('guard_dog_enum_auto_block_window', 60);
        $auto_block_duration = get_option('guard_dog_enum_auto_block_duration', 1440);

        $rest_api_block = get_option('guard_dog_enum_rest_api_block', true);
        $author_archives_block = get_option('guard_dog_enum_author_archives_block', true);
        $login_errors_block = get_option('guard_dog_enum_login_errors_block', true);
        $password_reset_block = get_option('guard_dog_enum_password_reset_block', true);
        $xmlrpc_block = get_option('guard_dog_enum_xmlrpc_block', true);
        $oembed_block = get_option('guard_dog_enum_oembed_block', true);
        $registration_block = get_option('guard_dog_enum_registration_block', true);

        $alert_immediate_enabled = get_option('guard_dog_enum_alert_immediate_enabled', false);
        $alert_immediate_threshold = get_option('guard_dog_enum_alert_immediate_threshold', 10);
        $alert_immediate_window = get_option('guard_dog_enum_alert_immediate_window', 5);
        $alert_immediate_email = get_option('guard_dog_enum_alert_immediate_email', get_option('admin_email'));
        $alert_digest_enabled = get_option('guard_dog_enum_alert_digest_enabled', false);
        $alert_digest_frequency = get_option('guard_dog_enum_alert_digest_frequency', 'weekly');
        $alert_digest_threshold = get_option('guard_dog_enum_alert_digest_threshold', 50);
        $alert_digest_email = get_option('guard_dog_enum_alert_digest_email', get_option('admin_email'));

        $wp_roles = wp_roles();
        $all_roles = $wp_roles->get_names();

        ?>
        <h3>
            <span class="dashicons dashicons-hidden"></span>
            <?php esc_html_e('User Enumeration Protection', 'guard-dog'); ?>
        </h3>

        <p><?php esc_html_e('Protect against attacks that try to discover valid usernames on your site through various WordPress endpoints and features.', 'guard-dog'); ?></p>

        <form method="post" action="options.php" class="guard-dog-settings-form">
            <?php settings_fields('guard_dog_user_enumeration_settings'); ?>

            <table class="guard-dog-form-table">
                <tr>
                    <th><?php esc_html_e('Enable Protection', 'guard-dog'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="guard_dog_enum_enabled" value="1" <?php checked($enum_enabled); ?> />
                            <?php esc_html_e('Enable user enumeration protection', 'guard-dog'); ?>
                        </label>
                        <p class="description"><?php esc_html_e('Block or log attempts to enumerate users through various WordPress endpoints.', 'guard-dog'); ?></p>
                    </td>
                </tr>
            </table>

            <h4><?php esc_html_e('Protection Vectors', 'guard-dog'); ?></h4>
            <p class="description"><?php esc_html_e('Checked vectors will be blocked. Unchecked vectors will still be logged but not blocked.', 'guard-dog'); ?></p>

            <table class="guard-dog-form-table">
                <tr>
                    <th><?php esc_html_e('REST API Users', 'guard-dog'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="guard_dog_enum_rest_api_block" value="1" <?php checked($rest_api_block); ?> />
                            <?php esc_html_e('Block /wp-json/wp/v2/users endpoint', 'guard-dog'); ?>
                        </label>
                        <p class="description"><?php esc_html_e('Prevents anonymous access to the REST API users endpoint.', 'guard-dog'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Author Archives', 'guard-dog'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="guard_dog_enum_author_archives_block" value="1" <?php checked($author_archives_block); ?> />
                            <?php esc_html_e('Block ?author=N enumeration', 'guard-dog'); ?>
                        </label>
                        <p class="description"><?php esc_html_e('Prevents sequential ID scanning via author archive URLs.', 'guard-dog'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Login Errors', 'guard-dog'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="guard_dog_enum_login_errors_block" value="1" <?php checked($login_errors_block); ?> />
                            <?php esc_html_e('Use generic "Invalid credentials" message', 'guard-dog'); ?>
                        </label>
                        <p class="description"><?php esc_html_e('Replaces revealing error messages like "Unknown username" with generic errors.', 'guard-dog'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Password Reset', 'guard-dog'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="guard_dog_enum_password_reset_block" value="1" <?php checked($password_reset_block); ?> />
                            <?php esc_html_e('Use generic "Check your email" message', 'guard-dog'); ?>
                        </label>
                        <p class="description"><?php esc_html_e('Shows the same message whether or not the email exists.', 'guard-dog'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th><?php esc_html_e('XML-RPC', 'guard-dog'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="guard_dog_enum_xmlrpc_block" value="1" <?php checked($xmlrpc_block); ?> />
                            <?php esc_html_e('Remove user enumeration methods', 'guard-dog'); ?>
                        </label>
                        <p class="description"><?php esc_html_e('Removes wp.getAuthors, wp.getUsers, wp.getUsersBlogs methods.', 'guard-dog'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th><?php esc_html_e('oEmbed', 'guard-dog'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="guard_dog_enum_oembed_block" value="1" <?php checked($oembed_block); ?> />
                            <?php esc_html_e('Strip author data from embeds', 'guard-dog'); ?>
                        </label>
                        <p class="description"><?php esc_html_e('Removes author_name and author_url from oEmbed responses.', 'guard-dog'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Registration', 'guard-dog'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="guard_dog_enum_registration_block" value="1" <?php checked($registration_block); ?> />
                            <?php esc_html_e('Use generic registration errors', 'guard-dog'); ?>
                        </label>
                        <p class="description"><?php esc_html_e('Hides "username exists" and "email exists" errors.', 'guard-dog'); ?></p>
                    </td>
                </tr>
            </table>

            <h4><?php esc_html_e('Bypass Settings', 'guard-dog'); ?></h4>

            <table class="guard-dog-form-table">
                <tr>
                    <th><?php esc_html_e('Bypass Roles', 'guard-dog'); ?></th>
                    <td>
                        <fieldset>
                            <?php foreach ($all_roles as $role_key => $role_name): ?>
                                <label style="display: inline-block; margin-right: 15px;">
                                    <input type="checkbox"
                                           name="guard_dog_enum_bypass_roles[]"
                                           value="<?php echo esc_attr($role_key); ?>"
                                           <?php checked(in_array($role_key, $bypass_roles, true)); ?> />
                                    <?php echo esc_html(translate_user_role($role_name)); ?>
                                </label>
                            <?php endforeach; ?>
                        </fieldset>
                        <p class="description"><?php esc_html_e('Users with these roles can access protected endpoints normally.', 'guard-dog'); ?></p>
                    </td>
                </tr>
            </table>

            <h4><?php esc_html_e('Auto-Block', 'guard-dog'); ?></h4>

            <table class="guard-dog-form-table">
                <tr>
                    <th><?php esc_html_e('Enable Auto-Block', 'guard-dog'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="guard_dog_enum_auto_block_enabled" value="1" <?php checked($auto_block_enabled); ?> />
                            <?php esc_html_e('Automatically block IPs after repeated attempts', 'guard-dog'); ?>
                        </label>
                    </td>
                </tr>
                <tr class="guard-dog-dependent-field">
                    <th><?php esc_html_e('Block Threshold', 'guard-dog'); ?></th>
                    <td>
                        <input type="number" name="guard_dog_enum_auto_block_threshold" value="<?php echo esc_attr($auto_block_threshold); ?>" min="5" max="100" class="small-text" />
                        <?php esc_html_e('attempts within', 'guard-dog'); ?>
                        <input type="number" name="guard_dog_enum_auto_block_window" value="<?php echo esc_attr($auto_block_window); ?>" min="5" max="1440" class="small-text" />
                        <?php esc_html_e('minutes', 'guard-dog'); ?>
                    </td>
                </tr>
                <tr class="guard-dog-dependent-field">
                    <th><?php esc_html_e('Block Duration', 'guard-dog'); ?></th>
                    <td>
                        <input type="number" name="guard_dog_enum_auto_block_duration" value="<?php echo esc_attr($auto_block_duration); ?>" min="15" max="10080" class="small-text" />
                        <?php esc_html_e('minutes', 'guard-dog'); ?>
                        <p class="description"><?php esc_html_e('How long to block the IP (1440 = 24 hours).', 'guard-dog'); ?></p>
                    </td>
                </tr>
            </table>

            <h4><?php esc_html_e('Notifications', 'guard-dog'); ?></h4>

            <table class="guard-dog-form-table">
                <tr>
                    <th><?php esc_html_e('Immediate Alerts', 'guard-dog'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="guard_dog_enum_alert_immediate_enabled" value="1" <?php checked($alert_immediate_enabled); ?> />
                            <?php esc_html_e('Send email alert when threshold reached', 'guard-dog'); ?>
                        </label>
                    </td>
                </tr>
                <tr class="guard-dog-dependent-field">
                    <th><?php esc_html_e('Alert Threshold', 'guard-dog'); ?></th>
                    <td>
                        <input type="number" name="guard_dog_enum_alert_immediate_threshold" value="<?php echo esc_attr($alert_immediate_threshold); ?>" min="3" max="100" class="small-text" />
                        <?php esc_html_e('attempts in', 'guard-dog'); ?>
                        <input type="number" name="guard_dog_enum_alert_immediate_window" value="<?php echo esc_attr($alert_immediate_window); ?>" min="1" max="60" class="small-text" />
                        <?php esc_html_e('minutes', 'guard-dog'); ?>
                    </td>
                </tr>
                <tr class="guard-dog-dependent-field">
                    <th><?php esc_html_e('Alert Email', 'guard-dog'); ?></th>
                    <td>
                        <input type="email" name="guard_dog_enum_alert_immediate_email" value="<?php echo esc_attr($alert_immediate_email); ?>" class="regular-text" />
                    </td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Digest Reports', 'guard-dog'); ?></th>
                    <td>
                        <label>
                            <input type="checkbox" name="guard_dog_enum_alert_digest_enabled" value="1" <?php checked($alert_digest_enabled); ?> />
                            <?php esc_html_e('Send periodic digest of enumeration activity', 'guard-dog'); ?>
                        </label>
                    </td>
                </tr>
                <tr class="guard-dog-dependent-field">
                    <th><?php esc_html_e('Digest Frequency', 'guard-dog'); ?></th>
                    <td>
                        <select name="guard_dog_enum_alert_digest_frequency">
                            <option value="daily" <?php selected($alert_digest_frequency, 'daily'); ?>><?php esc_html_e('Daily', 'guard-dog'); ?></option>
                            <option value="weekly" <?php selected($alert_digest_frequency, 'weekly'); ?>><?php esc_html_e('Weekly', 'guard-dog'); ?></option>
                            <option value="monthly" <?php selected($alert_digest_frequency, 'monthly'); ?>><?php esc_html_e('Monthly', 'guard-dog'); ?></option>
                        </select>
                    </td>
                </tr>
                <tr class="guard-dog-dependent-field">
                    <th><?php esc_html_e('Minimum Events', 'guard-dog'); ?></th>
                    <td>
                        <input type="number" name="guard_dog_enum_alert_digest_threshold" value="<?php echo esc_attr($alert_digest_threshold); ?>" min="1" max="1000" class="small-text" />
                        <p class="description"><?php esc_html_e('Only send digest if this many events occurred.', 'guard-dog'); ?></p>
                    </td>
                </tr>
                <tr class="guard-dog-dependent-field">
                    <th><?php esc_html_e('Digest Email', 'guard-dog'); ?></th>
                    <td>
                        <input type="email" name="guard_dog_enum_alert_digest_email" value="<?php echo esc_attr($alert_digest_email); ?>" class="regular-text" />
                    </td>
                </tr>
            </table>

            <?php submit_button(__('Save Enumeration Settings', 'guard-dog'), 'primary', 'submit', true, ['id' => 'submit-user-enumeration']); ?>
        </form>
        <?php
    }

    public static function register_settings(): void {
        // Register Site-Wide Access Control settings
        register_setting('guard_dog_site_wide_settings', 'guard_dog_site_wide_blocking', [
            'type' => 'boolean',
            'sanitize_callback' => function($input) {
                return !empty($input);
            },
            'default' => false,
        ]);

        register_setting('guard_dog_site_wide_settings', 'guard_dog_ip_whitelist', [
            'type' => 'string',
            'sanitize_callback' => function($input) {
                if (class_exists('Guard_Dog_Access_Control')) {
                    return Guard_Dog_Access_Control::sanitize_ip_whitelist($input);
                }

                return sanitize_textarea_field($input);
            },
            'default' => get_option('guard_dog_ip_whitelist', ''),
        ]);

        // Register IP Management settings
        register_setting('guard_dog_ip_management_settings', 'guard_dog_ip_blacklist', [
            'type' => 'array',
            'sanitize_callback' => function($input) {
                // If input is already an array (from AJAX/direct updates), return it as-is
                if (is_array($input)) {
                    return $input;
                }
                // Legacy support: if it's a string (textarea input), parse it
                if (is_string($input) && !empty($input)) {
                    $lines = array_filter(array_map('trim', explode("\n", $input)));
                    $blacklist = [];
                    foreach ($lines as $line) {
                        if (!empty($line)) {
                            $blacklist[] = $line; // Legacy format: simple string entries
                        }
                    }
                    return $blacklist;
                }
                // Empty input returns empty array
                return [];
            },
            'default' => [],
        ]);

        register_setting('guard_dog_ip_management_settings', 'guard_dog_ip_whitelist', [
            'type' => 'string',
            'sanitize_callback' => function($input) {
                if (class_exists('Guard_Dog_Access_Control')) {
                    return Guard_Dog_Access_Control::sanitize_ip_whitelist($input);
                }

                return sanitize_textarea_field($input);
            },
            'default' => '',
        ]);

        // Register User Management settings
        register_setting('guard_dog_user_management_settings', 'guard_dog_user_blacklist', [
            'type' => 'string',
            'sanitize_callback' => function($input) {
                // Extract only usernames from each entry (e.g., 'Adam Greenwell (test-guarddog-user)' => 'test-guarddog-user')
                $entries = preg_split('/,\s*/', $input);
                $usernames = array_filter(array_map(function($entry) {
                    if (preg_match('/\(([^)]+)\)$/', $entry, $matches)) {
                        return trim($matches[1]); // Username inside parentheses
                    }
                    return trim($entry); // Fallback: use as-is
                }, $entries));
                return implode(',', $usernames);
            },
            'default' => '',
        ]);

        register_setting('guard_dog_user_management_settings', 'guard_dog_user_whitelist', [
            'type' => 'string',
            'sanitize_callback' => function($input) {
                // Extract only usernames from each entry
                $entries = preg_split('/,\s*/', $input);
                $usernames = array_filter(array_map(function($entry) {
                    if (preg_match('/\(([^)]+)\)$/', $entry, $matches)) {
                        return trim($matches[1]); // Username inside parentheses
                    }
                    return trim($entry); // Fallback: use as-is
                }, $entries));
                return implode(',', $usernames);
            },
            'default' => '',
        ]);

        // Register Country Management settings
        register_setting('guard_dog_country_management_settings', 'guard_dog_country_blacklist', [
            'type' => 'array',
            'sanitize_callback' => function($input) {
                // If input is already an array (from AJAX/direct updates), return it as-is
                if (is_array($input)) {
                    return $input;
                }
                // If it's a string (from form submission, though we don't use that), return empty array
                return [];
            },
            'default' => [],
        ]);

        // Register User Enumeration settings (moved from Login Security)
        $enum_settings_group = 'guard_dog_user_enumeration_settings';

        register_setting($enum_settings_group, 'guard_dog_enum_enabled', [
            'type' => 'boolean',
            'sanitize_callback' => function ($input) { return !empty($input); },
            'default' => false,
        ]);
        register_setting($enum_settings_group, 'guard_dog_enum_bypass_roles', [
            'type' => 'array',
            'sanitize_callback' => function ($input) {
                return is_array($input) ? array_map('sanitize_text_field', $input) : ['administrator'];
            },
            'default' => ['administrator'],
        ]);
        register_setting($enum_settings_group, 'guard_dog_enum_auto_block_enabled', [
            'type' => 'boolean',
            'sanitize_callback' => function ($input) { return !empty($input); },
            'default' => true,
        ]);
        register_setting($enum_settings_group, 'guard_dog_enum_auto_block_threshold', [
            'type' => 'integer',
            'sanitize_callback' => 'absint',
            'default' => 20,
        ]);
        register_setting($enum_settings_group, 'guard_dog_enum_auto_block_window', [
            'type' => 'integer',
            'sanitize_callback' => 'absint',
            'default' => 60,
        ]);
        register_setting($enum_settings_group, 'guard_dog_enum_auto_block_duration', [
            'type' => 'integer',
            'sanitize_callback' => 'absint',
            'default' => 1440,
        ]);

        // Per-vector settings
        $enum_vectors = [
            'guard_dog_enum_rest_api_block',
            'guard_dog_enum_author_archives_block',
            'guard_dog_enum_login_errors_block',
            'guard_dog_enum_password_reset_block',
            'guard_dog_enum_xmlrpc_block',
            'guard_dog_enum_oembed_block',
            'guard_dog_enum_registration_block',
        ];
        foreach ($enum_vectors as $vector_option) {
            register_setting($enum_settings_group, $vector_option, [
                'type' => 'boolean',
                'sanitize_callback' => function ($input) { return !empty($input); },
                'default' => true,
            ]);
        }

        // Notification settings
        register_setting($enum_settings_group, 'guard_dog_enum_alert_immediate_enabled', [
            'type' => 'boolean',
            'sanitize_callback' => function ($input) { return !empty($input); },
            'default' => false,
        ]);
        register_setting($enum_settings_group, 'guard_dog_enum_alert_immediate_threshold', [
            'type' => 'integer',
            'sanitize_callback' => 'absint',
            'default' => 10,
        ]);
        register_setting($enum_settings_group, 'guard_dog_enum_alert_immediate_window', [
            'type' => 'integer',
            'sanitize_callback' => 'absint',
            'default' => 5,
        ]);
        register_setting($enum_settings_group, 'guard_dog_enum_alert_immediate_email', [
            'type' => 'string',
            'sanitize_callback' => 'sanitize_email',
            'default' => get_option('admin_email'),
        ]);
        register_setting($enum_settings_group, 'guard_dog_enum_alert_digest_enabled', [
            'type' => 'boolean',
            'sanitize_callback' => function ($input) { return !empty($input); },
            'default' => false,
        ]);
        register_setting($enum_settings_group, 'guard_dog_enum_alert_digest_frequency', [
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => 'weekly',
        ]);
        register_setting($enum_settings_group, 'guard_dog_enum_alert_digest_threshold', [
            'type' => 'integer',
            'sanitize_callback' => 'absint',
            'default' => 50,
        ]);
        register_setting($enum_settings_group, 'guard_dog_enum_alert_digest_email', [
            'type' => 'string',
            'sanitize_callback' => 'sanitize_email',
            'default' => get_option('admin_email'),
        ]);

        // Add settings sections and fields
        self::add_settings_sections();
    }

    /**
     * Add settings sections and fields
     */
    public static function add_settings_sections(): void {
        // Site-Wide Settings Section
        add_settings_section(
            'guard_dog_site_wide_section',
            '',
            '__return_empty_string',
            'guard_dog_site_wide_settings'
        );

        add_settings_field(
            'guard_dog_site_wide_blocking',
            __('Enable Site-Wide Blocking', 'guard-dog'),
            [self::class, 'render_site_wide_blocking_field'],
            'guard_dog_site_wide_settings',
            'guard_dog_site_wide_section'
        );

        add_settings_field(
            'guard_dog_access_denied_customizer_notice',
            __('Access Denied Page Customization', 'guard-dog'),
            [self::class, 'render_access_denied_customizer_notice'],
            'guard_dog_site_wide_settings',
            'guard_dog_site_wide_section'
        );

        // IP Management Settings Section
        add_settings_section(
            'guard_dog_ip_management_section',
            '',
            '__return_empty_string',
            'guard_dog_ip_management_settings'
        );

        add_settings_field(
            'guard_dog_ip_whitelist',
            __('IP Whitelist', 'guard-dog'),
            [self::class, 'render_ip_whitelist_field'],
            'guard_dog_ip_management_settings',
            'guard_dog_ip_management_section'
        );

        add_settings_field(
            'guard_dog_ip_blacklist',
            __('IP Blacklist', 'guard-dog'),
            [self::class, 'render_ip_blacklist_field'],
            'guard_dog_ip_management_settings',
            'guard_dog_ip_management_section'
        );

        // User Management Settings Section
        add_settings_section(
            'guard_dog_user_management_section',
            '',
            '__return_empty_string',
            'guard_dog_user_management_settings'
        );

        add_settings_field(
            'guard_dog_user_whitelist',
            __('Username Whitelist', 'guard-dog'),
            [self::class, 'render_user_whitelist_field'],
            'guard_dog_user_management_settings',
            'guard_dog_user_management_section'
        );

        add_settings_field(
            'guard_dog_user_blacklist',
            __('Username Blacklist', 'guard-dog'),
            [self::class, 'render_user_blacklist_field'],
            'guard_dog_user_management_settings',
            'guard_dog_user_management_section'
        );

        // Country Management Settings Section
        add_settings_section(
            'guard_dog_country_management_section',
            '',
            '__return_empty_string',
            'guard_dog_country_management_settings'
        );

        add_settings_field(
            'guard_dog_country_blacklist',
            __('Country Blacklist', 'guard-dog'),
            [self::class, 'render_country_blacklist_field'],
            'guard_dog_country_management_settings',
            'guard_dog_country_management_section'
        );
    }

    /**
     * Render field methods
     */
    public static function render_site_wide_blocking_field(): void {
        $site_wide_blocking = get_option('guard_dog_site_wide_blocking', false);
        ?>
        <label class="guard-dog-toggle">
            <input type="checkbox" name="guard_dog_site_wide_blocking" value="1" <?php checked($site_wide_blocking, true); ?>>
            <span class="guard-dog-toggle-slider"></span>
        </label>
        <p class="description">
            <?php esc_html_e('When enabled, only IPs in the whitelist can access ANY page on the site. This is perfect for staging/preview environments.', 'guard-dog'); ?>
        </p>
        <div class="guard-dog-warning">
            <strong>⚠️ <?php esc_html_e('Warning:', 'guard-dog'); ?></strong>
            <?php esc_html_e('Make sure your current IP is in the whitelist before enabling this feature to avoid locking yourself out!', 'guard-dog'); ?>
        </div>
        <?php
    }

    public static function render_access_denied_customizer_notice(): void {
        ?>
        <div class="guard-dog-info-box" style="max-width: 600px;">
            <p>
                <?php esc_html_e('Customize the appearance and content of the access denied page using the visual customizer.', 'guard-dog'); ?>
            </p>
            <p>
                <a href="<?php echo esc_url(admin_url('admin.php?page=guard-dog-access-denied-customizer')); ?>" class="button button-primary">
                    <span class="dashicons dashicons-admin-customizer"></span>
                    <?php esc_html_e('Customize Access Denied Page', 'guard-dog'); ?>
                </a>
            </p>
            <p class="description">
                <?php esc_html_e('The customizer allows you to configure colors, text, logo, and layout settings with a live preview.', 'guard-dog'); ?>
            </p>
        </div>
        <?php
    }

    public static function render_ip_whitelist_field(): void {
        $allowed_ips = get_option('guard_dog_ip_whitelist', '');
        $entries = class_exists('Guard_Dog_Access_Control')
            ? Guard_Dog_Access_Control::parse_ip_whitelist_entries($allowed_ips)
            : array_map(
                function($ip) {
                    return [
                        'ip'   => trim((string) $ip),
                        'note' => '',
                    ];
                },
                array_filter(array_map('trim', explode("\n", (string) $allowed_ips)))
            );
        $serialized_entries = class_exists('Guard_Dog_Access_Control')
            ? Guard_Dog_Access_Control::sanitize_ip_whitelist($allowed_ips)
            : sanitize_textarea_field($allowed_ips);
        ?>
        <div class="guard-dog-ip-whitelist-manager">
            <div class="guard-dog-add-ip-form guard-dog-add-whitelist-ip-form">
                <h4><?php esc_html_e('Add IP to Whitelist', 'guard-dog'); ?></h4>
                <table class="form-table">
                    <tr>
                        <th scope="row">
                            <label for="guard-dog-new-whitelist-ip-address"><?php esc_html_e('IP Address', 'guard-dog'); ?></label>
                        </th>
                        <td>
                            <input type="text" id="guard-dog-new-whitelist-ip-address" class="regular-text code" placeholder="192.168.1.100 or 192.168.1.0/24">
                            <p class="description"><?php esc_html_e('Supports IPv4, IPv6, and CIDR notation.', 'guard-dog'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="guard-dog-new-whitelist-ip-note"><?php esc_html_e('Note (optional)', 'guard-dog'); ?></label>
                        </th>
                        <td>
                            <input type="text" id="guard-dog-new-whitelist-ip-note" class="regular-text" placeholder="<?php esc_attr_e('e.g., Adam\'s House', 'guard-dog'); ?>">
                            <p class="description"><?php esc_html_e('Add a short label so you know who or what this IP belongs to later.', 'guard-dog'); ?></p>
                        </td>
                    </tr>
                </table>
                <p>
                    <button type="button" id="guard-dog-add-whitelist-ip-button" class="button button-primary"><?php esc_html_e('Add IP to Whitelist', 'guard-dog'); ?></button>
                    <span id="guard-dog-add-whitelist-ip-message" class="guard-dog-inline-message"></span>
                </p>
            </div>

            <div class="guard-dog-ip-whitelist-table-wrapper">
                <h4><?php esc_html_e('Current Whitelist', 'guard-dog'); ?></h4>
                <table class="wp-list-table widefat fixed striped" id="guard-dog-ip-whitelist-table">
                    <thead>
                        <tr>
                            <th style="width: 35%;"><?php esc_html_e('IP Address', 'guard-dog'); ?></th>
                            <th style="width: 45%;"><?php esc_html_e('Note', 'guard-dog'); ?></th>
                            <th style="width: 20%;"><?php esc_html_e('Actions', 'guard-dog'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($entries as $entry): ?>
                            <tr data-ip="<?php echo esc_attr($entry['ip'] ?? ''); ?>" data-note="<?php echo esc_attr($entry['note'] ?? ''); ?>">
                                <td><code><?php echo esc_html($entry['ip'] ?? ''); ?></code></td>
                                <td>
                                    <?php if (!empty($entry['note'])): ?>
                                        <?php echo esc_html($entry['note']); ?>
                                    <?php else: ?>
                                        <span class="guard-dog-muted-text"><?php esc_html_e('No note', 'guard-dog'); ?></span>
                                    <?php endif; ?>
                                </td>
                                <td>
                                    <button type="button" class="button button-small guard-dog-remove-whitelist-ip" data-ip="<?php echo esc_attr($entry['ip'] ?? ''); ?>">
                                        <?php esc_html_e('Remove', 'guard-dog'); ?>
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
                <p class="guard-dog-list-empty" <?php echo empty($entries) ? '' : 'hidden'; ?>>
                    <?php esc_html_e('No IP addresses are currently whitelisted.', 'guard-dog'); ?>
                </p>
            </div>
        </div>

        <textarea name="guard_dog_ip_whitelist" id="guard-dog-ip-whitelist-hidden" class="guard-dog-hidden-field" aria-hidden="true" hidden><?php echo esc_textarea($serialized_entries); ?></textarea>
        <p class="description">
            <?php esc_html_e('Always allow these IP addresses. This list has the highest priority and is required for site-wide blocking. Notes are saved for admin context only and do not affect matching.', 'guard-dog'); ?>
        </p>
        <?php
    }

    public static function render_ip_blacklist_field(): void {
        // Get access control instance to use structured blacklist methods
        $access_control = Guard_Dog()->features['access_control'] ?? null;
        $full_blacklist = $access_control ? $access_control->get_full_blacklist() : [];
        
        // Handle legacy text format for display
        $legacy_blacklist = get_option('guard_dog_ip_blacklist', '');
        if (is_string($legacy_blacklist) && !empty($legacy_blacklist) && empty($full_blacklist)) {
            // Show legacy format if migration hasn't happened yet
            ?>
            <textarea name="guard_dog_ip_blacklist" rows="8" class="large-text code" placeholder="192.168.1.100&#10;203.0.113.45&#10;198.51.100.0/24&#10;2603:6011:2500:d354:a1e4:3762:561d:dc8e&#10;2001:db8::/32"><?php echo esc_textarea($legacy_blacklist); ?></textarea>
            <p class="description">
                <?php esc_html_e('Block these IP addresses from accessing the site. One per line. Supports IPv4, IPv6, and CIDR notation.', 'guard-dog'); ?>
            </p>
            <?php
            return;
        }
        
        // Display structured blacklist with expiration support
        ?>
        <div class="guard-dog-ip-blacklist-manager">
            <div class="guard-dog-add-ip-form" style="margin-bottom: 20px; padding: 15px; background: #f9f9f9; border: 1px solid #ddd; border-radius: 4px;">
                <h4 style="margin-top: 0;"><?php esc_html_e('Add IP to Blacklist', 'guard-dog'); ?></h4>
                <table class="form-table" style="margin-bottom: 0;">
                    <tr>
                        <th scope="row">
                            <label for="guard-dog-new-ip-address"><?php esc_html_e('IP Address', 'guard-dog'); ?></label>
                        </th>
                        <td>
                            <input type="text" id="guard-dog-new-ip-address" class="regular-text code" placeholder="192.168.1.100 or 192.168.1.0/24">
                            <p class="description" style="margin-top: 5px;"><?php esc_html_e('Supports IPv4, IPv6, and CIDR notation.', 'guard-dog'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="guard-dog-new-ip-expiration"><?php esc_html_e('Expiration (days)', 'guard-dog'); ?></label>
                        </th>
                        <td>
                            <input type="number" id="guard-dog-new-ip-expiration" class="small-text" value="30" min="0" step="1">
                            <p class="description" style="margin-top: 5px;"><?php esc_html_e('Enter 0 for permanent blacklist. Default: 30 days.', 'guard-dog'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="guard-dog-new-ip-reason"><?php esc_html_e('Reason (optional)', 'guard-dog'); ?></label>
                        </th>
                        <td>
                            <input type="text" id="guard-dog-new-ip-reason" class="regular-text" placeholder="<?php esc_attr_e('e.g., Malicious activity detected', 'guard-dog'); ?>">
                        </td>
                    </tr>
                </table>
                <p>
                    <button type="button" id="guard-dog-add-ip-button" class="button button-primary"><?php esc_html_e('Add IP to Blacklist', 'guard-dog'); ?></button>
                    <span id="guard-dog-add-ip-message" style="margin-left: 10px;"></span>
                </p>
            </div>

            <div class="guard-dog-ip-blacklist-table-wrapper">
                <h4><?php esc_html_e('Current Blacklist', 'guard-dog'); ?></h4>
                <?php if (empty($full_blacklist)): ?>
                    <p><?php esc_html_e('No IP addresses are currently blacklisted.', 'guard-dog'); ?></p>
                <?php else: ?>
                    <table class="wp-list-table widefat fixed striped" id="guard-dog-ip-blacklist-table">
                        <thead>
                            <tr>
                                <th style="width: 25%;"><?php esc_html_e('IP Address', 'guard-dog'); ?></th>
                                <th style="width: 15%;"><?php esc_html_e('Expires', 'guard-dog'); ?></th>
                                <th style="width: 20%;"><?php esc_html_e('Added', 'guard-dog'); ?></th>
                                <th style="width: 25%;"><?php esc_html_e('Reason', 'guard-dog'); ?></th>
                                <th style="width: 15%;"><?php esc_html_e('Actions', 'guard-dog'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($full_blacklist as $entry): 
                                $ip = $entry['ip'] ?? '';
                                $expires_date = $entry['expires_date'] ?? null;
                                $added_date = $entry['added_date'] ?? null;
                                $reason = $entry['reason'] ?? '';
                                $source = $entry['source'] ?? 'manual';
                                
                                // Check if expired
                                $is_expired = false;
                                if ($expires_date && $expires_date !== '') {
                                    $is_expired = strtotime($expires_date) < time();
                                }
                                
                                $expires_display = $expires_date ? date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($expires_date)) : __('Permanent', 'guard-dog');
                                $added_display = $added_date ? date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($added_date)) : __('Unknown', 'guard-dog');
                            ?>
                                <tr class="<?php echo $is_expired ? 'expired' : ''; ?>">
                                    <td><code><?php echo esc_html($ip); ?></code></td>
                                    <td>
                                        <?php if ($is_expired): ?>
                                            <span style="color: #d63638;"><?php esc_html_e('Expired', 'guard-dog'); ?></span>
                                        <?php else: ?>
                                            <?php echo esc_html($expires_display); ?>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo esc_html($added_display); ?></td>
                                    <td><?php echo esc_html($reason); ?></td>
                                    <td>
                                        <button type="button" class="button button-small guard-dog-remove-ip" data-ip="<?php echo esc_attr($ip); ?>">
                                            <?php esc_html_e('Remove', 'guard-dog'); ?>
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Structured blacklist entries are managed through AJAX so saving IP settings does not overwrite them. -->
        <input type="hidden" id="guard-dog-ip-blacklist-hidden" value="">
        
        <p class="description">
            <?php esc_html_e('Block these IP addresses from accessing the site. Supports IPv4, IPv6, and CIDR notation. Expired entries are automatically removed.', 'guard-dog'); ?>
        </p>
        <?php
    }

    public static function render_user_whitelist_field(): void {
        $allowed_users = get_option('guard_dog_user_whitelist', '');
        ?>
        <div class="guard-dog-user-input-wrapper">
            <input type="text" id="guard-dog-username-whitelist-input" placeholder="<?php esc_attr_e('Type a username', 'guard-dog'); ?>" class="regular-text">
            <button type="button" class="button" id="guard-dog-add-whitelist-user"><?php esc_html_e('Add', 'guard-dog'); ?></button>
            <div id="guard-dog-username-whitelist-suggestions" class="suggestions"></div>
        </div>
        <div class="guard-dog-user-tags" id="guard-dog-username-whitelist-tags">
            <!-- Whitelisted users will be displayed here -->
        </div>
        <input type="hidden" name="guard_dog_user_whitelist" id="guard-dog-username-whitelist-hidden" value="<?php echo esc_attr($allowed_users); ?>">
        <p class="description">
            <?php esc_html_e('Always allow these usernames (if their IP is not blacklisted).', 'guard-dog'); ?>
        </p>
        <?php
    }

    public static function render_user_blacklist_field(): void {
        $blocked_users = get_option('guard_dog_user_blacklist', '');
        ?>
        <div class="guard-dog-user-input-wrapper">
            <input type="text" id="guard-dog-username-blacklist-input" placeholder="<?php esc_attr_e('Type a username', 'guard-dog'); ?>" class="regular-text">
            <button type="button" class="button" id="guard-dog-add-blacklist-user"><?php esc_html_e('Add', 'guard-dog'); ?></button>
            <div id="guard-dog-username-blacklist-suggestions" class="suggestions"></div>
        </div>
        <div class="guard-dog-user-tags" id="guard-dog-username-blacklist-tags">
            <!-- Blacklisted users will be displayed here -->
        </div>
        <input type="hidden" name="guard_dog_user_blacklist" id="guard-dog-username-blacklist-hidden" value="<?php echo esc_attr($blocked_users); ?>">
        <p class="description">
            <?php esc_html_e('Block these usernames from accessing the site.', 'guard-dog'); ?>
        </p>
        <?php
    }

    /**
     * Get comprehensive list of countries with ISO codes, names, and flag emojis
     *
     * @since 1.8.48
     * @return array Array of countries with 'code', 'name', and 'flag' keys
     */
    private static function get_countries_list(): array {
        return [
            ['code' => 'AF', 'name' => 'Afghanistan', 'flag' => '🇦🇫'],
            ['code' => 'AX', 'name' => 'Åland Islands', 'flag' => '🇦🇽'],
            ['code' => 'AL', 'name' => 'Albania', 'flag' => '🇦🇱'],
            ['code' => 'DZ', 'name' => 'Algeria', 'flag' => '🇩🇿'],
            ['code' => 'AS', 'name' => 'American Samoa', 'flag' => '🇦🇸'],
            ['code' => 'AD', 'name' => 'Andorra', 'flag' => '🇦🇩'],
            ['code' => 'AO', 'name' => 'Angola', 'flag' => '🇦🇴'],
            ['code' => 'AI', 'name' => 'Anguilla', 'flag' => '🇦🇮'],
            ['code' => 'AQ', 'name' => 'Antarctica', 'flag' => '🇦🇶'],
            ['code' => 'AG', 'name' => 'Antigua and Barbuda', 'flag' => '🇦🇬'],
            ['code' => 'AR', 'name' => 'Argentina', 'flag' => '🇦🇷'],
            ['code' => 'AM', 'name' => 'Armenia', 'flag' => '🇦🇲'],
            ['code' => 'AW', 'name' => 'Aruba', 'flag' => '🇦🇼'],
            ['code' => 'AU', 'name' => 'Australia', 'flag' => '🇦🇺'],
            ['code' => 'AT', 'name' => 'Austria', 'flag' => '🇦🇹'],
            ['code' => 'AZ', 'name' => 'Azerbaijan', 'flag' => '🇦🇿'],
            ['code' => 'BS', 'name' => 'Bahamas', 'flag' => '🇧🇸'],
            ['code' => 'BH', 'name' => 'Bahrain', 'flag' => '🇧🇭'],
            ['code' => 'BD', 'name' => 'Bangladesh', 'flag' => '🇧🇩'],
            ['code' => 'BB', 'name' => 'Barbados', 'flag' => '🇧🇧'],
            ['code' => 'BY', 'name' => 'Belarus', 'flag' => '🇧🇾'],
            ['code' => 'BE', 'name' => 'Belgium', 'flag' => '🇧🇪'],
            ['code' => 'BZ', 'name' => 'Belize', 'flag' => '🇧🇿'],
            ['code' => 'BJ', 'name' => 'Benin', 'flag' => '🇧🇯'],
            ['code' => 'BM', 'name' => 'Bermuda', 'flag' => '🇧🇲'],
            ['code' => 'BT', 'name' => 'Bhutan', 'flag' => '🇧🇹'],
            ['code' => 'BO', 'name' => 'Bolivia', 'flag' => '🇧🇴'],
            ['code' => 'BQ', 'name' => 'Bonaire, Sint Eustatius and Saba', 'flag' => '🇧🇶'],
            ['code' => 'BA', 'name' => 'Bosnia and Herzegovina', 'flag' => '🇧🇦'],
            ['code' => 'BW', 'name' => 'Botswana', 'flag' => '🇧🇼'],
            ['code' => 'BV', 'name' => 'Bouvet Island', 'flag' => '🇧🇻'],
            ['code' => 'BR', 'name' => 'Brazil', 'flag' => '🇧🇷'],
            ['code' => 'IO', 'name' => 'British Indian Ocean Territory', 'flag' => '🇮🇴'],
            ['code' => 'BN', 'name' => 'Brunei Darussalam', 'flag' => '🇧🇳'],
            ['code' => 'BG', 'name' => 'Bulgaria', 'flag' => '🇧🇬'],
            ['code' => 'BF', 'name' => 'Burkina Faso', 'flag' => '🇧🇫'],
            ['code' => 'BI', 'name' => 'Burundi', 'flag' => '🇧🇮'],
            ['code' => 'CV', 'name' => 'Cabo Verde', 'flag' => '🇨🇻'],
            ['code' => 'KH', 'name' => 'Cambodia', 'flag' => '🇰🇭'],
            ['code' => 'CM', 'name' => 'Cameroon', 'flag' => '🇨🇲'],
            ['code' => 'CA', 'name' => 'Canada', 'flag' => '🇨🇦'],
            ['code' => 'KY', 'name' => 'Cayman Islands', 'flag' => '🇰🇾'],
            ['code' => 'CF', 'name' => 'Central African Republic', 'flag' => '🇨🇫'],
            ['code' => 'TD', 'name' => 'Chad', 'flag' => '🇹🇩'],
            ['code' => 'CL', 'name' => 'Chile', 'flag' => '🇨🇱'],
            ['code' => 'CN', 'name' => 'China', 'flag' => '🇨🇳'],
            ['code' => 'CX', 'name' => 'Christmas Island', 'flag' => '🇨🇽'],
            ['code' => 'CC', 'name' => 'Cocos (Keeling) Islands', 'flag' => '🇨🇨'],
            ['code' => 'CO', 'name' => 'Colombia', 'flag' => '🇨🇴'],
            ['code' => 'KM', 'name' => 'Comoros', 'flag' => '🇰🇲'],
            ['code' => 'CG', 'name' => 'Congo', 'flag' => '🇨🇬'],
            ['code' => 'CD', 'name' => 'Congo, Democratic Republic of the', 'flag' => '🇨🇩'],
            ['code' => 'CK', 'name' => 'Cook Islands', 'flag' => '🇨🇰'],
            ['code' => 'CR', 'name' => 'Costa Rica', 'flag' => '🇨🇷'],
            ['code' => 'CI', 'name' => 'Côte d\'Ivoire', 'flag' => '🇨🇮'],
            ['code' => 'HR', 'name' => 'Croatia', 'flag' => '🇭🇷'],
            ['code' => 'CU', 'name' => 'Cuba', 'flag' => '🇨🇺'],
            ['code' => 'CW', 'name' => 'Curaçao', 'flag' => '🇨🇼'],
            ['code' => 'CY', 'name' => 'Cyprus', 'flag' => '🇨🇾'],
            ['code' => 'CZ', 'name' => 'Czechia', 'flag' => '🇨🇿'],
            ['code' => 'DK', 'name' => 'Denmark', 'flag' => '🇩🇰'],
            ['code' => 'DJ', 'name' => 'Djibouti', 'flag' => '🇩🇯'],
            ['code' => 'DM', 'name' => 'Dominica', 'flag' => '🇩🇲'],
            ['code' => 'DO', 'name' => 'Dominican Republic', 'flag' => '🇩🇴'],
            ['code' => 'EC', 'name' => 'Ecuador', 'flag' => '🇪🇨'],
            ['code' => 'EG', 'name' => 'Egypt', 'flag' => '🇪🇬'],
            ['code' => 'SV', 'name' => 'El Salvador', 'flag' => '🇸🇻'],
            ['code' => 'GQ', 'name' => 'Equatorial Guinea', 'flag' => '🇬🇶'],
            ['code' => 'ER', 'name' => 'Eritrea', 'flag' => '🇪🇷'],
            ['code' => 'EE', 'name' => 'Estonia', 'flag' => '🇪🇪'],
            ['code' => 'SZ', 'name' => 'Eswatini', 'flag' => '🇸🇿'],
            ['code' => 'ET', 'name' => 'Ethiopia', 'flag' => '🇪🇹'],
            ['code' => 'FK', 'name' => 'Falkland Islands (Malvinas)', 'flag' => '🇫🇰'],
            ['code' => 'FO', 'name' => 'Faroe Islands', 'flag' => '🇫🇴'],
            ['code' => 'FJ', 'name' => 'Fiji', 'flag' => '🇫🇯'],
            ['code' => 'FI', 'name' => 'Finland', 'flag' => '🇫🇮'],
            ['code' => 'FR', 'name' => 'France', 'flag' => '🇫🇷'],
            ['code' => 'GF', 'name' => 'French Guiana', 'flag' => '🇬🇫'],
            ['code' => 'PF', 'name' => 'French Polynesia', 'flag' => '🇵🇫'],
            ['code' => 'TF', 'name' => 'French Southern Territories', 'flag' => '🇹🇫'],
            ['code' => 'GA', 'name' => 'Gabon', 'flag' => '🇬🇦'],
            ['code' => 'GM', 'name' => 'Gambia', 'flag' => '🇬🇲'],
            ['code' => 'GE', 'name' => 'Georgia', 'flag' => '🇬🇪'],
            ['code' => 'DE', 'name' => 'Germany', 'flag' => '🇩🇪'],
            ['code' => 'GH', 'name' => 'Ghana', 'flag' => '🇬🇭'],
            ['code' => 'GI', 'name' => 'Gibraltar', 'flag' => '🇬🇮'],
            ['code' => 'GR', 'name' => 'Greece', 'flag' => '🇬🇷'],
            ['code' => 'GL', 'name' => 'Greenland', 'flag' => '🇬🇱'],
            ['code' => 'GD', 'name' => 'Grenada', 'flag' => '🇬🇩'],
            ['code' => 'GP', 'name' => 'Guadeloupe', 'flag' => '🇬🇵'],
            ['code' => 'GU', 'name' => 'Guam', 'flag' => '🇬🇺'],
            ['code' => 'GT', 'name' => 'Guatemala', 'flag' => '🇬🇹'],
            ['code' => 'GG', 'name' => 'Guernsey', 'flag' => '🇬🇬'],
            ['code' => 'GN', 'name' => 'Guinea', 'flag' => '🇬🇳'],
            ['code' => 'GW', 'name' => 'Guinea-Bissau', 'flag' => '🇬🇼'],
            ['code' => 'GY', 'name' => 'Guyana', 'flag' => '🇬🇾'],
            ['code' => 'HT', 'name' => 'Haiti', 'flag' => '🇭🇹'],
            ['code' => 'HM', 'name' => 'Heard Island and McDonald Islands', 'flag' => '🇭🇲'],
            ['code' => 'VA', 'name' => 'Holy See', 'flag' => '🇻🇦'],
            ['code' => 'HN', 'name' => 'Honduras', 'flag' => '🇭🇳'],
            ['code' => 'HK', 'name' => 'Hong Kong', 'flag' => '🇭🇰'],
            ['code' => 'HU', 'name' => 'Hungary', 'flag' => '🇭🇺'],
            ['code' => 'IS', 'name' => 'Iceland', 'flag' => '🇮🇸'],
            ['code' => 'IN', 'name' => 'India', 'flag' => '🇮🇳'],
            ['code' => 'ID', 'name' => 'Indonesia', 'flag' => '🇮🇩'],
            ['code' => 'IR', 'name' => 'Iran', 'flag' => '🇮🇷'],
            ['code' => 'IQ', 'name' => 'Iraq', 'flag' => '🇮🇶'],
            ['code' => 'IE', 'name' => 'Ireland', 'flag' => '🇮🇪'],
            ['code' => 'IM', 'name' => 'Isle of Man', 'flag' => '🇮🇲'],
            ['code' => 'IL', 'name' => 'Israel', 'flag' => '🇮🇱'],
            ['code' => 'IT', 'name' => 'Italy', 'flag' => '🇮🇹'],
            ['code' => 'JM', 'name' => 'Jamaica', 'flag' => '🇯🇲'],
            ['code' => 'JP', 'name' => 'Japan', 'flag' => '🇯🇵'],
            ['code' => 'JE', 'name' => 'Jersey', 'flag' => '🇯🇪'],
            ['code' => 'JO', 'name' => 'Jordan', 'flag' => '🇯🇴'],
            ['code' => 'KZ', 'name' => 'Kazakhstan', 'flag' => '🇰🇿'],
            ['code' => 'KE', 'name' => 'Kenya', 'flag' => '🇰🇪'],
            ['code' => 'KI', 'name' => 'Kiribati', 'flag' => '🇰🇮'],
            ['code' => 'KP', 'name' => 'Korea, Democratic People\'s Republic of', 'flag' => '🇰🇵'],
            ['code' => 'KR', 'name' => 'Korea, Republic of', 'flag' => '🇰🇷'],
            ['code' => 'KW', 'name' => 'Kuwait', 'flag' => '🇰🇼'],
            ['code' => 'KG', 'name' => 'Kyrgyzstan', 'flag' => '🇰🇬'],
            ['code' => 'LA', 'name' => 'Lao People\'s Democratic Republic', 'flag' => '🇱🇦'],
            ['code' => 'LV', 'name' => 'Latvia', 'flag' => '🇱🇻'],
            ['code' => 'LB', 'name' => 'Lebanon', 'flag' => '🇱🇧'],
            ['code' => 'LS', 'name' => 'Lesotho', 'flag' => '🇱🇸'],
            ['code' => 'LR', 'name' => 'Liberia', 'flag' => '🇱🇷'],
            ['code' => 'LY', 'name' => 'Libya', 'flag' => '🇱🇾'],
            ['code' => 'LI', 'name' => 'Liechtenstein', 'flag' => '🇱🇮'],
            ['code' => 'LT', 'name' => 'Lithuania', 'flag' => '🇱🇹'],
            ['code' => 'LU', 'name' => 'Luxembourg', 'flag' => '🇱🇺'],
            ['code' => 'MO', 'name' => 'Macao', 'flag' => '🇲🇴'],
            ['code' => 'MG', 'name' => 'Madagascar', 'flag' => '🇲🇬'],
            ['code' => 'MW', 'name' => 'Malawi', 'flag' => '🇲🇼'],
            ['code' => 'MY', 'name' => 'Malaysia', 'flag' => '🇲🇾'],
            ['code' => 'MV', 'name' => 'Maldives', 'flag' => '🇲🇻'],
            ['code' => 'ML', 'name' => 'Mali', 'flag' => '🇲🇱'],
            ['code' => 'MT', 'name' => 'Malta', 'flag' => '🇲🇹'],
            ['code' => 'MH', 'name' => 'Marshall Islands', 'flag' => '🇲🇭'],
            ['code' => 'MQ', 'name' => 'Martinique', 'flag' => '🇲🇶'],
            ['code' => 'MR', 'name' => 'Mauritania', 'flag' => '🇲🇷'],
            ['code' => 'MU', 'name' => 'Mauritius', 'flag' => '🇲🇺'],
            ['code' => 'YT', 'name' => 'Mayotte', 'flag' => '🇾🇹'],
            ['code' => 'MX', 'name' => 'Mexico', 'flag' => '🇲🇽'],
            ['code' => 'FM', 'name' => 'Micronesia', 'flag' => '🇫🇲'],
            ['code' => 'MD', 'name' => 'Moldova', 'flag' => '🇲🇩'],
            ['code' => 'MC', 'name' => 'Monaco', 'flag' => '🇲🇨'],
            ['code' => 'MN', 'name' => 'Mongolia', 'flag' => '🇲🇳'],
            ['code' => 'ME', 'name' => 'Montenegro', 'flag' => '🇲🇪'],
            ['code' => 'MS', 'name' => 'Montserrat', 'flag' => '🇲🇸'],
            ['code' => 'MA', 'name' => 'Morocco', 'flag' => '🇲🇦'],
            ['code' => 'MZ', 'name' => 'Mozambique', 'flag' => '🇲🇿'],
            ['code' => 'MM', 'name' => 'Myanmar', 'flag' => '🇲🇲'],
            ['code' => 'NA', 'name' => 'Namibia', 'flag' => '🇳🇦'],
            ['code' => 'NR', 'name' => 'Nauru', 'flag' => '🇳🇷'],
            ['code' => 'NP', 'name' => 'Nepal', 'flag' => '🇳🇵'],
            ['code' => 'NL', 'name' => 'Netherlands', 'flag' => '🇳🇱'],
            ['code' => 'NC', 'name' => 'New Caledonia', 'flag' => '🇳🇨'],
            ['code' => 'NZ', 'name' => 'New Zealand', 'flag' => '🇳🇿'],
            ['code' => 'NI', 'name' => 'Nicaragua', 'flag' => '🇳🇮'],
            ['code' => 'NE', 'name' => 'Niger', 'flag' => '🇳🇪'],
            ['code' => 'NG', 'name' => 'Nigeria', 'flag' => '🇳🇬'],
            ['code' => 'NU', 'name' => 'Niue', 'flag' => '🇳🇺'],
            ['code' => 'NF', 'name' => 'Norfolk Island', 'flag' => '🇳🇫'],
            ['code' => 'MK', 'name' => 'North Macedonia', 'flag' => '🇲🇰'],
            ['code' => 'MP', 'name' => 'Northern Mariana Islands', 'flag' => '🇲🇵'],
            ['code' => 'NO', 'name' => 'Norway', 'flag' => '🇳🇴'],
            ['code' => 'OM', 'name' => 'Oman', 'flag' => '🇴🇲'],
            ['code' => 'PK', 'name' => 'Pakistan', 'flag' => '🇵🇰'],
            ['code' => 'PW', 'name' => 'Palau', 'flag' => '🇵🇼'],
            ['code' => 'PS', 'name' => 'Palestine, State of', 'flag' => '🇵🇸'],
            ['code' => 'PA', 'name' => 'Panama', 'flag' => '🇵🇦'],
            ['code' => 'PG', 'name' => 'Papua New Guinea', 'flag' => '🇵🇬'],
            ['code' => 'PY', 'name' => 'Paraguay', 'flag' => '🇵🇾'],
            ['code' => 'PE', 'name' => 'Peru', 'flag' => '🇵🇪'],
            ['code' => 'PH', 'name' => 'Philippines', 'flag' => '🇵🇭'],
            ['code' => 'PN', 'name' => 'Pitcairn', 'flag' => '🇵🇳'],
            ['code' => 'PL', 'name' => 'Poland', 'flag' => '🇵🇱'],
            ['code' => 'PT', 'name' => 'Portugal', 'flag' => '🇵🇹'],
            ['code' => 'PR', 'name' => 'Puerto Rico', 'flag' => '🇵🇷'],
            ['code' => 'QA', 'name' => 'Qatar', 'flag' => '🇶🇦'],
            ['code' => 'RE', 'name' => 'Réunion', 'flag' => '🇷🇪'],
            ['code' => 'RO', 'name' => 'Romania', 'flag' => '🇷🇴'],
            ['code' => 'RU', 'name' => 'Russia', 'flag' => '🇷🇺'],
            ['code' => 'RW', 'name' => 'Rwanda', 'flag' => '🇷🇼'],
            ['code' => 'BL', 'name' => 'Saint Barthélemy', 'flag' => '🇧🇱'],
            ['code' => 'SH', 'name' => 'Saint Helena, Ascension and Tristan da Cunha', 'flag' => '🇸🇭'],
            ['code' => 'KN', 'name' => 'Saint Kitts and Nevis', 'flag' => '🇰🇳'],
            ['code' => 'LC', 'name' => 'Saint Lucia', 'flag' => '🇱🇨'],
            ['code' => 'MF', 'name' => 'Saint Martin (French part)', 'flag' => '🇲🇫'],
            ['code' => 'PM', 'name' => 'Saint Pierre and Miquelon', 'flag' => '🇵🇲'],
            ['code' => 'VC', 'name' => 'Saint Vincent and the Grenadines', 'flag' => '🇻🇨'],
            ['code' => 'WS', 'name' => 'Samoa', 'flag' => '🇼🇸'],
            ['code' => 'SM', 'name' => 'San Marino', 'flag' => '🇸🇲'],
            ['code' => 'ST', 'name' => 'Sao Tome and Principe', 'flag' => '🇸🇹'],
            ['code' => 'SA', 'name' => 'Saudi Arabia', 'flag' => '🇸🇦'],
            ['code' => 'SN', 'name' => 'Senegal', 'flag' => '🇸🇳'],
            ['code' => 'RS', 'name' => 'Serbia', 'flag' => '🇷🇸'],
            ['code' => 'SC', 'name' => 'Seychelles', 'flag' => '🇸🇨'],
            ['code' => 'SL', 'name' => 'Sierra Leone', 'flag' => '🇸🇱'],
            ['code' => 'SG', 'name' => 'Singapore', 'flag' => '🇸🇬'],
            ['code' => 'SX', 'name' => 'Sint Maarten (Dutch part)', 'flag' => '🇸🇽'],
            ['code' => 'SK', 'name' => 'Slovakia', 'flag' => '🇸🇰'],
            ['code' => 'SI', 'name' => 'Slovenia', 'flag' => '🇸🇮'],
            ['code' => 'SB', 'name' => 'Solomon Islands', 'flag' => '🇸🇧'],
            ['code' => 'SO', 'name' => 'Somalia', 'flag' => '🇸🇴'],
            ['code' => 'ZA', 'name' => 'South Africa', 'flag' => '🇿🇦'],
            ['code' => 'GS', 'name' => 'South Georgia and the South Sandwich Islands', 'flag' => '🇬🇸'],
            ['code' => 'SS', 'name' => 'South Sudan', 'flag' => '🇸🇸'],
            ['code' => 'ES', 'name' => 'Spain', 'flag' => '🇪🇸'],
            ['code' => 'LK', 'name' => 'Sri Lanka', 'flag' => '🇱🇰'],
            ['code' => 'SD', 'name' => 'Sudan', 'flag' => '🇸🇩'],
            ['code' => 'SR', 'name' => 'Suriname', 'flag' => '🇸🇷'],
            ['code' => 'SJ', 'name' => 'Svalbard and Jan Mayen', 'flag' => '🇸🇯'],
            ['code' => 'SE', 'name' => 'Sweden', 'flag' => '🇸🇪'],
            ['code' => 'CH', 'name' => 'Switzerland', 'flag' => '🇨🇭'],
            ['code' => 'SY', 'name' => 'Syrian Arab Republic', 'flag' => '🇸🇾'],
            ['code' => 'TW', 'name' => 'Taiwan', 'flag' => '🇹🇼'],
            ['code' => 'TJ', 'name' => 'Tajikistan', 'flag' => '🇹🇯'],
            ['code' => 'TZ', 'name' => 'Tanzania', 'flag' => '🇹🇿'],
            ['code' => 'TH', 'name' => 'Thailand', 'flag' => '🇹🇭'],
            ['code' => 'TL', 'name' => 'Timor-Leste', 'flag' => '🇹🇱'],
            ['code' => 'TG', 'name' => 'Togo', 'flag' => '🇹🇬'],
            ['code' => 'TK', 'name' => 'Tokelau', 'flag' => '🇹🇰'],
            ['code' => 'TO', 'name' => 'Tonga', 'flag' => '🇹🇴'],
            ['code' => 'TT', 'name' => 'Trinidad and Tobago', 'flag' => '🇹🇹'],
            ['code' => 'TN', 'name' => 'Tunisia', 'flag' => '🇹🇳'],
            ['code' => 'TR', 'name' => 'Turkey', 'flag' => '🇹🇷'],
            ['code' => 'TM', 'name' => 'Turkmenistan', 'flag' => '🇹🇲'],
            ['code' => 'TC', 'name' => 'Turks and Caicos Islands', 'flag' => '🇹🇨'],
            ['code' => 'TV', 'name' => 'Tuvalu', 'flag' => '🇹🇻'],
            ['code' => 'UG', 'name' => 'Uganda', 'flag' => '🇺🇬'],
            ['code' => 'UA', 'name' => 'Ukraine', 'flag' => '🇺🇦'],
            ['code' => 'AE', 'name' => 'United Arab Emirates', 'flag' => '🇦🇪'],
            ['code' => 'GB', 'name' => 'United Kingdom', 'flag' => '🇬🇧'],
            ['code' => 'UM', 'name' => 'United States Minor Outlying Islands', 'flag' => '🇺🇲'],
            ['code' => 'US', 'name' => 'United States', 'flag' => '🇺🇸'],
            ['code' => 'UY', 'name' => 'Uruguay', 'flag' => '🇺🇾'],
            ['code' => 'UZ', 'name' => 'Uzbekistan', 'flag' => '🇺🇿'],
            ['code' => 'VU', 'name' => 'Vanuatu', 'flag' => '🇻🇺'],
            ['code' => 'VE', 'name' => 'Venezuela', 'flag' => '🇻🇪'],
            ['code' => 'VN', 'name' => 'Vietnam', 'flag' => '🇻🇳'],
            ['code' => 'VG', 'name' => 'Virgin Islands, British', 'flag' => '🇻🇬'],
            ['code' => 'VI', 'name' => 'Virgin Islands, U.S.', 'flag' => '🇻🇮'],
            ['code' => 'WF', 'name' => 'Wallis and Futuna', 'flag' => '🇼🇫'],
            ['code' => 'EH', 'name' => 'Western Sahara', 'flag' => '🇪🇭'],
            ['code' => 'YE', 'name' => 'Yemen', 'flag' => '🇾🇪'],
            ['code' => 'ZM', 'name' => 'Zambia', 'flag' => '🇿🇲'],
            ['code' => 'ZW', 'name' => 'Zimbabwe', 'flag' => '🇿🇼'],
        ];
    }

    /**
     * Get country name by code (for display purposes)
     *
     * @since 1.8.48
     * @param string $code Country code
     * @return string Country name or code if not found
     */
    private static function get_country_name_by_code(string $code): string {
        $countries = self::get_countries_list();
        foreach ($countries as $country) {
            if ($country['code'] === strtoupper($code)) {
                return $country['name'];
            }
        }
        return $code;
    }

    public static function render_country_blacklist_field(): void {
        // Get access control instance to use structured blacklist methods
        $access_control = Guard_Dog()->features['access_control'] ?? null;
        $full_blacklist = $access_control ? $access_control->get_full_country_blacklist() : [];
        
        // Get comprehensive country list
        $countries = self::get_countries_list();
        
        // Build country names lookup for table display
        $country_names = [];
        foreach ($countries as $country) {
            $country_names[$country['code']] = $country['name'];
        }
        
        ?>
        <div class="guard-dog-country-blacklist-manager">
            <div class="guard-dog-add-country-form" style="margin-bottom: 20px; padding: 15px; background: #f9f9f9; border: 1px solid #ddd; border-radius: 4px;">
                <h4 style="margin-top: 0;"><?php esc_html_e('Add Country to Blacklist', 'guard-dog'); ?></h4>
                <table class="form-table" style="margin-bottom: 0;">
                    <tr>
                        <th scope="row">
                            <label for="guard-dog-new-country-code"><?php esc_html_e('Country', 'guard-dog'); ?></label>
                        </th>
                        <td>
                            <div style="position: relative; max-width: 400px;">
                                <input type="text" 
                                       id="guard-dog-new-country-code" 
                                       class="regular-text" 
                                       placeholder="<?php esc_attr_e('Type country name (e.g., China, Singapore)...', 'guard-dog'); ?>" 
                                       autocomplete="off"
                                       style="width: 100%;">
                                <input type="hidden" id="guard-dog-new-country-code-value" value="">
                                <div id="guard-dog-country-suggestions" class="guard-dog-country-suggestions" style="display: none;"></div>
                            </div>
                            <script type="application/json" id="guard-dog-countries-data">
                                <?php echo json_encode($countries); ?>
                            </script>
                            <p class="description" style="margin-top: 5px;">
                                <?php esc_html_e('Type the full country name (e.g., "China" or "Singapore"). The country code will be automatically applied.', 'guard-dog'); ?>
                            </p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="guard-dog-new-country-expiration"><?php esc_html_e('Expiration (days)', 'guard-dog'); ?></label>
                        </th>
                        <td>
                            <input type="number" id="guard-dog-new-country-expiration" class="small-text" value="30" min="0" step="1">
                            <p class="description" style="margin-top: 5px;"><?php esc_html_e('Enter 0 for permanent blacklist. Default: 30 days.', 'guard-dog'); ?></p>
                        </td>
                    </tr>
                    <tr>
                        <th scope="row">
                            <label for="guard-dog-new-country-reason"><?php esc_html_e('Reason (optional)', 'guard-dog'); ?></label>
                        </th>
                        <td>
                            <input type="text" id="guard-dog-new-country-reason" class="regular-text" placeholder="<?php esc_attr_e('e.g., High volume of malicious traffic', 'guard-dog'); ?>">
                        </td>
                    </tr>
                </table>
                <p>
                    <button type="button" id="guard-dog-add-country-button" class="button button-primary"><?php esc_html_e('Add Country to Blacklist', 'guard-dog'); ?></button>
                    <span id="guard-dog-add-country-message" style="margin-left: 10px;"></span>
                </p>
            </div>

            <div class="guard-dog-country-blacklist-table-wrapper">
                <h4><?php esc_html_e('Current Country Blacklist', 'guard-dog'); ?></h4>
                <?php if (empty($full_blacklist)): ?>
                    <p><?php esc_html_e('No countries are currently blacklisted.', 'guard-dog'); ?></p>
                <?php else: ?>
                    <table class="wp-list-table widefat fixed striped" id="guard-dog-country-blacklist-table">
                        <thead>
                            <tr>
                                <th style="width: 20%;"><?php esc_html_e('Country Code', 'guard-dog'); ?></th>
                                <th style="width: 25%;"><?php esc_html_e('Country Name', 'guard-dog'); ?></th>
                                <th style="width: 15%;"><?php esc_html_e('Expires', 'guard-dog'); ?></th>
                                <th style="width: 20%;"><?php esc_html_e('Added', 'guard-dog'); ?></th>
                                <th style="width: 20%;"><?php esc_html_e('Reason', 'guard-dog'); ?></th>
                                <th style="width: 15%;"><?php esc_html_e('Actions', 'guard-dog'); ?></th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($full_blacklist as $entry): 
                                $country_code = isset($entry['country_code']) ? strtoupper($entry['country_code']) : '';
                                $expires_date = $entry['expires_date'] ?? null;
                                $added_date = $entry['added_date'] ?? null;
                                $reason = $entry['reason'] ?? '';
                                $source = $entry['source'] ?? 'manual';
                                
                                // Check if expired
                                $is_expired = false;
                                if ($expires_date && $expires_date !== '') {
                                    $is_expired = strtotime($expires_date) < time();
                                }
                                
                                $country_name = isset($country_names[$country_code]) ? $country_names[$country_code] : self::get_country_name_by_code($country_code);
                                // Get flag emoji for display
                                $country_flag = '';
                                foreach ($countries as $country) {
                                    if ($country['code'] === $country_code) {
                                        $country_flag = $country['flag'];
                                        break;
                                    }
                                }
                                $expires_display = $expires_date ? date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($expires_date)) : __('Permanent', 'guard-dog');
                                $added_display = $added_date ? date_i18n(get_option('date_format') . ' ' . get_option('time_format'), strtotime($added_date)) : __('Unknown', 'guard-dog');
                            ?>
                                <tr class="<?php echo $is_expired ? 'expired' : ''; ?>">
                                    <td><code><?php echo esc_html($country_flag . ' ' . $country_code); ?></code></td>
                                    <td><?php echo esc_html($country_name); ?></td>
                                    <td>
                                        <?php if ($is_expired): ?>
                                            <span style="color: #d63638;"><?php esc_html_e('Expired', 'guard-dog'); ?></span>
                                        <?php else: ?>
                                            <?php echo esc_html($expires_display); ?>
                                        <?php endif; ?>
                                    </td>
                                    <td><?php echo esc_html($added_display); ?></td>
                                    <td><?php echo esc_html($reason); ?></td>
                                    <td>
                                        <button type="button" class="button button-small guard-dog-remove-country" data-country="<?php echo esc_attr($country_code); ?>">
                                            <?php esc_html_e('Remove', 'guard-dog'); ?>
                                        </button>
                                    </td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                <?php endif; ?>
            </div>
        </div>
        
        <!-- Hidden field to store blacklist data (for Settings API compatibility) -->
        <input type="hidden" name="guard_dog_country_blacklist" id="guard-dog-country-blacklist-hidden" value="">
        
        <p class="description">
            <?php esc_html_e('Block access from these countries based on IP geolocation. Expired entries are automatically removed.', 'guard-dog'); ?>
        </p>
        <?php
    }

    /**
     * Render access control help sidebar
     */
    private function render_access_control_help(): void {
        $current_ip = Guard_Dog_Utils::get_user_ip() ?: '127.0.0.1';
        $site_wide_blocking = get_option('guard_dog_site_wide_blocking', false);
        $ip_whitelist = get_option('guard_dog_ip_whitelist', '');
        $is_current_ip_whitelisted = false;

        // Use the same parsing logic as the access control class
        if (!empty($ip_whitelist)) {
            $access_control = function_exists('Guard_Dog') && isset(Guard_Dog()->features['access_control']) ? Guard_Dog()->features['access_control'] : null;
            if ($access_control) {
                // Use the same parsing method as the access control class.
                $ip_whitelist_array = method_exists($access_control, 'parse_ip_whitelist')
                    ? $access_control->parse_ip_whitelist($ip_whitelist)
                    : $access_control->parse_newline_list($ip_whitelist);
                $is_current_ip_whitelisted = $access_control->is_ip_in_list($current_ip, $ip_whitelist_array);
            }
        }
        ?>
        <div class="guard-dog-card">
            <h3>
                <span class="dashicons dashicons-info"></span>
                <?php esc_html_e('Access Control Help', 'guard-dog'); ?>
            </h3>

            <!-- Current IP Information -->
            <div class="guard-dog-help-section">
                <h4><?php esc_html_e('Your Current IP', 'guard-dog'); ?></h4>
                <div class="guard-dog-ip-display">
                    <code><?php echo esc_html($current_ip); ?></code>
                    <?php if ($site_wide_blocking): ?>
                        <?php if ($is_current_ip_whitelisted): ?>
                            <span class="guard-dog-status enabled"><?php esc_html_e('Whitelisted', 'guard-dog'); ?></span>
                        <?php else: ?>
                            <span class="guard-dog-status disabled"><?php esc_html_e('Not Whitelisted', 'guard-dog'); ?></span>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
                <p class="description">
                    <?php esc_html_e('This is your current IP address. Make sure it\'s in the whitelist before enabling site-wide blocking.', 'guard-dog'); ?>
                </p>
            </div>

            <!-- Site-Wide Blocking Status -->
            <?php if ($site_wide_blocking): ?>
            <div class="guard-dog-help-section">
                <h4><?php esc_html_e('Site-Wide Blocking Status', 'guard-dog'); ?></h4>
                <div class="guard-dog-status-indicator enabled">
                    <span class="dashicons dashicons-shield-alt"></span>
                    <?php esc_html_e('Active', 'guard-dog'); ?>
                </div>
                <p class="description">
                    <?php esc_html_e('Site-wide blocking is currently enabled. Only whitelisted IPs can access the site.', 'guard-dog'); ?>
                </p>
            </div>
            <?php endif; ?>

            <!-- Quick Actions -->
            <div class="guard-dog-help-section">
                <h4><?php esc_html_e('Quick Actions', 'guard-dog'); ?></h4>
                <div class="guard-dog-quick-actions">
                    <button type="button" class="button guard-dog-quick-action" id="guard-dog-add-current-ip">
                        <?php esc_html_e('Add My IP to Whitelist', 'guard-dog'); ?>
                    </button>
                </div>
            </div>

            <!-- Tips -->
            <div class="guard-dog-help-section">
                <h4><?php esc_html_e('Tips & Best Practices', 'guard-dog'); ?></h4>
                <ul class="guard-dog-tips-list">
                    <li><?php esc_html_e('Always add your IP to the whitelist before enabling site-wide blocking', 'guard-dog'); ?></li>
                    <li><?php esc_html_e('Use CIDR notation (e.g., 192.168.1.0/24 for IPv4, 2001:db8::/32 for IPv6) for IP ranges', 'guard-dog'); ?></li>
                    <li><?php esc_html_e('Supports both IPv4 and IPv6 addresses', 'guard-dog'); ?></li>
                    <li><?php esc_html_e('Test access control changes from a different IP or device', 'guard-dog'); ?></li>
                    <li><?php esc_html_e('Keep emergency access methods available (FTP, hosting panel)', 'guard-dog'); ?></li>
                    <li><?php esc_html_e('Site-wide blocking prevents access to ALL pages including login', 'guard-dog'); ?></li>
                </ul>
            </div>

            <!-- Emergency Access -->
            <div class="guard-dog-help-section">
                <h4><?php esc_html_e('Emergency Access', 'guard-dog'); ?></h4>
                <p><?php esc_html_e('If you get locked out, you can disable Guard Dog via FTP by renaming the plugin folder or using your hosting control panel.', 'guard-dog'); ?></p>
            </div>
        </div>
        <?php
    }
}
