<?php
/**
 * Guard Dog Users & Sessions Page
 *
 * Consolidated admin page combining User Registration (email verification,
 * password policy), Temporary Access, and Sessions into a single tabbed interface.
 * Uses composition to delegate tab rendering to existing page instances.
 *
 * @package GuardDog
 * @since 2.0.0
 */

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

class Guard_Dog_Users_Sessions_Page {

    /**
     * Query arg used for the outer Users & Sessions tabs.
     */
    private const TAB_QUERY_ARG = 'users_sessions_tab';

    /**
     * Feature instances for User Registration tabs
     * @var array
     */
    private $features;

    /**
     * Delegated User Registration page instance
     * @var Guard_Dog_User_Registration_Page|null
     */
    private $user_registration_page;

    /**
     * Delegated Temporary Access page instance
     * @var Guard_Dog_Temp_Access_Page|null
     */
    private $temp_access_page;

    /**
     * Delegated Sessions page instance
     * @var Guard_Dog_Sessions_Page|null
     */
    private $sessions_page;

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

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

    /**
     * Constructor
     *
     * @param array                        $features             Feature class instances
     * @param Guard_Dog_Temp_Access|null   $temp_access_handler  Temporary access handler instance
     * @param Guard_Dog_Session_Manager|null $session_manager    Session manager instance
     */
    public function __construct(array $features = [], $temp_access_handler = null, $session_manager = null) {
        $this->features = $features;

        $this->initialize_delegate_pages($temp_access_handler, $session_manager);
        $this->initialize_tabs();
        $this->determine_current_tab();
    }

    /**
     * Initialize delegate page instances for composition
     *
     * @param Guard_Dog_Temp_Access|null    $temp_access_handler Temporary access handler instance
     * @param Guard_Dog_Session_Manager|null $session_manager    Session manager instance
     */
    private function initialize_delegate_pages($temp_access_handler, $session_manager): void {
        // User Registration page handles email_verification and password_policy tabs
        if (class_exists('Guard_Dog_User_Registration_Page')) {
            $this->user_registration_page = new Guard_Dog_User_Registration_Page($this->features);
        }

        // Temporary Access page handles the temporary_access tab
        if ($temp_access_handler && class_exists('Guard_Dog_Temp_Access_Page')) {
            $this->temp_access_page = new Guard_Dog_Temp_Access_Page($temp_access_handler);
        }

        // Sessions page handles the sessions tab
        if ($session_manager && class_exists('Guard_Dog_Sessions_Page')) {
            $this->sessions_page = new Guard_Dog_Sessions_Page($session_manager);
        }
    }

    /**
     * Initialize tabs configuration
     */
    private function initialize_tabs(): void {
        $this->tabs = [
            'email_verification' => [
                'label' => __('Email Verification', 'guard-dog'),
                'icon'  => 'dashicons-email-alt',
            ],
            'password_policy' => [
                'label' => __('Password Policy', 'guard-dog'),
                'icon'  => 'dashicons-lock',
            ],
            'temporary_access' => [
                'label' => __('Temporary Access', 'guard-dog'),
                'icon'  => 'dashicons-clock',
            ],
            'sessions' => [
                'label' => __('Sessions', 'guard-dog'),
                'icon'  => 'dashicons-laptop',
            ],
        ];
    }

    /**
     * Determine the current active tab from request parameters
     */
    private function determine_current_tab(): void {
        $this->current_tab = 'email_verification';

        $tab_param = $this->get_requested_tab();
        if ($tab_param && array_key_exists($tab_param, $this->tabs)) {
            $this->current_tab = $tab_param;
        }
    }

