<?php
/**
 * Template for 2FA user profile section
 *
 * @package Guard_Dog
 * @since 1.2.0
 */

// Prevent direct access
if (!defined('ABSPATH')) {
    exit;
}

// Ensure we have the required variables
if (!isset($user) || !isset($can_setup) || !isset($tfa_globally_enabled)) {
    return;
}

// 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

// Check if user has 2FA enabled
$tfa_enabled = get_user_meta($user->ID, '_guard_dog_2fa_enabled', true);
$tfa_secret = get_user_meta($user->ID, '_guard_dog_2fa_secret', true);
$backup_codes = get_user_meta($user->ID, '_guard_dog_2fa_backup_codes', true);

// Check email 2FA status
$email_2fa_enabled = get_option('guard_dog_email_2fa_enabled', false);
$email_provider_configured = false;
$is_email_2fa_enabled_for_user = false;

if (function_exists('Guard_Dog')) {
    if (isset(Guard_Dog()->features['email_provider'])) {
        $email_provider_configured = Guard_Dog()->features['email_provider']->is_configured();
    }
    if (isset(Guard_Dog()->features['email_two_factor_auth'])) {
        $is_email_2fa_enabled_for_user = Guard_Dog()->features['email_two_factor_auth']->is_email_2fa_enabled_for_user($user->ID);
    }
}

// Only allow users to setup email 2FA for themselves AND if email 2FA is globally enabled
$can_setup_email_2fa = (get_current_user_id() === $user->ID) && $email_2fa_enabled;
// phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound

// Debug logging (not output to HTML)
if (function_exists('Guard_Dog') && Guard_Dog()->debug) {
    Guard_Dog()->debug->info('2FA template debug values', 'two_factor', [
        'user_id' => $user->ID,
        'tfa_enabled' => $tfa_enabled,
        'tfa_secret' => $tfa_secret ? 'present' : 'missing',
        'can_setup' => $can_setup,
        'tfa_globally_enabled' => $tfa_globally_enabled,
        'email_2fa_enabled' => $email_2fa_enabled,
        'email_provider_configured' => $email_provider_configured,
        'is_email_2fa_enabled_for_user' => $is_email_2fa_enabled_for_user
    ]);
}
?>

