<?php
/**
 * Guard Dog User Registration Settings Page
 *
 * Admin page for managing email verification and password policy settings.
 *
 * @package GuardDog
 * @since 1.9.0
 */

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

class Guard_Dog_User_Registration_Page {

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

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

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

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

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

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

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

    /**
     * Render the user registration settings page
     */
    public function render(): void {
        // Prepare data for page
        $this->prepare_page_data();
        
        // Render main page
        $this->render_user_registration_page();
    }

    /**
     * Prepare data for page
     */
    private function prepare_page_data(): void {
        // Check if email provider is configured
        $email_provider = $this->features['email_provider'] ?? null;
        $email_provider_configured = $email_provider && $email_provider->is_configured();

        // Email verification settings
        $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 settings
        $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 settings
        $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', []);

        // Pass data to partials via global variables
        $GLOBALS['guard_dog_user_registration_data'] = [
            // Email provider status
            'email_provider_configured' => $email_provider_configured,
            // Email verification
            'email_verification_enabled' => $email_verification_enabled,
            'email_verification_expiry' => $email_verification_expiry,
            'email_verification_bypass_admin' => $email_verification_bypass_admin,
            'email_verification_resend_limit' => $email_verification_resend_limit,
            'email_verification_resend_daily_limit' => $email_verification_resend_daily_limit,
            // Password policy
            'password_policy_enabled' => $password_policy_enabled,
            'password_min_length' => $password_min_length,
            'password_require_uppercase' => $password_require_uppercase,
            'password_require_lowercase' => $password_require_lowercase,
            'password_require_numbers' => $password_require_numbers,
            'password_require_special' => $password_require_special,
            'password_block_common' => $password_block_common,
            'password_block_username' => $password_block_username,
            'password_block_email' => $password_block_email,
            'password_reuse_limit' => $password_reuse_limit,
            'password_policy_exempt_roles' => $password_policy_exempt_roles,
            // Password expiration
            'password_expiration_enabled' => $password_expiration_enabled,
            'password_expiration_days' => $password_expiration_days,
            'password_expiration_warning_days' => $password_expiration_warning_days,
            'password_expiration_email_enabled' => $password_expiration_email_enabled,
            'password_expiration_exempt_roles' => $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 user registration settings page
     */
    private function render_user_registration_page(): void {
        $data = $GLOBALS['guard_dog_user_registration_data'] ?? [];
        ?>
        <div class="wrap guard-dog-admin">
            <h1 class="guard-dog-page-title">
                <span class="dashicons dashicons-admin-users"></span>
                <?php esc_html_e('User Registration Security', 'guard-dog'); ?>
            </h1>

            <p class="guard-dog-page-subtitle">
                <?php esc_html_e('Configure email verification requirements and password strength policies for user accounts.', 'guard-dog'); ?>
            </p>

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

            <div class="guard-dog-admin-grid">
                <div class="guard-dog-main-content">
                    <form method="post" action="options.php">
                        <?php settings_fields('guard_dog_user_registration'); ?>

                        <!-- 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_user_registration_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($data); ?>
                            </div>
                        </div>

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

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

    /**
     * Render all tab panels
     *
     * @param array $data Page data
     */
    private function render_all_tab_panels(array $data): 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 'email_verification':
                        $this->render_email_verification_tab($data);
                        break;
                    case 'password_policy':
                        $this->render_password_policy_tab($data);
                        break;
                }
                ?>
            </div>
            <?php
        }
    }