    /**
     * Get the requested outer tab from the current request.
     *
     * Supports the new dedicated query arg and the legacy nonce-protected tab
     * links so older bookmarks continue to work during the transition.
     */
    private function get_requested_tab(): string {
        if (isset($_GET[self::TAB_QUERY_ARG])) {
            return sanitize_text_field(wp_unslash($_GET[self::TAB_QUERY_ARG]));
        }

        if (
            isset($_GET['tab'])
            && isset($_GET['_wpnonce'])
            && wp_verify_nonce(sanitize_text_field(wp_unslash($_GET['_wpnonce'])), 'guard_dog_users_sessions_tab')
        ) {
            return sanitize_text_field(wp_unslash($_GET['tab']));
        }

        return '';
    }

    /**
     * Build a tab URL for the consolidated page without relying on the legacy tab arg.
     */
    private function get_tab_url(string $tab_id): string {
        return add_query_arg(
            [self::TAB_QUERY_ARG => $tab_id],
            remove_query_arg(['tab', '_wpnonce'])
        );
    }

    /**
     * Render the Users & Sessions page
     */
    public function render(): void {
        $this->prepare_page_data();
        $this->render_page_with_tabs();
    }

    /**
     * Prepare data needed by User Registration tabs
     */
    private function prepare_page_data(): void {
        $email_provider = $this->features['email_provider'] ?? null;
        $email_provider_configured = $email_provider && $email_provider->is_configured();

        $GLOBALS['guard_dog_user_registration_data'] = [
            // Email provider status
            'email_provider_configured'          => $email_provider_configured,
            // Email verification
            'email_verification_enabled'         => get_option(Guard_Dog_Email_Verification::OPTION_ENABLED, false),
            'email_verification_expiry'          => get_option(Guard_Dog_Email_Verification::OPTION_EXPIRY, 48),
            'email_verification_bypass_admin'    => get_option(Guard_Dog_Email_Verification::OPTION_BYPASS_ADMIN, true),
            'email_verification_resend_limit'    => get_option(Guard_Dog_Email_Verification::OPTION_RESEND_LIMIT, 3),
            'email_verification_resend_daily_limit' => get_option(Guard_Dog_Email_Verification::OPTION_RESEND_DAILY_LIMIT, 5),
            // Password policy
            'password_policy_enabled'            => get_option(Guard_Dog_Password_Policy::OPTION_ENABLED, false),
            'password_min_length'                => get_option('guard_dog_password_min_length', 12),
            'password_require_uppercase'         => get_option('guard_dog_password_require_uppercase', true),
            'password_require_lowercase'         => get_option('guard_dog_password_require_lowercase', true),
            'password_require_numbers'           => get_option('guard_dog_password_require_numbers', true),
            'password_require_special'           => get_option('guard_dog_password_require_special', true),
            'password_block_common'              => get_option('guard_dog_password_block_common', false),
            'password_block_username'            => get_option('guard_dog_password_block_username', true),
            'password_block_email'               => get_option('guard_dog_password_block_email', true),
            'password_reuse_limit'               => get_option('guard_dog_password_reuse_limit', 5),
            'password_policy_exempt_roles'       => get_option('guard_dog_password_policy_exempt_roles', []),
            // Password expiration
            'password_expiration_enabled'        => get_option('guard_dog_password_expiration_enabled', false),
            'password_expiration_days'           => get_option('guard_dog_password_expiration_days', 90),
            'password_expiration_warning_days'   => get_option('guard_dog_password_expiration_warning_days', 7),
            'password_expiration_email_enabled'  => get_option('guard_dog_password_expiration_email_enabled', false),
            'password_expiration_exempt_roles'   => get_option('guard_dog_password_expiration_exempt_roles', []),
            // Available roles for exemption
            'available_roles'                    => $this->get_available_roles(),
        ];
    }

    /**
     * Get available WordPress roles for exemption selection
     *
     * @return array Array of role slugs and names
     */
    private function get_available_roles(): array {
        $roles = [];
        $wp_roles = wp_roles();

        foreach ($wp_roles->get_names() as $slug => $name) {
            $roles[] = [
                'slug' => $slug,
                'name' => $name,
            ];
        }

        return $roles;
    }

