<?php

/**
 * Guard Dog Authentication Page
 *
 * Consolidated admin page for login security and CAPTCHA settings.
 * Uses composition to delegate tab rendering to the existing
 * Login Security and CAPTCHA page classes.
 *
 * @package GuardDog
 * @since 2.0.0
 */

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

class Guard_Dog_Authentication_Page {

    /**
     * Query arg used for the Authentication tabs.
     */
    private const TAB_QUERY_ARG = 'authentication_tab';

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

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

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

    /**
     * Login Security page instance for delegation
     * @var Guard_Dog_Login_Security_Page
     */
    private $login_security_page;

    /**
     * CAPTCHA page instance for delegation
     * @var Guard_Dog_Captcha_Page
     */
    private $captcha_page;

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

    /**
     * Initialize tabs configuration
     *
     * All non-CAPTCHA tabs originate from Login Security and are rendered
     * through the legacy delegate page. The CAPTCHA tab is rendered by the
     * dedicated CAPTCHA page class.
     *
     * @return void
     */
    private function initialize_tabs(): void {
        $this->tabs = [
            'custom-url' => [
                'label' => __('Custom URL', 'guard-dog'),
                'icon'  => 'dashicons-admin-links',
                'group' => 'login_security',
            ],
            'login-attempts' => [
                'label' => __('Login Attempts', 'guard-dog'),
                'icon'  => 'dashicons-shield',
                'group' => 'login_security',
            ],
            'captcha' => [
                'label' => __('CAPTCHA', 'guard-dog'),
                'icon'  => 'dashicons-shield-alt',
                'group' => 'captcha',
            ],
            'two-factor' => [
                'label' => __('Two-Factor Auth', 'guard-dog'),
                'icon'  => 'dashicons-smartphone',
                'group' => 'login_security',
            ],
            'passkeys' => [
                'label' => __('Passkeys', 'guard-dog'),
                'icon'  => 'dashicons-admin-network',
                'group' => 'login_security',
            ],
            'social-login' => [
                'label' => __('Social Login', 'guard-dog'),
                'icon'  => 'dashicons-share',
                'group' => 'login_security',
            ],
            'login-form' => [
                'label' => __('Frontend Login Form', 'guard-dog'),
                'icon'  => 'dashicons-feedback',
                'group' => 'login_security',
            ],
        ];
    }

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

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

    /**
     * Get the requested Authentication tab from the current request.
     *
     * Supports the new dedicated query arg and the legacy nonce-protected tab
     * links so older URLs 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_authentication_tab')) {
            return sanitize_text_field(wp_unslash($_GET['tab']));
        }

        return '';
    }

    /**
     * Build a tab URL for the consolidated Authentication page.
     */
    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 Authentication page
     *
     * @return void
     */
    public function render(): void {
        $this->login_security_page->prepare_page_data();

        $login_security_data = $GLOBALS['guard_dog_login_security_data'] ?? [];

        ?>
        <div class="wrap guard-dog-admin">
            <h1 class="guard-dog-page-title">
                <span class="dashicons dashicons-lock"></span>
                <?php esc_html_e('Authentication', 'guard-dog'); ?>
            </h1>

            <p class="guard-dog-page-subtitle">
                <?php esc_html_e('Configure login security, CAPTCHA protection, and authentication methods to secure your WordPress site.', 'guard-dog'); ?>
            </p>

            <?php
            settings_errors('guard_dog_login_security');
            settings_errors('guard_dog_captcha');
            ?>

            <div class="guard-dog-admin-grid">
                <div class="guard-dog-main-content">
                    <?php $this->render_tabbed_interface($login_security_data); ?>
                </div>

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

    /**
     * Render the complete tabbed interface including navigation and all tab panels
     *
     * @param array $data Login security page data
     * @return void
     */
    private function render_tabbed_interface(array $data): void {
        ?>
        <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_authentication_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_login_security_form($data); ?>
                <?php $this->render_captcha_form(); ?>
            </div>
        </div>
        <?php
    }

    /**
     * Render the login security form wrapping tabs 1,2,4,5,6
     *
     * All login-security tabs share one form with settings_fields('guard_dog_login_security').
     * Every tab panel is rendered in the DOM (hidden by CSS when inactive) so that
     * all fields are submitted together.
     *
     * @param array $data Login security page data from globals
     * @return void
     */
    private function render_login_security_form(array $data): void {
        $login_security_tabs = array_filter($this->tabs, function (array $tab): bool {
            return $tab['group'] === 'login_security';
        });

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

            <?php foreach ($login_security_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_login_security_tab_content($tab_id, $data); ?>
                </div>
            <?php endforeach; ?>

            <p class="submit">
                <input type="submit" name="submit" class="button-primary" value="<?php esc_attr_e('Save Authentication Settings', 'guard-dog'); ?>">
            </p>
        </form>
        <?php
    }

    /**
     * Render the CAPTCHA form as a standalone form for the captcha tab
     *
     * The CAPTCHA tab uses its own settings group ('guard_dog_captcha')
     * and is wrapped in a separate form.
     *
     * @return void
     */
    private function render_captcha_form(): void {
        ?>
        <div id="captcha"
             class="guard-dog-tab-panel<?php echo esc_attr($this->current_tab === 'captcha' ? ' active' : ''); ?>">
            <form method="post" action="options.php" class="guard-dog-settings-form">
                <?php settings_fields('guard_dog_captcha'); ?>

                <?php $this->captcha_page->render_captcha_form_content(); ?>

                <p class="submit">
                    <input type="submit" name="submit" class="button-primary" value="<?php esc_attr_e('Save Authentication Settings', 'guard-dog'); ?>">
                </p>
            </form>
        </div>
        <?php
    }

    /**
     * Delegate rendering of a login-security tab to the Login Security page
     *
     * @param string $tab_id The tab identifier
     * @param array  $data   The prepared page data
     * @return void
     */
    private function render_login_security_tab_content(string $tab_id, array $data): void {
        switch ($tab_id) {
            case 'custom-url':
                $this->login_security_page->render_custom_url_tab($data);
                break;
            case 'login-attempts':
                $this->login_security_page->render_login_attempts_tab($data);
                break;
            case 'two-factor':
                $this->login_security_page->render_two_factor_tab($data);
                break;
            case 'passkeys':
                $this->login_security_page->render_passkeys_tab($data);
                break;
            case 'social-login':
                $this->login_security_page->render_social_login_tab($data);
                break;
            case 'login-form':
                $this->login_security_page->render_login_form_tab($data);
                break;
            default:
                ?>
                <p><?php esc_html_e('Invalid tab selected.', 'guard-dog'); ?></p>
                <?php
                break;
        }
    }
}