    /**
     * Render the Email Verification tab
     *
     * @param array $data Page data
     */
    private function render_email_verification_tab(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)); ?> />
                                <label for="guard_dog_email_verification_enabled">
                                    <?php esc_html_e('Require email verification for new user registrations', 'guard-dog'); ?>
                                </label>
                                <?php if (!($data['email_provider_configured'] ?? false)): ?>
                                    <p class="description" style="color: #d63638;">
                                        <?php esc_html_e('This setting requires an email provider to be configured.', 'guard-dog'); ?>
                                    </p>
                                <?php endif; ?>
                            </td>
                        </tr>

                        <tr>
                            <th scope="row">
                                <label for="guard_dog_email_verification_expiry">
                                    <?php esc_html_e('Verification Link Expiry', 'guard-dog'); ?>
                                </label>
                            </th>
                            <td>
                                <input type="number" 
                                       id="guard_dog_email_verification_expiry" 
                                       name="guard_dog_email_verification_expiry" 
                                       value="<?php echo esc_attr($data['email_verification_expiry'] ?? 48); ?>" 
                                       min="1" 
                                       max="168" 
                                       class="small-text" />
                                <label for="guard_dog_email_verification_expiry">
                                    <?php esc_html_e('hours', 'guard-dog'); ?>
                                </label>
                                <p class="description">
                                    <?php esc_html_e('How long verification links remain valid.', 'guard-dog'); ?>
                                </p>
                            </td>
                        </tr>

                        <tr>
                            <th scope="row">
                                <label for="guard_dog_email_verification_bypass_admin">
                                    <?php esc_html_e('Bypass for Admin-Created Users', '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); ?> />
                                <label for="guard_dog_email_verification_bypass_admin">
                                    <?php esc_html_e('Automatically verify users created by administrators', 'guard-dog'); ?>
                                </label>
                            </td>
                        </tr>

                        <tr>
                            <th scope="row">
                                <label for="guard_dog_email_verification_resend_limit">
                                    <?php esc_html_e('Resend Rate Limits', '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" />
                                <label for="guard_dog_email_verification_resend_limit">
                                    <?php esc_html_e('per hour,', 'guard-dog'); ?>
                                </label>

                                <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" />
                                <label for="guard_dog_email_verification_resend_daily_limit">
                                    <?php esc_html_e('per day', 'guard-dog'); ?>
                                </label>
                                <p class="description">
                                    <?php esc_html_e('Rate limits for resending verification emails.', 'guard-dog'); ?>
                                </p>
                            </td>
                        </tr>
                    </table>
        <?php
    }

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

        <p><?php esc_html_e('Enforce password strength requirements for all users.', '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); ?> />
                    <label for="guard_dog_password_policy_enabled">
                        <?php esc_html_e('Enforce password strength requirements', 'guard-dog'); ?>
                    </label>
                </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="128"
                           class="small-text" />
                    <label for="guard_dog_password_min_length">
                        <?php esc_html_e('characters', 'guard-dog'); ?>
                    </label>
                </td>
            </tr>

            <tr>
                <th scope="row"><?php esc_html_e('Required Character Types', '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('Uppercase letters (A-Z)', '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('Lowercase letters (a-z)', '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('Numbers (0-9)', '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('Special characters (!@#$%^&*)', 'guard-dog'); ?>
                        </label>
                    </fieldset>
                </td>
            </tr>

            <tr>
                <th scope="row"><?php esc_html_e('Blocked Content', '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 address', 'guard-dog'); ?>
                        </label>
                    </fieldset>
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="guard_dog_password_reuse_limit">
                        <?php esc_html_e('Password Reuse Prevention', '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="10"
                           class="small-text" />
                    <label for="guard_dog_password_reuse_limit">
                        <?php esc_html_e('previous passwords (0 = disabled)', 'guard-dog'); ?>
                    </label>
                    <p class="description">
                        <?php esc_html_e('Prevent users from reusing their last N passwords.', 'guard-dog'); ?>
                    </p>
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="guard_dog_password_policy_exempt_roles">
                        <?php esc_html_e('Exempt Roles', 'guard-dog'); ?>
                    </label>
                </th>
                <td>
                    <fieldset>
                        <?php foreach ($data['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'], $data['password_policy_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 policy requirements.', 'guard-dog'); ?>
                    </p>
                </td>
            </tr>

            <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); ?> />
                    <label for="guard_dog_password_expiration_enabled">
                        <?php esc_html_e('Require users to change their password after a set period', 'guard-dog'); ?>
                    </label>
                    <p class="description">
                        <?php esc_html_e('When enabled, users will be required to reset their password after the expiration period.', 'guard-dog'); ?>
                    </p>
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="guard_dog_password_expiration_days">
                        <?php esc_html_e('Expiration Period', '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" />
                    <label for="guard_dog_password_expiration_days">
                        <?php esc_html_e('days', 'guard-dog'); ?>
                    </label>
                    <p class="description">
                        <?php esc_html_e('Number of days before a password expires. Default: 90 days.', 'guard-dog'); ?>
                    </p>
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="guard_dog_password_expiration_warning_days">
                        <?php esc_html_e('Warning Period', '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="0"
                           max="30"
                           class="small-text" />
                    <label for="guard_dog_password_expiration_warning_days">
                        <?php esc_html_e('days before expiration', 'guard-dog'); ?>
                    </label>
                    <p class="description">
                        <?php esc_html_e('Number of days before expiration to start showing warnings. Default: 7 days.', 'guard-dog'); ?>
                    </p>
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="guard_dog_password_expiration_email_enabled">
                        <?php esc_html_e('Enable 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); ?>
                           <?php disabled(!($data['email_provider_configured'] ?? false)); ?> />
                    <label for="guard_dog_password_expiration_email_enabled">
                        <?php esc_html_e('Send email notifications for password expiration', 'guard-dog'); ?>
                    </label>
                    <?php if (!($data['email_provider_configured'] ?? false)): ?>
                        <p class="description" style="color: #d63638;">
                            <?php esc_html_e('This setting requires an email provider to be configured.', 'guard-dog'); ?>
                            <?php
                            printf(
                                esc_html__('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>
                    <?php else: ?>
                        <p class="description">
                            <?php esc_html_e('Users will receive email warnings before their password expires and a notice when it expires.', 'guard-dog'); ?>
                        </p>
                    <?php endif; ?>
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <?php esc_html_e('Email Template', 'guard-dog'); ?>
                </th>
                <td>
                    <a href="<?php echo esc_url(admin_url('admin.php?page=guard-dog-email-customizer&template_type=password-expiration')); ?>" class="button" target="_blank">
                        <?php esc_html_e('Customize Email Template', 'guard-dog'); ?>
                    </a>
                    <p class="description">
                        <?php esc_html_e('Customize the appearance and content of password expiration emails using the visual template editor.', 'guard-dog'); ?>
                    </p>
                </td>
            </tr>

            <tr>
                <th scope="row">
                    <label for="guard_dog_password_expiration_exempt_roles">
                        <?php esc_html_e('Exempt Roles (Expiration)', 'guard-dog'); ?>
                    </label>
                </th>
                <td>
                    <fieldset>
                        <?php foreach ($data['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'], $data['password_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 requirements.', 'guard-dog'); ?>
                    </p>
                </td>
            </tr>

            <!-- Manual Trigger -->
            <tr>
                <th scope="row">
                    <label><?php esc_html_e('Manual Check', 'guard-dog'); ?></label>
                </th>
                <td>
                    <button type="button" id="guard-dog-trigger-check" class="button">
                        <?php esc_html_e('Send Expiration Emails Now', 'guard-dog'); ?>
                    </button>
                    <p class="description">
                        <?php esc_html_e('Immediately check all users and send any pending expiration warning or notice emails.', 'guard-dog'); ?>
                    </p>
                    <div id="guard-dog-trigger-results" style="display: none; margin-top: 10px; padding: 10px; border-radius: 4px;"></div>
                </td>
            </tr>
        </table>
        <?php
    }

    /**
     * Render the help sidebar
     *
     * @param array $data Page data
     */
    private function render_help_sidebar(array $data): void {
        ?>
        <div class="guard-dog-card">
            <h3>
                <span class="dashicons dashicons-info"></span>
                <?php esc_html_e('User Registration Help', 'guard-dog'); ?>
            </h3>

            <div class="guard-dog-help-section">
                <h4><?php esc_html_e('Email Verification', 'guard-dog'); ?></h4>
                <p><?php esc_html_e('When enabled, new users must click a verification link in their email before they can log in. This prevents fake account registrations.', 'guard-dog'); ?></p>
            </div>

            <div class="guard-dog-help-section">
                <h4><?php esc_html_e('Password Policy', 'guard-dog'); ?></h4>
                <p><?php esc_html_e('Enforce strong passwords to protect user accounts from brute force attacks. Configure minimum length and required character types.', 'guard-dog'); ?></p>
            </div>

            <div class="guard-dog-help-section">
                <h4><?php esc_html_e('Password Expiration', 'guard-dog'); ?></h4>
                <p><?php esc_html_e('Require users to periodically change their passwords. This limits the damage if a password is compromised.', 'guard-dog'); ?></p>
            </div>

            <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('Use at least 12 character passwords', 'guard-dog'); ?></li>
                    <li><?php esc_html_e('Require multiple character types', 'guard-dog'); ?></li>
                    <li><?php esc_html_e('Block common passwords for maximum security', 'guard-dog'); ?></li>
                    <li><?php esc_html_e('Set reasonable expiration periods (60-90 days)', 'guard-dog'); ?></li>
                    <li><?php esc_html_e('Configure an email provider for email features', 'guard-dog'); ?></li>
                </ul>
            </div>
        </div>
        <?php
    }

    /**
     * Register settings
     */
    public static function register_settings(): void {
        // Email verification settings
        register_setting('guard_dog_user_registration', Guard_Dog_Email_Verification::OPTION_ENABLED, [
            'type' => 'boolean',
            'sanitize_callback' => function($input) {
                // Check if trying to enable email verification
                if (!empty($input)) {
                    // Check if email provider is configured
                    $email_provider = Guard_Dog()->features['email_provider'] ?? null;
                    if (!$email_provider || !$email_provider->is_configured()) {
                        // Email provider not configured, prevent enabling
                        add_settings_error(
                            Guard_Dog_Email_Verification::OPTION_ENABLED,
                            'email_provider_not_configured',
                            __('Email Verification cannot be enabled because no email provider is configured. Please configure an email provider in the Settings page first.', 'guard-dog'),
                            'error'
                        );
                        return false;
                    }
                }
                return !empty($input);
            },
            'default' => false,
        ]);

        register_setting('guard_dog_user_registration', Guard_Dog_Email_Verification::OPTION_EXPIRY, [
            'type' => 'integer',
            'sanitize_callback' => 'absint',
            'default' => 48,
        ]);

        register_setting('guard_dog_user_registration', Guard_Dog_Email_Verification::OPTION_BYPASS_ADMIN, [
            'type' => 'boolean',
            'sanitize_callback' => function($input) {
                return !empty($input);
            },
            'default' => true,
        ]);

        register_setting('guard_dog_user_registration', Guard_Dog_Email_Verification::OPTION_RESEND_LIMIT, [
            'type' => 'integer',
            'sanitize_callback' => 'absint',
            'default' => 3,
        ]);

        register_setting('guard_dog_user_registration', Guard_Dog_Email_Verification::OPTION_RESEND_DAILY_LIMIT, [
            'type' => 'integer',
            'sanitize_callback' => 'absint',
            'default' => 5,
        ]);

        // Password policy settings
        register_setting('guard_dog_user_registration', Guard_Dog_Password_Policy::OPTION_ENABLED, [
            'type' => 'boolean',
            'sanitize_callback' => function($input) {
                return !empty($input);
            },
            'default' => false,
        ]);

        register_setting('guard_dog_user_registration', 'guard_dog_password_min_length', [
            'type' => 'integer',
            'sanitize_callback' => 'absint',
            'default' => 12,
        ]);

        register_setting('guard_dog_user_registration', 'guard_dog_password_require_uppercase', [
            'type' => 'boolean',
            'sanitize_callback' => function($input) {
                return !empty($input);
            },
            'default' => true,
        ]);

        register_setting('guard_dog_user_registration', 'guard_dog_password_require_lowercase', [
            'type' => 'boolean',
            'sanitize_callback' => function($input) {
                return !empty($input);
            },
            'default' => true,
        ]);

        register_setting('guard_dog_user_registration', 'guard_dog_password_require_numbers', [
            'type' => 'boolean',
            'sanitize_callback' => function($input) {
                return !empty($input);
            },
            'default' => true,
        ]);

        register_setting('guard_dog_user_registration', 'guard_dog_password_require_special', [
            'type' => 'boolean',
            'sanitize_callback' => function($input) {
                return !empty($input);
            },
            'default' => true,
        ]);

        register_setting('guard_dog_user_registration', 'guard_dog_password_block_common', [
            'type' => 'boolean',
            'sanitize_callback' => function($input) {
                return !empty($input);
            },
            'default' => false,
        ]);

        register_setting('guard_dog_user_registration', 'guard_dog_password_block_username', [
            'type' => 'boolean',
            'sanitize_callback' => function($input) {
                return !empty($input);
            },
            'default' => true,
        ]);

        register_setting('guard_dog_user_registration', 'guard_dog_password_block_email', [
            'type' => 'boolean',
            'sanitize_callback' => function($input) {
                return !empty($input);
            },
            'default' => true,
        ]);

        register_setting('guard_dog_user_registration', 'guard_dog_password_reuse_limit', [
            'type' => 'integer',
            'sanitize_callback' => 'absint',
            'default' => 5,
        ]);

        register_setting('guard_dog_user_registration', 'guard_dog_password_policy_exempt_roles', [
            'type' => 'array',
            'sanitize_callback' => function($input) {
                if (!is_array($input)) {
                    return [];
                }
                return array_map('sanitize_text_field', $input);
            },
            'default' => [],
        ]);

        // Password expiration settings
        register_setting('guard_dog_user_registration', 'guard_dog_password_expiration_enabled', [
            'type' => 'boolean',
            'sanitize_callback' => function($input) {
                return !empty($input);
            },
            'default' => false,
        ]);

        register_setting('guard_dog_user_registration', 'guard_dog_password_expiration_days', [
            'type' => 'integer',
            'sanitize_callback' => function($input) {
                $value = absint($input);
                // Ensure value is between 1 and 365
                if ($value < 1) {
                    return 90; // Default
                }
                if ($value > 365) {
                    return 365; // Max
                }
                return $value;
            },
            'default' => 90,
        ]);

        register_setting('guard_dog_user_registration', 'guard_dog_password_expiration_warning_days', [
            'type' => 'integer',
            'sanitize_callback' => function($input) {
                $value = absint($input);
                // Ensure value is between 0 and 30
                if ($value < 0) {
                    return 7; // Default
                }
                if ($value > 30) {
                    return 30; // Max
                }
                return $value;
            },
            'default' => 7,
        ]);

        register_setting('guard_dog_user_registration', 'guard_dog_password_expiration_email_enabled', [
            'type' => 'boolean',
            'sanitize_callback' => function($input) {
                // Check if trying to enable email notifications
                if (!empty($input)) {
                    // Check if email provider is configured
                    $email_provider = Guard_Dog()->features['email_provider'] ?? null;
                    if (!$email_provider || !$email_provider->is_configured()) {
                        // Email provider not configured, prevent enabling
                        add_settings_error(
                            'guard_dog_password_expiration_email_enabled',
                            'email_provider_not_configured',
                            __('Password expiration emails cannot be enabled because no email provider is configured. Please configure an email provider in the Settings page first.', 'guard-dog'),
                            'error'
                        );
                        return false;
                    }
                }
                return !empty($input);
            },
            'default' => false,
        ]);


        register_setting('guard_dog_user_registration', 'guard_dog_password_expiration_exempt_roles', [
            'type' => 'array',
            'sanitize_callback' => function($input) {
                if (!is_array($input)) {
                    return [];
                }
                return array_map('sanitize_text_field', $input);
            },
            'default' => [],
        ]);
    }

} // End class Guard_Dog_User_Registration_Page