    /**
     * Render the page with integrated tabbed interface
     */
    private function render_page_with_tabs(): void {
        ?>
        <div class="wrap guard-dog-admin">
            <h1 class="guard-dog-page-title">
                <span class="dashicons dashicons-admin-users"></span>
                <?php esc_html_e('Users & Sessions', 'guard-dog'); ?>
            </h1>

            <p class="guard-dog-page-subtitle">
                <?php esc_html_e('Manage user registration settings, temporary access, and active sessions.', 'guard-dog'); ?>
            </p>

            <?php settings_errors('guard_dog_user_registration'); ?>

            <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($this->get_tab_url($tab_id)); ?>"
                                   class="guard-dog-tab-link<?php echo esc_attr($this->current_tab === $tab_id ? ' active' : ''); ?>"
                                   data-tab="<?php echo esc_attr($tab_id); ?>"
                                   data-storage-key="guard_dog_users_sessions_active_tab"
                                   data-query-param="<?php echo esc_attr(self::TAB_QUERY_ARG); ?>">
                                    <?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_help_sidebar(); ?>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Render all tab panels with proper wrapper structure
     */
    private function render_all_tab_panels(): void {
        $data = $GLOBALS['guard_dog_user_registration_data'] ?? [];

        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 $this->render_tab_content($tab_id, $data); ?>
            </div>
            <?php
        }
    }

    /**
     * Render content for a specific tab
     *
     * Tabs 1-2 (email_verification, password_policy) are wrapped in a form with
     * settings_fields('guard_dog_user_registration'). Tabs 3-4 delegate to their
     * respective page instances which contain their own forms.
     *
     * @param string $tab_id The tab identifier
     * @param array  $data   The prepared page data
     */
    private function render_tab_content(string $tab_id, array $data): void {
        switch ($tab_id) {
            case 'email_verification':
            case 'password_policy':
                $this->render_user_registration_tab($tab_id, $data);
                break;

            case 'temporary_access':
                $this->render_temporary_access_tab();
                break;

            case 'sessions':
                $this->render_sessions_tab();
                break;

            default:
                ?>
                <p><?php esc_html_e('Invalid tab selected.', 'guard-dog'); ?></p>
                <?php
                break;
        }
    }

    /**
     * Render a User Registration tab (email_verification or password_policy)
     *
     * Each tab gets its own form with the guard_dog_user_registration settings group.
     *
     * @param string $tab_id The tab identifier
     * @param array  $data   The prepared page data
     */
    private function render_user_registration_tab(string $tab_id, array $data): void {
        ?>
        <form method="post" action="options.php">
            <?php settings_fields('guard_dog_user_registration'); ?>

            <?php
            switch ($tab_id) {
                case 'email_verification':
                    $this->render_email_verification_content($data);
                    break;
                case 'password_policy':
                    $this->render_password_policy_content($data);
                    break;
            }
            ?>

            <?php submit_button(__('Save Settings', 'guard-dog')); ?>
        </form>
        <?php
    }

