<?php
/**
 * 2FA Login Form Partial
 *
 * This template is loaded via Guard_Dog_View_Loader::render_partial() which uses
 * extract() to inject variables from the calling context.
 *
 * @package GuardDog
 * @since 1.8.0
 *
 * @var int                      $user_id          The ID of the user attempting to log in.
 * @var string                   $username         The username of the user attempting to log in.
 * @var string                   $redirect_to      The URL to redirect to after successful login.
 * @var bool                     $rememberme       Whether the "Remember Me" option was selected.
 * @var string                   $flow_token       Random token bound to the pending login transient.
 * @var string                   $captcha_token    The CAPTCHA token from the initial login form (if any).
 * @var string                   $captcha_provider The CAPTCHA provider type (recaptcha, hcaptcha, turnstile).
 * @var Guard_Dog_Two_Factor_Auth $guard_dog_this   The Two Factor Auth instance (passed as 'this' and renamed).
 */

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

// phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
// These are local variables in a template file, not global variables
// The Plugin Checker incorrectly flags local template variables as globals
// These variables are scoped to this template file and do not pollute the global namespace

// Get recovery code count for the user
$encrypted_codes = get_user_meta($user_id, Guard_Dog_Two_Factor_Auth::USER_META_RECOVERY_CODES, true);
$recovery_codes = $guard_dog_this->decode_recovery_codes($encrypted_codes);
$recovery_count = count($recovery_codes);

// Check which 2FA methods the user has enabled
$email_2fa_enabled = get_option('guard_dog_email_2fa_enabled', false);
$user_has_email_2fa = false;
if ($email_2fa_enabled && function_exists('Guard_Dog') && isset(Guard_Dog()->features['email_two_factor_auth'])) {
    $user_has_email_2fa = Guard_Dog()->features['email_two_factor_auth']->is_email_2fa_enabled_for_user($user_id);
}

// Check if user has app-based 2FA enabled
$user_has_app_2fa = (bool) get_user_meta($user_id, '_guard_dog_2fa_enabled', true) && 
                     !empty(get_user_meta($user_id, '_guard_dog_2fa_secret', true));

$error_message = '';
// phpcs:disable WordPress.Security.NonceVerification.Recommended
// Nonce verification is not required in this context:
// 1. This is a view partial that only reads GET parameters for display purposes
// 2. The GET parameter is used only to display error messages, not to process form data
// 3. No privileged actions or data modifications occur based on this GET parameter
// 4. All input is properly sanitized before use
if (isset($_GET['guard_dog_2fa_error'])) {
    switch (sanitize_text_field(wp_unslash($_GET['guard_dog_2fa_error']))) {
        case 'access_denied':
            $error_message = esc_html__('Access denied. This username or IP address has been blocked from logging in.', 'guard-dog');
            break;
        case 'guard_dog_2fa_invalid_code':
        case 'invalid_code':
            $error_message = '<strong>' . esc_html__('ERROR', 'guard-dog') . ':</strong> ' .
                esc_html__('The verification code or recovery code you entered is incorrect. Please try again.', 'guard-dog') .
                '<br><small>' . esc_html__('If you are using a recovery code, remember each code can only be used once.', 'guard-dog') . '</small>';
            break;
        default:
            $error_message = '';
    }
}
// phpcs:enable WordPress.Security.NonceVerification.Recommended

$show_recovery = false;
// phpcs:disable WordPress.Security.NonceVerification.Missing
// Nonce verification is not required in this context:
// 1. This is a view partial that only reads POST data for display state determination
// 2. The POST data is used only to determine which form to show (recovery vs. regular), not to process form submissions
// 3. Actual form processing with nonce verification happens in the main 2FA handler class (Guard_Dog_Two_Factor_Auth)
// 4. This view is called by the handler after it has already verified nonces and processed the form
// 5. All input is properly sanitized before use
// 6. No privileged actions or data modifications occur based on this POST data check
if (isset($_POST['guard_dog_2fa_code']) && isset($_POST['guard_dog_2fa_interim_login']) && sanitize_text_field(wp_unslash($_POST['guard_dog_2fa_interim_login'])) === '1') {
    // If the user submitted the recovery form, show it again
    if (isset($_POST['guard_dog_2fa_recovery_code']) && !empty(sanitize_text_field(wp_unslash($_POST['guard_dog_2fa_recovery_code'])))) {
        $show_recovery = true;
    }
}
// phpcs:enable WordPress.Security.NonceVerification.Missing

