<?php

/**
 * Guard Dog Temporary Access Page
 * 
 * Manages temporary access users that provide time-limited access to the site.
 * Includes user creation, monitoring, and management tools.
 *
 * @package GuardDog
 * @since 1.6.0
 */

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

class Guard_Dog_Temp_Access_Page {

    /**
     * Query arg used for the inner Temporary Access tabs.
     */
    private const TAB_QUERY_ARG = 'temp_access_tab';

    /**
     * @var Guard_Dog_Temp_Access The temporary access handler instance
     */
    private $temp_access_handler;

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

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

    /**
     * Constructor.
     *
     * @param Guard_Dog_Temp_Access $temp_access_handler The handler instance.
     */
    public function __construct($temp_access_handler) {
        $this->temp_access_handler = $temp_access_handler;
        $this->initialize_tabs();
        $this->determine_current_tab();
    }

    /**
     * Initialize tabs configuration
     */
    private function initialize_tabs(): void {
        $this->tabs = [
            'settings' => [
                'label' => __('Settings', 'guard-dog'),
                'icon' => 'dashicons-admin-settings'
            ],
            'create-user' => [
                'label' => __('Create User', 'guard-dog'),
                'icon' => 'dashicons-plus-alt'
            ],
            'manage-users' => [
                'label' => __('Manage Users', 'guard-dog'),
                'icon' => 'dashicons-groups'
            ]
        ];
    }

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

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