    /**
     * Render the Email Verification tab content
     *
     * @param array $data Page data
     */
    private function render_email_verification_content(array $data): void {
        ?>
        <h3>
            <span class="dashicons dashicons-email-alt"></span>
            <?php esc_html_e('Email Verification Settings', 'guard-dog'); ?>
        </h3>

        <p><?php esc_html_e('Require new users to verify their email address before they can log in.', 'guard-dog'); ?></p>

        <?php if (!($data['email_provider_configured'] ?? false)): ?>
            <div class="guard-dog-security-notice" style="margin-bottom: 20px;">
                <h4><?php esc_html_e('Email Provider Required', 'guard-dog'); ?></h4>
                <p>
                    <?php
                    // Translators: %s is a link to the Settings page
                    printf(
                        esc_html__('Email verification requires an email provider to be configured. Please configure an email provider in %s first.', 'guard-dog'),
                        '<a href="' . esc_url(admin_url('admin.php?page=guard-dog-settings')) . '">' . esc_html__('Settings', 'guard-dog') . '</a>'
                    );
                    ?>
                </p>
            </div>
        <?php endif; ?>

        <table class="form-table">
            <tr>
                <th scope="row">
                    <label for="guard_dog_email_verification_enabled">
                        <?php esc_html_e('Enable Email Verification', 'guard-dog'); ?>
                    </label>
                </th>
                <td>
                    <input type="checkbox"
                           id="guard_dog_email_verification_enabled"
                           name="guard_dog_email_verification_enabled"
                           value="1"
                           <?php checked($data['email_verification_enabled'] ?? false); ?>
                           <?php disabled(!($data['email_provider_configured'] ?? false)); ?> />
                    <p class="description">
                        <?php esc_html_e('When enabled, new users must verify their email address before they can log in.', 'guard-dog'); ?>
                    </p>
                </td>
            </tr>
            <tr>
                <th scope="row">
                    <label for="guard_dog_email_verification_link_expiration">
                        <?php esc_html_e('Verification Link Expiry (Hours)', 'guard-dog'); ?>
                    </label>
                </th>
                <td>
                    <input type="number"
                           id="guard_dog_email_verification_link_expiration"
                           name="guard_dog_email_verification_link_expiration"
                           value="<?php echo esc_attr($data['email_verification_expiry'] ?? 48); ?>"
                           min="1"
                           max="168"
                           class="small-text" />
                    <p class="description">
                        <?php esc_html_e('How long the verification link remains valid (1-168 hours).', 'guard-dog'); ?>
                    </p>
                </td>
            </tr>
            <tr>
                <th scope="row">
                    <label for="guard_dog_email_verification_bypass_admin">
                        <?php esc_html_e('Admin Bypass', 'guard-dog'); ?>
                    </label>
                </th>
                <td>
                    <input type="checkbox"
                           id="guard_dog_email_verification_bypass_admin"
                           name="guard_dog_email_verification_bypass_admin"
                           value="1"
                           <?php checked($data['email_verification_bypass_admin'] ?? true); ?> />
                    <p class="description">
                        <?php esc_html_e('Allow administrators to bypass email verification.', 'guard-dog'); ?>
                    </p>
                </td>
            </tr>
            <tr>
                <th scope="row">
                    <label for="guard_dog_email_verification_resend_limit">
                        <?php esc_html_e('Resend Limit (Per Request)', 'guard-dog'); ?>
                    </label>
                </th>
                <td>
                    <input type="number"
                           id="guard_dog_email_verification_resend_limit"
                           name="guard_dog_email_verification_resend_limit"
                           value="<?php echo esc_attr($data['email_verification_resend_limit'] ?? 3); ?>"
                           min="1"
                           max="10"
                           class="small-text" />
                    <p class="description">
                        <?php esc_html_e('Maximum number of verification emails that can be resent per request.', 'guard-dog'); ?>
                    </p>
                </td>
            </tr>
            <tr>
                <th scope="row">
                    <label for="guard_dog_email_verification_resend_daily_limit">
                        <?php esc_html_e('Daily Resend Limit', 'guard-dog'); ?>
                    </label>
                </th>
                <td>
                    <input type="number"
                           id="guard_dog_email_verification_resend_daily_limit"
                           name="guard_dog_email_verification_resend_daily_limit"
                           value="<?php echo esc_attr($data['email_verification_resend_daily_limit'] ?? 5); ?>"
                           min="1"
                           max="20"
                           class="small-text" />
                    <p class="description">
                        <?php esc_html_e('Maximum number of verification emails per user per day.', 'guard-dog'); ?>
                    </p>
                </td>
            </tr>
        </table>
        <?php
    }