$main_message = '';
if (!empty($error_message)) {
    $main_message = '<p class="message error-message">' . $error_message . '</p>';
} else {
    if ($user_has_email_2fa && $user_has_app_2fa) {
        $main_message = '<p class="message">' . esc_html__('Please choose your two-factor authentication method and enter the verification code.', 'guard-dog') . '</p>';
    } elseif ($user_has_email_2fa) {
        $main_message = '<p class="message">' . esc_html__('Please enter the verification code sent to your email address.', 'guard-dog') . '</p>';
    } elseif ($user_has_app_2fa) {
        $main_message = '<p class="message">' . esc_html__('Please enter the two-factor authentication code from your authenticator app, or use a recovery code if you cannot access your device.', 'guard-dog') . '</p>';
    } else {
        $main_message = '<p class="message">' . esc_html__('Two-factor authentication is required but no methods are configured.', 'guard-dog') . '</p>';
    }
}
// phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound

// Display the message directly since login_header was already called in the main 2FA class
if (!empty($main_message)) {
    echo wp_kses_post($main_message);
}

?>

<div id="guard-dog-2fa-login-container">
    <!-- App-based 2FA Form -->
    <?php if ($user_has_app_2fa): ?>
    <form name="loginform" id="loginform" action="<?php echo esc_url(site_url('wp-login.php', 'login_post')); ?>" method="post" class="<?php echo esc_attr($show_recovery ? '' : 'show'); ?>">
        <?php if ($user_has_email_2fa && $user_has_app_2fa): ?>
        <div class="guard-dog-2fa-method-selector">
            <p class="guard-dog-2fa-method-label"><?php esc_html_e('Choose your 2FA method:', 'guard-dog'); ?></p>
            <div class="guard-dog-2fa-method-options">
                <label class="guard-dog-2fa-method-option">
                    <input type="radio" name="guard_dog_2fa_method" value="app">
                    <span class="guard-dog-2fa-method-text">
                        <span class="dashicons dashicons-smartphone"></span>
                        <?php esc_html_e('Authenticator App', 'guard-dog'); ?>
                    </span>
                </label>
                <label class="guard-dog-2fa-method-option">
                    <input type="radio" name="guard_dog_2fa_method" value="email">
                    <span class="guard-dog-2fa-method-text">
                        <span class="dashicons dashicons-email-alt"></span>
                        <?php esc_html_e('Email Code', 'guard-dog'); ?>
                    </span>
                </label>
            </div>
        </div>
        <div class="guard-dog-2fa-email-status" id="guard-dog-2fa-email-status"></div>
        <div class="guard-dog-2fa-code-section">
            <p>
                <label for="guard_dog_2fa_code"><?php esc_html_e('Verification Code', 'guard-dog'); ?></label>
                <input type="text" name="guard_dog_2fa_code" id="guard_dog_2fa_code" class="input" value="" size="20" maxlength="6" autocomplete="off" placeholder="<?php esc_attr_e('Enter 6-digit code', 'guard-dog'); ?>" />
            </p>
        </div>
        <?php else: ?>
        <input type="hidden" name="guard_dog_2fa_method" value="app" />
        <p>
            <label for="guard_dog_2fa_code"><?php esc_html_e('Verification Code', 'guard-dog'); ?></label>
            <input type="text" name="guard_dog_2fa_code" id="guard_dog_2fa_code" class="input" value="" size="20" maxlength="6" autocomplete="off" autofocus="autofocus" placeholder="<?php esc_attr_e('Enter 6-digit code', 'guard-dog'); ?>" />
        </p>
        <?php endif; ?>
        <input type="hidden" name="log" value="<?php echo esc_attr($username); ?>" />
        <input type="hidden" name="redirect_to" value="<?php echo esc_attr($redirect_to); ?>" />
        <input type="hidden" name="rememberme" value="<?php echo esc_attr($rememberme ? 'forever' : ''); ?>" />
        <input type="hidden" name="guard_dog_2fa_interim_login" value="1" />
        <input type="hidden" name="guard_dog_2fa_flow_token" value="<?php echo esc_attr($flow_token); ?>" />
        <?php wp_nonce_field('guard_dog_verify_2fa_login_' . $user_id, 'guard_dog_2fa_nonce'); ?>
        
        <!-- Preserve CAPTCHA token from initial login -->
        <?php if (!empty($captcha_token)): ?>
            <?php if ($captcha_provider === 'recaptcha'): ?>
                <input type="hidden" name="g-recaptcha-response" value="<?php echo esc_attr($captcha_token); ?>" />
            <?php elseif ($captcha_provider === 'hcaptcha'): ?>
                <input type="hidden" name="h-captcha-response" value="<?php echo esc_attr($captcha_token); ?>" />
            <?php elseif ($captcha_provider === 'turnstile'): ?>
                <input type="hidden" name="cf-turnstile-response" value="<?php echo esc_attr($captcha_token); ?>" />
            <?php endif; ?>
        <?php endif; ?>
        <p class="submit">
            <input type="submit" name="wp-submit" id="wp-submit" class="button button-primary button-large" value="<?php esc_attr_e('Verify', 'guard-dog'); ?>" />
        </p>
        <p class="guard-dog-2fa-toggle-links" id="guard-dog-recovery-link-container">
            <?php if ($recovery_count > 0): ?>
            <a href="#" id="guard-dog-use-recovery-code" class="guard-dog-2fa-link"><?php esc_html_e('Use Recovery Code', 'guard-dog'); ?></a>
            <?php endif; ?>
        </p>
    </form>
    <?php endif; // End app-based 2FA form ?>

    <!-- Email-only 2FA Form (when user has only email 2FA enabled) -->
    <?php if ($user_has_email_2fa && !$user_has_app_2fa): ?>
    <form name="emailform" id="emailform" action="<?php echo esc_url(site_url('wp-login.php', 'login_post')); ?>" method="post" class="<?php echo esc_attr($show_recovery ? '' : 'show'); ?>">
        <input type="hidden" name="guard_dog_2fa_method" value="email" />
        
        <div class="guard-dog-email-2fa-section">
            <p>
                <label for="guard_dog_email_2fa_code"><?php esc_html_e('Email Verification Code', 'guard-dog'); ?></label>
                <input type="text" name="guard_dog_2fa_code" id="guard_dog_email_2fa_code" class="input" value="" size="20" maxlength="6" autocomplete="off" autofocus="autofocus" placeholder="<?php esc_attr_e('Enter 6-digit code', 'guard-dog'); ?>" />
            </p>
            <p class="guard-dog-email-2fa-send-code">
                <button type="button" id="guard-dog-send-email-code" class="button button-secondary">
                    <?php esc_html_e('Send Code to Email', 'guard-dog'); ?>
                </button>
                <span id="guard-dog-email-code-status" class="guard-dog-email-code-status"></span>
            </p>
        </div>
        
        <input type="hidden" name="log" value="<?php echo esc_attr($username); ?>" />
        <input type="hidden" name="redirect_to" value="<?php echo esc_attr($redirect_to); ?>" />
        <input type="hidden" name="rememberme" value="<?php echo esc_attr($rememberme ? 'forever' : ''); ?>" />
        <input type="hidden" name="guard_dog_2fa_interim_login" value="1" />
        <input type="hidden" name="guard_dog_2fa_flow_token" value="<?php echo esc_attr($flow_token); ?>" />
        <?php wp_nonce_field('guard_dog_verify_2fa_login_' . $user_id, 'guard_dog_2fa_nonce'); ?>
        
        <!-- Preserve CAPTCHA token from initial login -->
        <?php if (!empty($captcha_token)): ?>
            <?php if ($captcha_provider === 'recaptcha'): ?>
                <input type="hidden" name="g-recaptcha-response" value="<?php echo esc_attr($captcha_token); ?>" />
            <?php elseif ($captcha_provider === 'hcaptcha'): ?>
                <input type="hidden" name="h-captcha-response" value="<?php echo esc_attr($captcha_token); ?>" />
            <?php elseif ($captcha_provider === 'turnstile'): ?>
                <input type="hidden" name="cf-turnstile-response" value="<?php echo esc_attr($captcha_token); ?>" />
            <?php endif; ?>
        <?php endif; ?>
        
        <p class="submit">
            <input type="submit" name="wp-submit" id="wp-submit-email" class="button button-primary button-large" value="<?php esc_attr_e('Verify Email Code', 'guard-dog'); ?>" />
        </p>
    </form>
    <?php endif; // End email-only 2FA form ?>

    <!-- Recovery Code Form (only for app-based 2FA users) -->
    <?php if ($user_has_app_2fa): ?>
    <form name="recoveryform" id="recoveryform" action="<?php echo esc_url(site_url('wp-login.php', 'login_post')); ?>" method="post" class="<?php echo esc_attr($show_recovery ? 'show' : ''); ?>">
        <p>
            <label for="guard_dog_2fa_recovery_code"><?php esc_html_e('Recovery Code', 'guard-dog'); ?></label>
            <input type="text" name="guard_dog_2fa_code" id="guard_dog_2fa_recovery_code" class="input" value="" size="20" maxlength="20" autocomplete="off" placeholder="<?php esc_attr_e('Enter recovery code (e.g., abcd-1234-efgh)', 'guard-dog'); ?>" />
        </p>
        <input type="hidden" name="log" value="<?php echo esc_attr($username); ?>" />
        <input type="hidden" name="redirect_to" value="<?php echo esc_attr($redirect_to); ?>" />
        <input type="hidden" name="rememberme" value="<?php echo esc_attr($rememberme ? 'forever' : ''); ?>" />
        <input type="hidden" name="guard_dog_2fa_interim_login" value="1" />
        <input type="hidden" name="guard_dog_2fa_flow_token" value="<?php echo esc_attr($flow_token); ?>" />
        <?php wp_nonce_field('guard_dog_verify_2fa_login_' . $user_id, 'guard_dog_2fa_nonce'); ?>
        
        <!-- Preserve CAPTCHA token from initial login -->
        <?php if (!empty($captcha_token)): ?>
            <?php if ($captcha_provider === 'recaptcha'): ?>
                <input type="hidden" name="g-recaptcha-response" value="<?php echo esc_attr($captcha_token); ?>" />
            <?php elseif ($captcha_provider === 'hcaptcha'): ?>
                <input type="hidden" name="h-captcha-response" value="<?php echo esc_attr($captcha_token); ?>" />
            <?php elseif ($captcha_provider === 'turnstile'): ?>
                <input type="hidden" name="cf-turnstile-response" value="<?php echo esc_attr($captcha_token); ?>" />
            <?php endif; ?>
        <?php endif; ?>
        <p class="submit">
            <input type="submit" name="wp-submit" id="wp-submit-recovery" class="button button-primary button-large" value="<?php esc_attr_e('Verify Recovery Code', 'guard-dog'); ?>" />
        </p>
        <p class="guard-dog-2fa-toggle-links">
            <a href="#" id="guard-dog-use-totp-code" class="guard-dog-2fa-link"><?php esc_html_e('Back to Authenticator App', 'guard-dog'); ?></a>
        </p>
    </form>
    <?php endif; // End recovery form ?>


    <!-- Recovery Code Info (only for app-based 2FA users) -->
    <?php if ($user_has_app_2fa): ?>
        <?php if ($recovery_count > 0): ?>
        <p class="guard-dog-2fa-recovery-info">
            <small>
                <?php
                // Translators: %d is the number of recovery codes remaining.
                printf(esc_html__('You have %d recovery codes remaining.', 'guard-dog'), (int) $recovery_count);
                ?>
            </small>
        </p>
        <?php else: ?>
        <p class="guard-dog-2fa-recovery-info">
            <small><?php esc_html_e('No recovery codes available. Please contact an administrator.', 'guard-dog'); ?></small>
        </p>
        <?php endif; ?>
    <?php endif; ?>
</div>


<p id="backtologin">
    <a href="<?php echo esc_url(wp_login_url()); ?>">
        <?php esc_html_e('&larr; Back to Log In', 'guard-dog'); ?>
    </a>
</p>