    /**
     * Get the requested Temporary Access tab from the current request.
     *
     * Supports the new dedicated query arg and the legacy nonce-protected tab
     * links for backward compatibility.
     */
    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_temp_access_tab')) {
            return sanitize_text_field(wp_unslash($_GET['tab']));
        }

        return '';
    }

    /**
     * Determine whether Temporary Access is being rendered inside Users & Sessions.
     */
    private function is_embedded_in_users_sessions(): bool {
        return isset($_GET['page']) && 'guard-dog-users-sessions' === sanitize_text_field(wp_unslash($_GET['page']));
    }

    /**
     * Build a Temporary Access tab URL for the current page context.
     */
    private function get_tab_url(string $tab_id): string {
        $args = [self::TAB_QUERY_ARG => $tab_id];

        if ($this->is_embedded_in_users_sessions()) {
            $args['users_sessions_tab'] = 'temporary_access';
        }

        return add_query_arg(
            $args,
            remove_query_arg(['tab', '_wpnonce'])
        );
    }

    /**
     * Render the Temporary Access page
     */
    public function render(): void {
        // Handle form actions first
        $this->handle_form_actions();
        
        // Prepare data for partials
        $this->prepare_page_data();
        
        // Render main page with integrated tabs
        $this->render_page_with_tabs();
    }

    /**
     * Render the page content without the outer page wrapper
     *
     * Used by the consolidated Users & Sessions page to embed
     * Temporary Access content within a tab panel. Handles form
     * actions, prepares data, and renders the internal tabbed
     * interface (settings, create user, manage users) with sidebar.
     *
     * @return void
     */
    public function render_page_content(): void {
        $this->handle_form_actions();
        $this->prepare_page_data();

        $temp_access_data = $GLOBALS['guard_dog_temp_access_data'] ?? [];
        $active_users = $temp_access_data['active_users'] ?? [];
        $expired_users = $temp_access_data['expired_users'] ?? [];

        settings_errors('guard_dog_temp_access');
        ?>
        <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_temp_access_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 foreach ($this->tabs as $tab_id => $tab_config): ?>
                    <div id="<?php echo esc_attr($tab_id); ?>"
                         class="guard-dog-tab-panel<?php echo esc_attr($this->current_tab === $tab_id ? ' active' : ''); ?>">
                        <?php $this->render_tab_content($tab_id, $temp_access_data); ?>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        <?php
    }

    /**
     * Handle form actions (user creation, deletion, etc.)
     */
    private function handle_form_actions(): void {
        // Prevent multiple processing of the same request
        static $processed = false;
        if ($processed) {
            return;
        }
        
        if (!isset($_POST['action']) || !isset($_POST['guard_dog_nonce'])) {
            return;
        }

        // Mark as processed to prevent duplicate execution
        $processed = true;

        // Verify nonce first - use WordPress recommended pattern
        if (!wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['guard_dog_nonce'])), 'guard_dog_temp_access')) {
            add_settings_error('guard_dog_temp_access', 'invalid_nonce_' . time(), __('Security check failed. Please try again.', 'guard-dog'), 'error');
            return;
        }

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

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

        switch ($action) {
            case 'create_user':
                $this->handle_create_user();
                break;
            case 'delete_user':
                $this->handle_delete_user();
                break;
            default:
                add_settings_error('guard_dog_temp_access', 'invalid_action_' . time(), __('Invalid action specified.', 'guard-dog'), 'error');
                break;
        }
    }

    /**
     * Handle user creation
     */
    private function handle_create_user(): void {
        // phpcs:disable WordPress.Security.NonceVerification.Missing
        // Nonce verification is not required in this method because:
        // 1. This method is called from handle_form_actions() which verifies the nonce at line 115
        // 2. The nonce is verified before this method is called, ensuring the request is legitimate
        // 3. All POST data is properly sanitized before use
        // 4. Required fields are validated before being accessed
        // 5. No privileged actions occur without proper authorization checks
        
        // Validate required fields
        $required_fields = ['first_name', 'email', 'expiry', 'role'];
        foreach ($required_fields as $field) {
            if (!isset($_POST[$field]) || empty(sanitize_text_field(wp_unslash($_POST[$field])))) {
                add_settings_error('guard_dog_temp_access', 'missing_field_' . $field . '_' . time(),
	                // Translators: %s is field name that is missing.
                    sprintf(esc_html__('Required field %s is missing.', 'guard-dog'), esc_html($field)), 'error');
                return;
            }
        }

        // Generate username from first and last name
        // Required fields are validated above, so these array keys are guaranteed to exist
        // phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotValidated
        // Array keys are validated in the loop above - isset() checks ensure keys exist before access
        $first_name = sanitize_text_field(wp_unslash($_POST['first_name']));
        $last_name = sanitize_text_field(wp_unslash($_POST['last_name'] ?? ''));
        // phpcs:enable WordPress.Security.ValidatedSanitizedInput.InputNotValidated
        $base_username = $this->generate_username_from_name($first_name, $last_name);

        // Prepare user data - map form fields to expected structure
        // Required fields are validated above, so these array keys are guaranteed to exist
        // phpcs:disable WordPress.Security.ValidatedSanitizedInput.InputNotValidated
        // Array keys are validated in the loop above - isset() checks ensure keys exist before access
        $user_data = [
            'username' => $base_username, // Generated username
            'email' => sanitize_email(wp_unslash($_POST['email'])),
            'expiry' => absint(wp_unslash($_POST['expiry'])),
            'role' => sanitize_text_field(wp_unslash($_POST['role'])),
            'max_logins' => absint(wp_unslash($_POST['max_logins'] ?? 10)),
            'first_name' => $first_name,
            'last_name' => $last_name,
        ];
        // phpcs:enable WordPress.Security.ValidatedSanitizedInput.InputNotValidated
        
        // Create user
        $result = $this->temp_access_handler->create_temporary_user($user_data);

        if (is_wp_error($result)) {
            add_settings_error('guard_dog_temp_access', 'user_create_failed_' . time(), $result->get_error_message(), 'error');
        } else {
            add_settings_error('guard_dog_temp_access', 'user_create_success_' . time(), 
                sprintf(
                    // Translators: %1$s is the username of the temporary user, %2$s is the access URL for the temporary user.
                    __('Temporary user "%1$s" created successfully. Access URL: %2$s', 'guard-dog'), 
                    $result['username'], 
                    $result['url']
                ), 'success');
        }
        // phpcs:enable WordPress.Security.NonceVerification.Missing
    }

    /**
     * Handle user deletion
     */
    private function handle_delete_user(): void {
        // phpcs:disable WordPress.Security.NonceVerification.Missing
        // Nonce verification is not required in this method because:
        // 1. This method is called from handle_form_actions() which verifies the nonce at line 115
        // 2. The nonce is verified before this method is called, ensuring the request is legitimate
        // 3. All POST data is properly sanitized before use
        // 4. Required fields are validated before being accessed
        // 5. No privileged actions occur without proper authorization checks
        
        if (!isset($_POST['user_id']) || empty($_POST['user_id'])) {
            add_settings_error('guard_dog_temp_access', 'missing_user_id_' . time(), __('User ID is required for deletion.', 'guard-dog'), 'error');
            // phpcs:enable WordPress.Security.NonceVerification.Missing
            return;
        }

        $user_id = intval(sanitize_text_field(wp_unslash($_POST['user_id'])));
        // phpcs:enable WordPress.Security.NonceVerification.Missing
        
        if ($this->temp_access_handler->delete_temporary_user($user_id)) {
            add_settings_error('guard_dog_temp_access', 'user_delete_success_' . time(), __('Temporary user deleted successfully.', 'guard-dog'), 'success');
        } else {
            add_settings_error('guard_dog_temp_access', 'user_delete_failed_' . time(), __('Failed to delete temporary user.', 'guard-dog'), 'error');
        }
    }

    /**
     * Prepare data for page partials
     */
    private function prepare_page_data(): void {
        // Get temporary access data
        $temp_users = $this->temp_access_handler->get_temporary_users();
        
        // Separate active and expired users
        $active_users = [];
        $expired_users = [];
        $current_time = time();
        
        foreach ($temp_users as $user) {
            $expiry_time = get_user_meta($user['id'], Guard_Dog_Temp_Access::USER_META_EXPIRY, true);
            $login_count = get_user_meta($user['id'], Guard_Dog_Temp_Access::USER_META_LOGIN_COUNT, true);
            $max_logins = get_user_meta($user['id'], Guard_Dog_Temp_Access::USER_META_MAX_LOGINS, true);
            
            $is_expired = $expiry_time && $expiry_time < $current_time;
            $is_overused = $max_logins > 0 && $login_count >= $max_logins;
            
            if (!$is_expired && !$is_overused) {
                $active_users[] = $user;
            } else {
                $expired_users[] = $user;
            }
        }

        // Pass data to partials via global variables
        $GLOBALS['guard_dog_temp_access_data'] = [
            'temp_users' => $temp_users,
            'active_users' => $active_users,
            'expired_users' => $expired_users,
        ];
    }

    /**
     * Render the page with integrated tabbed interface
     */
    private function render_page_with_tabs(): void {
        // Get data from global variables
        $temp_access_data = $GLOBALS['guard_dog_temp_access_data'] ?? [];
        $temp_users = $temp_access_data['temp_users'] ?? [];
        $active_users = $temp_access_data['active_users'] ?? [];
        $expired_users = $temp_access_data['expired_users'] ?? [];
        
        ?>
        <div class="wrap guard-dog-admin">
            <h1 class="guard-dog-page-title">
                <span class="dashicons dashicons-clock"></span>
                <?php esc_html_e('Temporary Access Management', 'guard-dog'); ?>
            </h1>
            <p class="guard-dog-page-description">
                <?php esc_html_e('Create temporary WordPress users with time-limited access for developers, editors, or support staff. Users are automatically deleted when they expire.', 'guard-dog'); ?>
            </p>

            <?php 
            // Display settings messages (success/error notifications)
            settings_errors('guard_dog_temp_access');
            ?>

            <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_temp_access_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 foreach ($this->tabs as $tab_id => $tab_config): ?>
                                <div id="<?php echo esc_attr($tab_id); ?>" 
                                     class="guard-dog-tab-panel<?php echo esc_attr($this->current_tab === $tab_id ? ' active' : ''); ?>">
                                    <?php $this->render_tab_content($tab_id, $temp_access_data); ?>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>

                <div class="guard-dog-sidebar">
                            <?php $this->render_usage_stats($active_users, $expired_users); ?>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Render content for a specific tab
     *
     * @param string $tab_id The tab identifier
     * @param array $data The page data
     */
    private function render_tab_content(string $tab_id, array $data): void {
        switch ($tab_id) {
            case 'settings':
                $this->render_settings_tab($data);
                break;
            case 'create-user':
                $this->render_create_user_tab($data);
                break;
            case 'manage-users':
                $this->render_manage_users_tab($data);
                break;
            default:
                ?>
                <p><?php esc_html_e('Invalid tab selected.', 'guard-dog'); ?></p>
                <?php
                break;
        }
    }

    /**
     * Render the settings tab content
     *
     * @param array $data The page data
     */
    private function render_settings_tab(array $data): void {
        ?>
        <h3>
            <span class="dashicons dashicons-admin-settings"></span>
            <?php esc_html_e('Temporary Access Settings', 'guard-dog'); ?>
        </h3>

        <p><?php esc_html_e('Configure default settings for temporary user creation and management.', 'guard-dog'); ?></p>

        <form method="post" action="options.php" class="guard-dog-settings-form">
            <?php 
            // Add WordPress Settings API fields
            settings_fields('guard_dog_temp_access');
            ?>

            <div class="guard-dog-form-section">
                <table class="guard-dog-form-table">
                <tr>
                    <th><?php esc_html_e('Default Role', 'guard-dog'); ?></th>
                    <td>
                        <select name="guard_dog_temp_access_default_role">
                            <?php
                            $roles = wp_roles()->get_names();
                            $selected_role = get_option('guard_dog_temp_access_default_role', 'administrator');
                            foreach ($roles as $role_key => $role_name) {
                                printf('<option value="%s" %s>%s</option>', 
                                    esc_attr($role_key), 
                                    selected($selected_role, $role_key, false), 
                                    esc_html($role_name)
                                );
                            }
                            ?>
                        </select>
                        <p class="description"><?php esc_html_e('Default role assigned to new temporary users.', 'guard-dog'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Default Expiry', 'guard-dog'); ?></th>
                    <td>
                        <input type="number" name="guard_dog_temp_access_default_expiry" value="<?php echo esc_attr(get_option('guard_dog_temp_access_default_expiry', 7)); ?>" min="1" max="365" />
                        <span><?php esc_html_e('days', 'guard-dog'); ?></span>
                        <p class="description"><?php esc_html_e('Default number of days before temporary users expire.', 'guard-dog'); ?></p>
                    </td>
                </tr>
                <tr>
                    <th><?php esc_html_e('Max Logins', 'guard-dog'); ?></th>
                    <td>
                        <input type="number" name="guard_dog_temp_access_max_logins" value="<?php echo esc_attr(get_option('guard_dog_temp_access_max_logins', 10)); ?>" min="1" max="1000" />
                        <p class="description"><?php esc_html_e('Maximum number of logins allowed per temporary user.', 'guard-dog'); ?></p>
                    </td>
                </tr>
            </table>
            
            <p class="submit">
                <input type="submit" name="submit" class="button-primary" value="<?php esc_attr_e('Save Temporary Access Settings', 'guard-dog'); ?>">
            </p>
            </div>
        </form>
        <?php
    }

    /**
     * Render the create user tab content
     *
     * @param array $data The page data
     */
    private function render_create_user_tab(array $data): void {
        ?>
        <h3>
            <span class="dashicons dashicons-plus-alt"></span>
            <?php esc_html_e('Create New Temporary User', 'guard-dog'); ?>
        </h3>

        <?php $this->render_create_user_card(); ?>
        <?php
    }

    /**
     * Render the manage users tab content
     *
     * @param array $data The page data
     */
    private function render_manage_users_tab(array $data): void {
        $active_users = $data['active_users'] ?? [];
        $expired_users = $data['expired_users'] ?? [];
        
        ?>
        <h3>
            <span class="dashicons dashicons-groups"></span>
            <?php esc_html_e('Manage Temporary Users', 'guard-dog'); ?>
        </h3>

        <?php if (!empty($active_users)): ?>
            <?php $this->render_active_users_card($active_users); ?>
        <?php else: ?>
            <div class="guard-dog-notice-info">
                <p>
                    <?php esc_html_e('No active temporary users found.', 'guard-dog'); ?>
                    <a href="<?php echo esc_url($this->get_tab_url('create-user')); ?>" class="guard-dog-tab-link" data-tab="create-user" data-storage-key="guard_dog_temp_access_active_tab" data-query-param="<?php echo esc_attr(self::TAB_QUERY_ARG); ?>">
                        <?php esc_html_e('Create your first temporary user', 'guard-dog'); ?>
                    </a>
                </p>
            </div>
        <?php endif; ?>

        <?php if (!empty($expired_users)): ?>
            <div class="guard-dog-expired-users-section">
                <?php $this->render_expired_users_card($expired_users); ?>
            </div>
        <?php endif; ?>
        <?php
    }

    /**
     * Register settings
     */
    public static function register_settings(): void {
        // Register temporary access settings
        register_setting('guard_dog_temp_access', 'guard_dog_temp_access_default_role', [
            'type' => 'string',
            'sanitize_callback' => 'sanitize_text_field',
            'default' => 'administrator',
        ]);
        
        register_setting('guard_dog_temp_access', 'guard_dog_temp_access_default_expiry', [
            'type' => 'integer',
            'sanitize_callback' => function($input) {
                return max(1, min(365, intval($input))); // Between 1 and 365 days
            },
            'default' => 7,
        ]);
        
        register_setting('guard_dog_temp_access', 'guard_dog_temp_access_max_logins', [
            'type' => 'integer',
            'sanitize_callback' => function($input) {
                return max(1, min(1000, intval($input))); // Between 1 and 1000 logins
            },
            'default' => 10,
        ]);
    }



    /**
     * Add settings sections and fields (legacy - not used with custom interface)
     */
    public static function add_settings_sections(): void {
        // Add main temporary access settings section
        add_settings_section(
            'guard_dog_temp_access_main',
            __('Temporary Access Settings', 'guard-dog'),
            [self::class, 'render_section_description'],
            'guard_dog_temp_access'
        );

        // Add default role field
        add_settings_field(
            'guard_dog_temp_access_default_role',
            __('Default Role', 'guard-dog'),
            [self::class, 'render_default_role_field'],
            'guard_dog_temp_access',
            'guard_dog_temp_access_main'
        );

        // Add default expiry field
        add_settings_field(
            'guard_dog_temp_access_default_expiry',
            __('Default Expiry (Days)', 'guard-dog'),
            [self::class, 'render_default_expiry_field'],
            'guard_dog_temp_access',
            'guard_dog_temp_access_main'
        );

        // Add max logins field
        add_settings_field(
            'guard_dog_temp_access_max_logins',
            __('Maximum Logins', 'guard-dog'),
            [self::class, 'render_max_logins_field'],
            'guard_dog_temp_access',
            'guard_dog_temp_access_main'
        );
    }

    /**
     * Render section description
     */
    public static function render_section_description(): void {
        ?>
        <p><?php esc_html_e('Configure temporary access settings for creating time-limited user accounts.', 'guard-dog'); ?></p>
        <?php
    }

    /**
     * Render default role field
     */
    public static function render_default_role_field(): void {
        $default_role = get_option('guard_dog_temp_access_default_role', 'administrator');
        
        $roles = wp_roles()->get_names();
        ?>
        <select name="guard_dog_temp_access_default_role">
            <?php foreach ($roles as $role_value => $role_name): ?>
                <option value="<?php echo esc_attr($role_value); ?>"<?php echo selected($default_role, $role_value, false); ?>><?php echo esc_html($role_name); ?></option>
            <?php endforeach; ?>
        </select>
        
        <p class="description"><?php esc_html_e('Default role assigned to temporary users.', 'guard-dog'); ?></p>
        <?php
    }

    /**
     * Render default expiry field
     */
    public static function render_default_expiry_field(): void {
        $default_expiry = get_option('guard_dog_temp_access_default_expiry', 7);
        ?>
        <input type="number" name="guard_dog_temp_access_default_expiry" value="<?php echo esc_attr($default_expiry); ?>" min="1" max="365" class="small-text" />
        <p class="description"><?php esc_html_e('Default number of days before temporary access expires (1-365).', 'guard-dog'); ?></p>
        <?php
    }

    /**
     * Render max logins field
     */
    public static function render_max_logins_field(): void {
        $max_logins = get_option('guard_dog_temp_access_max_logins', 10);
        ?>
        <input type="number" name="guard_dog_temp_access_max_logins" value="<?php echo esc_attr($max_logins); ?>" min="1" max="1000" class="small-text" />
        <p class="description"><?php esc_html_e('Maximum number of logins allowed for temporary users (1-1000).', 'guard-dog'); ?></p>
        <?php
    }

    /**
     * Render usage statistics
     *
     * @param array $active_users The active users
     * @param array $expired_users The expired users
     */
    private function render_usage_stats(array $active_users, array $expired_users): void {
        ?>
        <div class="guard-dog-card">
            <h3><?php esc_html_e('Usage Statistics', 'guard-dog'); ?></h3>
            
            <div class="guard-dog-stats-overview">
                <div class="guard-dog-stat-item">
                    <div class="guard-dog-stat-number"><?php echo count($active_users); ?></div>
                    <div class="guard-dog-stat-label"><?php esc_html_e('Active Users', 'guard-dog'); ?></div>
                </div>
                
                <div class="guard-dog-stat-item">
                    <div class="guard-dog-stat-number"><?php echo count($expired_users); ?></div>
                    <div class="guard-dog-stat-label"><?php esc_html_e('Expired Users', 'guard-dog'); ?></div>
                </div>
                
                <div class="guard-dog-stat-item">
                    <div class="guard-dog-stat-number"><?php echo count($active_users) + count($expired_users); ?></div>
                    <div class="guard-dog-stat-label"><?php esc_html_e('Total Created', 'guard-dog'); ?></div>
                </div>
            </div>
            
            <?php if (!empty($active_users)): ?>
            <div class="guard-dog-stats-breakdown">
                <h4><?php esc_html_e('Active Users by Role', 'guard-dog'); ?></h4>
                
                <?php
                $role_counts = [];
                foreach ($active_users as $user) {
                    $role = $user['role'];
                    $role_counts[$role] = ($role_counts[$role] ?? 0) + 1;
                }
                ?>
                
                <div class="guard-dog-stats-chart">
                    <?php foreach ($role_counts as $role => $count): ?>
                        <div class="guard-dog-stat-row">
                            <span class="guard-dog-stat-type"><?php echo esc_html(ucfirst($role)); ?></span>
                            <span class="guard-dog-stat-count"><?php echo esc_html($count); ?></span>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            <?php endif; ?>
            
            <div class="guard-dog-stats-summary">
                <h4><?php esc_html_e('Quick Info', 'guard-dog'); ?></h4>
                
                <div class="guard-dog-info-list">
                    <div class="guard-dog-info-item">
                        <span class="guard-dog-info-label"><?php esc_html_e('Feature Status:', 'guard-dog'); ?></span>
                        <span class="guard-dog-info-value guard-dog-status-active"><?php esc_html_e('Enabled', 'guard-dog'); ?></span>
                    </div>
                    
                    <div class="guard-dog-info-item">
                        <span class="guard-dog-info-label"><?php esc_html_e('Auto Cleanup:', 'guard-dog'); ?></span>
                        <span class="guard-dog-info-value"><?php esc_html_e('Enabled', 'guard-dog'); ?></span>
                    </div>
                    
                    <div class="guard-dog-info-item">
                        <span class="guard-dog-info-label"><?php esc_html_e('Max Duration:', 'guard-dog'); ?></span>
                        <span class="guard-dog-info-value"><?php esc_html_e('1 Month', 'guard-dog'); ?></span>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Render create user card
     */
    private function render_create_user_card(): void {
        $default_role = get_option('guard_dog_temp_access_default_role', 'administrator');
        $default_expiry = get_option('guard_dog_temp_access_default_expiry', 7);
        $max_logins = get_option('guard_dog_temp_access_max_logins', 10);
        $roles = wp_roles()->get_names();
        ?>
        <form method="post" action="" class="guard-dog-create-user-form">
            <?php wp_nonce_field('guard_dog_temp_access', 'guard_dog_nonce'); ?>
            <input type="hidden" name="action" value="create_user" />

            <table class="form-table">
                <tr>
                    <th scope="row">
                        <label for="first_name"><?php esc_html_e('First Name', 'guard-dog'); ?></label>
                    </th>
                    <td>
                        <input type="text" id="first_name" name="first_name" class="regular-text" required />
                        <p class="description"><?php esc_html_e('First name for the temporary user. Username will be generated automatically.', 'guard-dog'); ?></p>
                    </td>
                </tr>

                <tr>
                    <th scope="row">
                        <label for="last_name"><?php esc_html_e('Last Name', 'guard-dog'); ?></label>
                    </th>
                    <td>
                        <input type="text" id="last_name" name="last_name" class="regular-text" />
                        <p class="description"><?php esc_html_e('Last name for the temporary user (optional).', 'guard-dog'); ?></p>
                    </td>
                </tr>

                <tr>
                    <th scope="row">
                        <label for="generated_username"><?php esc_html_e('Generated Username', 'guard-dog'); ?></label>
                    </th>
                    <td>
                        <input type="text" id="generated_username" class="regular-text guard-dog-generated-username" readonly />
                        <p class="description"><?php esc_html_e('This username will be automatically generated and is unique.', 'guard-dog'); ?></p>
                    </td>
                </tr>

                <tr>
                    <th scope="row">
                        <label for="email"><?php esc_html_e('Email', 'guard-dog'); ?></label>
                    </th>
                    <td>
                        <input type="email" id="email" name="email" class="regular-text" required />
                        <p class="description"><?php esc_html_e('Email address for the temporary user. This will be used for the access link.', 'guard-dog'); ?></p>
                    </td>
                </tr>

                <tr>
                    <th scope="row">
                        <label for="role"><?php esc_html_e('Role', 'guard-dog'); ?></label>
                    </th>
                    <td>
                        <select id="role" name="role">
                            <?php foreach ($roles as $role_value => $role_name): ?>
                                <option value="<?php echo esc_attr($role_value); ?>" <?php selected($default_role, $role_value); ?>>
                                    <?php echo esc_html($role_name); ?>
                                </option>
                            <?php endforeach; ?>
                        </select>
                        <p class="description"><?php esc_html_e('Role to assign to the temporary user.', 'guard-dog'); ?></p>
                    </td>
                </tr>

                <tr>
                    <th scope="row">
                        <label for="expiry"><?php esc_html_e('Expiry (Days)', 'guard-dog'); ?></label>
                    </th>
                    <td>
                        <input type="number" id="expiry" name="expiry" value="<?php echo esc_attr($default_expiry); ?>" min="1" max="365" class="small-text" />
                        <p class="description"><?php esc_html_e('Number of days before the account expires (1-365).', 'guard-dog'); ?></p>
                    </td>
                </tr>

                <tr>
                    <th scope="row">
                        <label for="max_logins"><?php esc_html_e('Max Logins', 'guard-dog'); ?></label>
                    </th>
                    <td>
                        <input type="number" id="max_logins" name="max_logins" value="<?php echo esc_attr($max_logins); ?>" min="1" max="1000" class="small-text" />
                        <p class="description"><?php esc_html_e('Maximum number of logins allowed (1-1000).', 'guard-dog'); ?></p>
                    </td>
                </tr>
            </table>

            <?php submit_button(__('Create Temporary User', 'guard-dog')); ?>
        </form>
        <?php
    }

    /**
     * Render active users card
     *
     * @param array $active_users The active users
     */
    private function render_active_users_card(array $active_users): void {
        ?>
        <div class="guard-dog-users-table-wrapper">
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <th scope="col"><?php esc_html_e('Username', 'guard-dog'); ?></th>
                        <th scope="col"><?php esc_html_e('Email', 'guard-dog'); ?></th>
                        <th scope="col"><?php esc_html_e('Role', 'guard-dog'); ?></th>
                        <th scope="col"><?php esc_html_e('Access Link', 'guard-dog'); ?></th>
                        <th scope="col"><?php esc_html_e('Expires', 'guard-dog'); ?></th>
                        <th scope="col"><?php esc_html_e('Logins Used', 'guard-dog'); ?></th>
                        <th scope="col"><?php esc_html_e('Actions', 'guard-dog'); ?></th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($active_users as $user): ?>
                        <tr>
                            <td><?php echo esc_html($user['username']); ?></td>
                            <td><?php echo esc_html($user['email']); ?></td>
                            <td><?php echo esc_html(ucfirst($user['role'])); ?></td>
                            <td>
                                <?php if (!empty($user['login_url'])): ?>
                                    <div class="guard-dog-access-link-container">
                                        <input type="text"
                                               class="guard-dog-access-link"
                                               value="<?php echo esc_attr($user['login_url']); ?>"
                                               readonly
                                               data-user="<?php echo esc_attr($user['username']); ?>" />
                                        <button type="button"
                                                class="button button-small guard-dog-copy-link"
                                                data-link="<?php echo esc_attr($user['login_url']); ?>"
                                                title="<?php esc_attr_e('Copy access link to clipboard', 'guard-dog'); ?>">
                                            <span class="dashicons dashicons-clipboard"></span>
                                        </button>
                                        <a href="<?php echo esc_url($user['login_url']); ?>"
                                           target="_blank"
                                           class="button button-small guard-dog-test-link"
                                           title="<?php esc_attr_e('Test access link', 'guard-dog'); ?>">
                                            <span class="dashicons dashicons-external"></span>
                                        </a>
                                    </div>
                                <?php else: ?>
                                    <span class="description"><?php esc_html_e('Shown only when the user is created.', 'guard-dog'); ?></span>
                                <?php endif; ?>
                            </td>
                            <td><?php echo esc_html(wp_date('Y-m-d H:i:s', strtotime($user['expires_at']))); ?></td>
                            <td><?php echo esc_html($user['logins_used'] . '/' . $user['max_logins']); ?></td>
                            <td>
                                <form method="post" action="" class="guard-dog-inline-form">
                                    <?php wp_nonce_field('guard_dog_temp_access', 'guard_dog_nonce'); ?>
                                    <input type="hidden" name="action" value="delete_user" />
                                    <input type="hidden" name="user_id" value="<?php echo esc_attr($user['id']); ?>" />
                                    <button type="submit" class="button button-small button-link-delete guard-dog-revoke-user-btn">
                                        <?php esc_html_e('Revoke', 'guard-dog'); ?>
                                    </button>
                                </form>
                            </td>
                        </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php
    }

    /**
     * Render expired users card
     *
     * @param array $expired_users The expired users
     */
    private function render_expired_users_card(array $expired_users): void {
        ?>
        <div class="guard-dog-card">
            <h3><?php esc_html_e('Expired Temporary Users', 'guard-dog'); ?></h3>
            
            <div class="guard-dog-users-table-wrapper">
                <table class="wp-list-table widefat fixed striped">
                    <thead>
                        <tr>
                            <th scope="col"><?php esc_html_e('Username', 'guard-dog'); ?></th>
                            <th scope="col"><?php esc_html_e('Email', 'guard-dog'); ?></th>
                            <th scope="col"><?php esc_html_e('Role', 'guard-dog'); ?></th>
                            <th scope="col"><?php esc_html_e('Expired', 'guard-dog'); ?></th>
                            <th scope="col"><?php esc_html_e('Logins Used', 'guard-dog'); ?></th>
                            <th scope="col"><?php esc_html_e('Actions', 'guard-dog'); ?></th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($expired_users as $user): ?>
                            <tr>
                                <td><?php echo esc_html($user['username']); ?></td>
                                <td><?php echo esc_html($user['email']); ?></td>
                                <td><?php echo esc_html(ucfirst($user['role'])); ?></td>
                                <td><?php echo esc_html(wp_date('Y-m-d H:i:s', strtotime($user['expires_at']))); ?></td>
                                <td><?php echo esc_html($user['logins_used'] . '/' . $user['max_logins']); ?></td>
                                <td>
                                    <form method="post" action="" class="guard-dog-inline-form">
                                        <?php wp_nonce_field('guard_dog_delete_temp_user', 'guard_dog_delete_temp_user_nonce'); ?>
                                        <input type="hidden" name="delete_user_id" value="<?php echo esc_attr($user['id']); ?>" />
                                        <button type="submit" class="button button-small button-link-delete guard-dog-delete-expired-user-btn">
                                            <?php esc_html_e('Delete', 'guard-dog'); ?>
                                        </button>
                                    </form>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        </div>
        <?php
    }

    /**
     * Generate a unique username from first and last name
     *
     * @param string $first_name The first name
     * @param string $last_name The last name
     * @return string Generated username
     */
    private function generate_username_from_name(string $first_name, string $last_name): string {
        // Create base username from first and last name
        $base_username = sanitize_user($first_name . ($last_name ? '.' . $last_name : ''));
        
        // Remove any non-alphanumeric characters except dots and hyphens
        $base_username = preg_replace('/[^a-zA-Z0-9.-]/', '', $base_username);
        
        // Convert to lowercase
        $base_username = strtolower($base_username);
        
        // Ensure it's not empty
        if (empty($base_username)) {
            $base_username = 'tempuser';
        }
        
        // Check if username exists and add number if needed
        $username = $base_username;
        $counter = 1;
        
        while (username_exists($username)) {
            $username = $base_username . $counter;
            $counter++;
            
            // Prevent infinite loop
            if ($counter > 100) {
                $username = $base_username . time();
                break;
            }
        }
        
        return $username;
    }

}