    /**
     * Render the Password Policy tab content
     *
     * @param array $data Page data
     */
    private function render_password_policy_content(array $data): void {
        $available_roles = $data['available_roles'] ?? [];
        ?>
        <h3>
            <span class="dashicons dashicons-lock"></span>
            <?php esc_html_e('Password Policy Settings', 'guard-dog'); ?>
        </h3>

        <p><?php esc_html_e('Configure password strength requirements and expiration policies for user accounts.', 'guard-dog'); ?></p>

        <table class="form-table">
            <tr>
                <th scope="row">
                    <label for="guard_dog_password_policy_enabled">
                        <?php esc_html_e('Enable Password Policy', 'guard-dog'); ?>
                    </label>
                </th>
                <td>
                    <input type="checkbox"
                           id="guard_dog_password_policy_enabled"
                           name="guard_dog_password_policy_enabled"
                           value="1"
                           <?php checked($data['password_policy_enabled'] ?? false); ?> />
                    <p class="description">
                        <?php esc_html_e('Enforce password strength requirements for all users.', 'guard-dog'); ?>
                    </p>
                </td>
            </tr>
            <tr>
                <th scope="row">
                    <label for="guard_dog_password_min_length">
                        <?php esc_html_e('Minimum Length', 'guard-dog'); ?>
                    </label>
                </th>
                <td>
                    <input type="number"
                           id="guard_dog_password_min_length"
                           name="guard_dog_password_min_length"
                           value="<?php echo esc_attr($data['password_min_length'] ?? 12); ?>"
                           min="8"
                           max="64"
                           class="small-text" />
                    <p class="description">
                        <?php esc_html_e('Minimum number of characters required (8-64).', 'guard-dog'); ?>
                    </p>
                </td>
            </tr>
            <tr>
                <th scope="row">
                    <?php esc_html_e('Character Requirements', 'guard-dog'); ?>
                </th>
                <td>
                    <fieldset>
                        <label>
                            <input type="checkbox"
                                   name="guard_dog_password_require_uppercase"
                                   value="1"
                                   <?php checked($data['password_require_uppercase'] ?? true); ?> />
                            <?php esc_html_e('Require uppercase letters', 'guard-dog'); ?>
                        </label><br />
                        <label>
                            <input type="checkbox"
                                   name="guard_dog_password_require_lowercase"
                                   value="1"
                                   <?php checked($data['password_require_lowercase'] ?? true); ?> />
                            <?php esc_html_e('Require lowercase letters', 'guard-dog'); ?>
                        </label><br />
                        <label>
                            <input type="checkbox"
                                   name="guard_dog_password_require_numbers"
                                   value="1"
                                   <?php checked($data['password_require_numbers'] ?? true); ?> />
                            <?php esc_html_e('Require numbers', 'guard-dog'); ?>
                        </label><br />
                        <label>
                            <input type="checkbox"
                                   name="guard_dog_password_require_special"
                                   value="1"
                                   <?php checked($data['password_require_special'] ?? true); ?> />
                            <?php esc_html_e('Require special characters', 'guard-dog'); ?>
                        </label>
                    </fieldset>
                </td>
            </tr>
            <tr>
                <th scope="row">
                    <?php esc_html_e('Password Restrictions', 'guard-dog'); ?>
                </th>
                <td>
                    <fieldset>
                        <label>
                            <input type="checkbox"
                                   name="guard_dog_password_block_common"
                                   value="1"
                                   <?php checked($data['password_block_common'] ?? false); ?> />
                            <?php esc_html_e('Block common passwords', 'guard-dog'); ?>
                        </label><br />
                        <label>
                            <input type="checkbox"
                                   name="guard_dog_password_block_username"
                                   value="1"
                                   <?php checked($data['password_block_username'] ?? true); ?> />
                            <?php esc_html_e('Block passwords containing username', 'guard-dog'); ?>
                        </label><br />
                        <label>
                            <input type="checkbox"
                                   name="guard_dog_password_block_email"
                                   value="1"
                                   <?php checked($data['password_block_email'] ?? true); ?> />
                            <?php esc_html_e('Block passwords containing email', 'guard-dog'); ?>
                        </label>
                    </fieldset>
                </td>
            </tr>
            <tr>
                <th scope="row">
                    <label for="guard_dog_password_reuse_limit">
                        <?php esc_html_e('Password Reuse Limit', 'guard-dog'); ?>
                    </label>
                </th>
                <td>
                    <input type="number"
                           id="guard_dog_password_reuse_limit"
                           name="guard_dog_password_reuse_limit"
                           value="<?php echo esc_attr($data['password_reuse_limit'] ?? 5); ?>"
                           min="0"
                           max="24"
                           class="small-text" />
                    <p class="description">
                        <?php esc_html_e('Number of previous passwords to remember (0 to disable).', 'guard-dog'); ?>
                    </p>
                </td>
            </tr>
            <tr>
                <th scope="row">
                    <?php esc_html_e('Exempt Roles', 'guard-dog'); ?>
                </th>
                <td>
                    <fieldset>
                        <?php
                        $exempt_roles = $data['password_policy_exempt_roles'] ?? [];
                        foreach ($available_roles as $role):
                            ?>
                            <label>
                                <input type="checkbox"
                                       name="guard_dog_password_policy_exempt_roles[]"
                                       value="<?php echo esc_attr($role['slug']); ?>"
                                       <?php checked(in_array($role['slug'], (array) $exempt_roles, true)); ?> />
                                <?php echo esc_html($role['name']); ?>
                            </label><br />
                        <?php endforeach; ?>
                    </fieldset>
                    <p class="description">
                        <?php esc_html_e('Selected roles will be exempt from the password policy.', 'guard-dog'); ?>
                    </p>
                </td>
            </tr>
        </table>

        <h3>
            <span class="dashicons dashicons-calendar-alt"></span>
            <?php esc_html_e('Password Expiration', 'guard-dog'); ?>
        </h3>

        <table class="form-table">
            <tr>
                <th scope="row">
                    <label for="guard_dog_password_expiration_enabled">
                        <?php esc_html_e('Enable Password Expiration', 'guard-dog'); ?>
                    </label>
                </th>
                <td>
                    <input type="checkbox"
                           id="guard_dog_password_expiration_enabled"
                           name="guard_dog_password_expiration_enabled"
                           value="1"
                           <?php checked($data['password_expiration_enabled'] ?? false); ?> />
                    <p class="description">
                        <?php esc_html_e('Require users to change their password periodically.', 'guard-dog'); ?>
                    </p>
                </td>
            </tr>
            <tr>
                <th scope="row">
                    <label for="guard_dog_password_expiration_days">
                        <?php esc_html_e('Expiration Period (Days)', 'guard-dog'); ?>
                    </label>
                </th>
                <td>
                    <input type="number"
                           id="guard_dog_password_expiration_days"
                           name="guard_dog_password_expiration_days"
                           value="<?php echo esc_attr($data['password_expiration_days'] ?? 90); ?>"
                           min="1"
                           max="365"
                           class="small-text" />
                    <p class="description">
                        <?php esc_html_e('Number of days before a password expires (1-365).', 'guard-dog'); ?>
                    </p>
                </td>
            </tr>
            <tr>
                <th scope="row">
                    <label for="guard_dog_password_expiration_warning_days">
                        <?php esc_html_e('Warning Period (Days)', 'guard-dog'); ?>
                    </label>
                </th>
                <td>
                    <input type="number"
                           id="guard_dog_password_expiration_warning_days"
                           name="guard_dog_password_expiration_warning_days"
                           value="<?php echo esc_attr($data['password_expiration_warning_days'] ?? 7); ?>"
                           min="1"
                           max="30"
                           class="small-text" />
                    <p class="description">
                        <?php esc_html_e('Days before expiration to start warning users.', 'guard-dog'); ?>
                    </p>
                </td>
            </tr>
            <tr>
                <th scope="row">
                    <label for="guard_dog_password_expiration_email_enabled">
                        <?php esc_html_e('Email Notifications', 'guard-dog'); ?>
                    </label>
                </th>
                <td>
                    <input type="checkbox"
                           id="guard_dog_password_expiration_email_enabled"
                           name="guard_dog_password_expiration_email_enabled"
                           value="1"
                           <?php checked($data['password_expiration_email_enabled'] ?? false); ?> />
                    <p class="description">
                        <?php esc_html_e('Send email notifications when passwords are about to expire.', 'guard-dog'); ?>
                    </p>
                </td>
            </tr>
            <tr>
                <th scope="row">
                    <?php esc_html_e('Expiration Exempt Roles', 'guard-dog'); ?>
                </th>
                <td>
                    <fieldset>
                        <?php
                        $expiration_exempt_roles = $data['password_expiration_exempt_roles'] ?? [];
                        foreach ($available_roles as $role):
                            ?>
                            <label>
                                <input type="checkbox"
                                       name="guard_dog_password_expiration_exempt_roles[]"
                                       value="<?php echo esc_attr($role['slug']); ?>"
                                       <?php checked(in_array($role['slug'], (array) $expiration_exempt_roles, true)); ?> />
                                <?php echo esc_html($role['name']); ?>
                            </label><br />
                        <?php endforeach; ?>
                    </fieldset>
                    <p class="description">
                        <?php esc_html_e('Selected roles will be exempt from password expiration.', 'guard-dog'); ?>
                    </p>
                </td>
            </tr>
        </table>
        <?php
    }