<div id="guard-dog-2fa-section" class="guard-dog-2fa-profile-section">
    <h3><?php esc_html_e('Two-Factor Authentication', 'guard-dog'); ?></h3>
    
    <?php if (isset($notice_message) && !empty($notice_message)): ?>
        <div class="notice notice-warning is-dismissible">
            <p><?php echo wp_kses_post($notice_message); ?></p>
        </div>
    <?php endif; ?>

    <?php if (isset($error_message) && !empty($error_message)): ?>
        <div class="notice notice-error">
            <p><?php echo wp_kses_post($error_message); ?></p>
            <p><a href="<?php echo esc_url(admin_url('profile.php#guard-dog-2fa-section')); ?>" class="button button-primary"><?php esc_html_e('Set up 2FA Now', 'guard-dog'); ?></a></p>
        </div>
    <?php endif; ?>

    <?php
    // Show informational message when both 2FA methods are enabled globally
    $app_2fa_globally_enabled = $tfa_globally_enabled;
    $email_2fa_globally_enabled = $email_2fa_enabled;
    if ($app_2fa_globally_enabled && $email_2fa_globally_enabled):
    ?>
        <div class="guard-dog-notice-info">
            <p><strong><?php esc_html_e('Note:', 'guard-dog'); ?></strong> 
            <?php esc_html_e('Both app-based and email-based 2FA are available. You only need to set up one method to meet 2FA requirements, but you can optionally enable both for extra security.', 'guard-dog'); ?></p>
        </div>
    <?php endif; ?>

    <!-- App-Based 2FA Section -->
    <div class="guard-dog-2fa-method-section">
        <h4>
            <span class="dashicons dashicons-smartphone"></span>
            <?php esc_html_e('App-Based Authentication', 'guard-dog'); ?>
        </h4>

        <?php if (!$tfa_globally_enabled): ?>
            <div class="guard-dog-notice-info">
                <p><?php esc_html_e('App-based two-factor authentication is not enabled globally by your administrator.', 'guard-dog'); ?></p>
            </div>
        <?php else: ?>
            <table class="form-table">
                <tr>
                    <th scope="row"><?php esc_html_e('Status', 'guard-dog'); ?></th>
                    <td>
                        <?php if ($tfa_enabled && $tfa_secret): ?>
                            <p class="guard-dog-status-enabled">
                                <span class="dashicons dashicons-yes-alt"></span>
                                <strong><?php esc_html_e('Enabled', 'guard-dog'); ?></strong>
                            </p>
                            <p class="description">
                                <?php esc_html_e('You will enter a 6-digit verification code from your authenticator app when logging in.', 'guard-dog'); ?>
                            </p>
                            <?php if ($can_setup): ?>
                                <button type="button" id="guard-dog-disable-2fa-profile" class="button button-secondary"
                                        data-user-id="<?php echo esc_attr($user->ID); ?>"
                                        data-nonce="<?php echo esc_attr(wp_create_nonce('guard_dog_disable_2fa_' . $user->ID)); ?>">
                                    <?php esc_html_e('Disable App 2FA', 'guard-dog'); ?>
                                </button>
                            <?php endif; ?>

                            <?php if (!empty($backup_codes) && is_array($backup_codes)): ?>
                                <div class="notice notice-warning inline guard-dog-notice-margin">
                                    <h4><?php esc_html_e('Save Your Recovery Codes!', 'guard-dog'); ?></h4>
                                    <p><?php esc_html_e('If you lose access to your authenticator app, you can use one of these codes to log in. Store them securely. Each code can only be used once.', 'guard-dog'); ?></p>
                                    <ul class="guard-dog-recovery-codes-list">
                                        <?php
                                        // phpcs:disable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                                        // $code is a foreach loop variable, not a global variable
                                        // The Plugin Checker incorrectly flags loop variables as globals
                                        foreach ($backup_codes as $code):
                                            ?>
                                            <li><code><?php echo esc_html($code); ?></code></li>
                                        <?php
                                        endforeach;
                                        // phpcs:enable WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedVariableFound
                                        ?>
                                    </ul>
                                </div>
                            <?php endif; ?>
                        <?php else: ?>
                            <p class="guard-dog-status-disabled">
                                <span class="dashicons dashicons-no-alt"></span>
                                <?php esc_html_e('Disabled', 'guard-dog'); ?>
                            </p>
                            <?php if ($can_setup): ?>
                                <button type="button" id="guard-dog-enable-2fa-button" class="button button-primary"
                                        data-user-id="<?php echo esc_attr($user->ID); ?>"
                                        data-nonce="<?php echo esc_attr(wp_create_nonce('guard_dog_generate_2fa_secret_' . $user->ID)); ?>">
                                    <?php esc_html_e('Enable App 2FA', 'guard-dog'); ?>
                                </button>
                                <p class="description">
                                    <?php esc_html_e('Enable app-based two-factor authentication. You will use an authenticator app to generate a 6-digit code when logging in.', 'guard-dog'); ?>
                                </p>

                                <div id="guard-dog-2fa-setup-section" class="guard-dog-setup-section">
                                    <h5><?php esc_html_e('App 2FA Setup', 'guard-dog'); ?></h5>
                                    <ol>
                                        <li><?php esc_html_e('Scan the QR code below or manually enter the secret key into your authenticator app.', 'guard-dog'); ?></li>
                                        <li><?php esc_html_e('Enter the 6-digit code generated by your app to verify setup.', 'guard-dog'); ?></li>
                                    </ol>
                                    <div id="guard-dog-2fa-qr-code" class="guard-dog-qr-container"></div>
                                    <p><?php esc_html_e('Secret Key:', 'guard-dog'); ?> <code id="guard-dog-2fa-secret-key" class="guard-dog-secret-key"></code></p>
                                    <p>
                                        <label for="guard-dog-2fa-verify-code"><?php esc_html_e('Verification Code:', 'guard-dog'); ?> </label>
                                        <input type="text" id="guard-dog-2fa-verify-code" name="guard_dog_2fa_verify_code" size="6" maxlength="6" autocomplete="off" />
                                        <button type="button" id="guard-dog-verify-2fa-button" class="button button-secondary">
                                            <?php esc_html_e('Verify & Enable', 'guard-dog'); ?>
                                        </button>
                                    </p>
                                    <div id="guard-dog-2fa-setup-feedback" class="guard-dog-feedback"></div>
                                </div>
                            <?php else: ?>
                                <p class="description"><?php esc_html_e('Users can enable 2FA from their own profile page.', 'guard-dog'); ?></p>
                            <?php endif; ?>
                        <?php endif; ?>
                    </td>
                </tr>
            </table>

            <?php if ($can_setup && !($tfa_enabled && $tfa_secret)): ?>
                <div class="guard-dog-app-2fa-info">
                    <h5><?php esc_html_e('How App 2FA Works', 'guard-dog'); ?></h5>
                    <ol>
                        <li><?php esc_html_e('Install an authenticator app (like Google Authenticator, Authy, etc.) on your mobile device', 'guard-dog'); ?></li>
                        <li><?php esc_html_e('Scan the QR code or enter the secret key to add your account', 'guard-dog'); ?></li>
                        <li><?php esc_html_e('When you log in, enter the 6-digit code from your app', 'guard-dog'); ?></li>
                        <li><?php esc_html_e('Codes refresh every 30 seconds for security', 'guard-dog'); ?></li>
                    </ol>

                    <div class="guard-dog-notice-info">
                        <p><strong><?php esc_html_e('Note:', 'guard-dog'); ?></strong>
                        <?php esc_html_e('You can enable both email and app-based 2FA for added security. During login, you can choose which method to use.', 'guard-dog'); ?></p>
                    </div>
                </div>
            <?php endif; ?>

            <?php if ($tfa_enabled && $can_setup): ?>
            <div id="guard-dog-recovery-codes-section" class="guard-dog-recovery-section">
                <h4><?php esc_html_e('Recovery Codes', 'guard-dog'); ?></h4>
                <p class="description">
                    <?php esc_html_e('Recovery codes allow you to access your account if you lose your authenticator device.', 'guard-dog'); ?>
                </p>
                <?php wp_nonce_field('guard_dog_regenerate_recovery_' . $user->ID, 'guard_dog_regenerate_recovery_nonce'); ?>
                <button type="button" id="guard-dog-regenerate-recovery-codes-profile" class="button button-secondary" 
                        data-user-id="<?php echo esc_attr($user->ID); ?>" 
                        data-nonce="<?php echo esc_attr(wp_create_nonce('guard_dog_regenerate_recovery_codes_' . $user->ID)); ?>">
                    <?php esc_html_e('Generate New Recovery Codes', 'guard-dog'); ?>
                </button>
                <p class="description">
                    <?php esc_html_e('Generating new codes will invalidate any previous codes.', 'guard-dog'); ?>
                </p>
                
                <div id="guard-dog-recovery-codes-display-profile" class="guard-dog-codes-display">
                    <h5><?php esc_html_e('Your New Recovery Codes', 'guard-dog'); ?></h5>
                    <p class="description"><?php esc_html_e('Save these codes securely. Each code can only be used once. They will only be shown this one time.', 'guard-dog'); ?></p>
                    <div id="guard-dog-recovery-codes-list-profile" class="guard-dog-codes-list">
                        <!-- Recovery codes will be populated here -->
                    </div>
                    <div class="guard-dog-codes-actions">
                        <button type="button" id="guard-dog-copy-recovery-codes-profile" class="button button-secondary">
                            <?php esc_html_e('Copy All Codes', 'guard-dog'); ?>
                        </button>
                        <button type="button" id="guard-dog-print-recovery-codes-profile" class="button button-secondary">
                            <?php esc_html_e('Print Codes', 'guard-dog'); ?>
                        </button>
                    </div>
                    <div class="guard-dog-codes-warning">
                        <p>
                            <strong><?php esc_html_e('Important:', 'guard-dog'); ?></strong> 
                            <?php esc_html_e('These codes will disappear when you navigate away from this page. Save them now!', 'guard-dog'); ?>
                        </p>
                    </div>
                </div>
            </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>

    <!-- Email-Based 2FA Section -->
    <div class="guard-dog-2fa-method-section">
        <h4>
            <span class="dashicons dashicons-email-alt"></span>
            <?php esc_html_e('Email-Based Authentication', 'guard-dog'); ?>
        </h4>
        
        <?php if (!$email_2fa_enabled): ?>
            <div class="guard-dog-notice-info">
                <p><?php esc_html_e('Email two-factor authentication is not enabled globally by your administrator.', 'guard-dog'); ?></p>
            </div>
        <?php elseif (!$email_provider_configured): ?>
            <div class="guard-dog-notice-warning">
                <p><?php esc_html_e('Email provider is not configured. Please contact your administrator to configure the email provider.', 'guard-dog'); ?></p>
            </div>
        <?php else: ?>
            <table class="form-table">
                <tr>
                    <th scope="row"><?php esc_html_e('Status', 'guard-dog'); ?></th>
                    <td>
                        <?php if ($is_email_2fa_enabled_for_user): ?>
                            <p class="guard-dog-status-enabled">
                                <span class="dashicons dashicons-yes-alt"></span>
                                <strong><?php esc_html_e('Enabled', 'guard-dog'); ?></strong>
                            </p>
                            <p class="description">
                                <?php esc_html_e('You will receive a 6-digit verification code via email when logging in.', 'guard-dog'); ?>
                            </p>
                            <?php if ($can_setup_email_2fa): ?>
                                <button type="button" id="guard-dog-disable-email-2fa" class="button button-secondary" 
                                        data-user-id="<?php echo esc_attr($user->ID); ?>" 
                                        data-nonce="<?php echo esc_attr(wp_create_nonce('guard_dog_disable_email_2fa_' . $user->ID)); ?>">
                                    <?php esc_html_e('Disable Email 2FA', 'guard-dog'); ?>
                                </button>
                            <?php endif; ?>
                        <?php else: ?>
                            <p class="guard-dog-status-disabled">
                                <span class="dashicons dashicons-no-alt"></span>
                                <?php esc_html_e('Disabled', 'guard-dog'); ?>
                            </p>
                            <?php if ($can_setup_email_2fa): ?>
                                <button type="button" id="guard-dog-enable-email-2fa" class="button button-primary" 
                                        data-user-id="<?php echo esc_attr($user->ID); ?>" 
                                        data-nonce="<?php echo esc_attr(wp_create_nonce('guard_dog_enable_email_2fa_' . $user->ID)); ?>">
                                    <?php esc_html_e('Enable Email 2FA', 'guard-dog'); ?>
                                </button>
                                <p class="description">
                                    <?php esc_html_e('Enable email-based two-factor authentication. You will receive a 6-digit code via email when logging in.', 'guard-dog'); ?>
                                </p>
                                
                                <div id="guard-dog-email-2fa-setup-section" class="guard-dog-setup-section guard-dog-email-setup-hidden">
                                    <h5><?php esc_html_e('Email 2FA Setup', 'guard-dog'); ?></h5>
                                    <p><?php esc_html_e('A verification code has been sent to your email address. Please enter the code below to complete the setup.', 'guard-dog'); ?></p>
                                    
                                    <p>
                                        <label for="guard-dog-email-2fa-verify-code"><?php esc_html_e('Verification Code:', 'guard-dog'); ?> </label>
                                        <input type="text" id="guard-dog-email-2fa-verify-code" name="guard_dog_email_2fa_verify_code" size="6" maxlength="6" autocomplete="off" />
                                        <button type="button" id="guard-dog-verify-email-2fa-button" class="button button-secondary">
                                            <?php esc_html_e('Verify & Enable', 'guard-dog'); ?>
                                        </button>
                                    </p>
                                    <div id="guard-dog-email-2fa-setup-feedback" class="guard-dog-feedback"></div>
                                </div>
                            <?php endif; ?>
                        <?php endif; ?>
                    </td>
                </tr>
            </table>

            <?php if ($can_setup_email_2fa && !$is_email_2fa_enabled_for_user): ?>
                <div class="guard-dog-email-2fa-info">
                    <h5><?php esc_html_e('How Email 2FA Works', 'guard-dog'); ?></h5>
                    <ol>
                        <li><?php esc_html_e('When you log in, you\'ll be prompted to enter a verification code', 'guard-dog'); ?></li>
                        <li><?php esc_html_e('A 6-digit code will be sent to your email address', 'guard-dog'); ?></li>
                        <li><?php esc_html_e('Enter the code to complete the login process', 'guard-dog'); ?></li>
                        <li><?php esc_html_e('The code expires after 10 minutes for security', 'guard-dog'); ?></li>
                    </ol>
                    
                    <div class="guard-dog-notice-info">
                        <p><strong><?php esc_html_e('Note:', 'guard-dog'); ?></strong> 
                        <?php esc_html_e('You can enable both email and app-based 2FA for added security. During login, you can choose which method to use.', 'guard-dog'); ?></p>
                    </div>
                </div>
            <?php endif; ?>
        <?php endif; ?>
    </div>

    <?php wp_nonce_field('guard_dog_verify_2fa_setup_' . $user->ID, 'guard_dog_verify_2fa_nonce', false, true); ?>
</div>