    /**
     * Render the Temporary Access tab
     *
     * Delegates to the Temp Access page instance which manages its own
     * internal sub-tabs and forms.
     */
    private function render_temporary_access_tab(): void {
        if ($this->temp_access_page) {
            $this->temp_access_page->render_page_content();
        } else {
            ?>
            <div class="guard-dog-notice-info">
                <p><?php esc_html_e('Temporary Access feature is not available.', 'guard-dog'); ?></p>
            </div>
            <?php
        }
    }

    /**
     * Render the Sessions tab
     *
     * Delegates to the Sessions page instance which manages its own
     * internal sub-tabs and forms.
     */
    private function render_sessions_tab(): void {
        if ($this->sessions_page) {
            $this->sessions_page->render_page_content();
        } else {
            ?>
            <div class="guard-dog-notice-info">
                <p><?php esc_html_e('Session Management feature is not available.', 'guard-dog'); ?></p>
            </div>
            <?php
        }
    }

    /**
     * Render the help sidebar
     */
    private function render_help_sidebar(): void {
        ?>
        <div class="guard-dog-card">
            <h3><?php esc_html_e('Users & Sessions', 'guard-dog'); ?></h3>

            <div class="guard-dog-info-list">
                <div class="guard-dog-info-item">
                    <span class="dashicons dashicons-email-alt"></span>
                    <div>
                        <strong><?php esc_html_e('Email Verification', 'guard-dog'); ?></strong>
                        <p class="description">
                            <?php esc_html_e('Require new users to verify their email address before logging in.', 'guard-dog'); ?>
                        </p>
                    </div>
                </div>

                <div class="guard-dog-info-item">
                    <span class="dashicons dashicons-lock"></span>
                    <div>
                        <strong><?php esc_html_e('Password Policy', 'guard-dog'); ?></strong>
                        <p class="description">
                            <?php esc_html_e('Enforce password strength and expiration policies for user accounts.', 'guard-dog'); ?>
                        </p>
                    </div>
                </div>

                <div class="guard-dog-info-item">
                    <span class="dashicons dashicons-clock"></span>
                    <div>
                        <strong><?php esc_html_e('Temporary Access', 'guard-dog'); ?></strong>
                        <p class="description">
                            <?php esc_html_e('Create time-limited user accounts for developers, editors, or support staff.', 'guard-dog'); ?>
                        </p>
                    </div>
                </div>

                <div class="guard-dog-info-item">
                    <span class="dashicons dashicons-laptop"></span>
                    <div>
                        <strong><?php esc_html_e('Sessions', 'guard-dog'); ?></strong>
                        <p class="description">
                            <?php esc_html_e('Monitor and manage active user sessions across your site.', 'guard-dog'); ?>
                        </p>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }
}
