<?php
/**
 * Template for the two-factor authentication verification page
 */

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

$user = wp_get_current_user();
$error = isset($_GET['error']) ? sanitize_text_field($_GET['error']) : '';

?><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo('charset'); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php esc_html_e('Two-Factor Authentication', 'iron-security'); ?> - <?php bloginfo('name'); ?></title>
    <style>
        body {
            background-color: #f1f1f1;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
            line-height: 1.5;
            padding: 0;
            margin: 0;
        }
        .iron-security-2fa-container {
            max-width: 400px;
            margin: 100px auto 0;
            padding: 40px;
            background: #fff;
            border-radius: 4px;
            box-shadow: 0 1px 3px rgba(0,0,0,.1);
        }
        .iron-security-2fa-logo {
            text-align: center;
            margin-bottom: 30px;
        }
        .iron-security-2fa-logo img {
            max-height: 80px;
            width: auto;
        }
        .iron-security-2fa-header {
            text-align: center;
            margin-bottom: 20px;
        }
        .iron-security-2fa-form {
            margin-top: 20px;
        }
        .iron-security-2fa-form label {
            display: block;
            margin-bottom: 5px;
            font-weight: 600;
        }
        .iron-security-2fa-input {
            width: 100%;
            padding: 10px;
            font-size: 16px;
            letter-spacing: 2px;
            text-align: center;
            margin-bottom: 20px;
            border: 1px solid #ddd;
            border-radius: 3px;
        }
        .iron-security-2fa-error {
            background-color: #f8d7da;
            color: #721c24;
            padding: 10px 15px;
            border-radius: 4px;
            margin: 0 0 20px;
            border-left: 4px solid #dc3545;
        }
        .iron-security-2fa-remember {
            margin-top: 15px;
        }
        .iron-security-2fa-actions {
            display: flex;
            justify-content: space-between;
            margin-top: 20px;
        }
        .iron-security-2fa-button {
            background: #2271b1;
            border: none;
            color: #fff;
            padding: 10px 15px;
            border-radius: 3px;
            cursor: pointer;
            font-size: 14px;
            font-weight: 600;
        }
        .iron-security-2fa-button.secondary {
            background: #f6f7f7;
            border: 1px solid #2271b1;
            color: #2271b1;
        }
        h1 {
            font-size: 24px;
            margin: 0 0 15px;
        }
        a {
            color: #2271b1;
            text-decoration: none;
        }
        a:hover {
            color: #135e96;
        }
        input[type="checkbox"] {
            margin-right: 5px;
        }
    </style>
</head>
<body class="iron-security-2fa">
    <div class="iron-security-2fa-container">
        <div class="iron-security-2fa-logo">
            <a href="<?php echo esc_url(home_url('/')); ?>">
                <?php 
                $custom_logo_id = get_theme_mod('custom_logo');
                if ($custom_logo_id) {
                    echo wp_get_attachment_image($custom_logo_id, 'medium');
                } else {
                    echo '<img src="' . esc_url(admin_url('images/w-logo-blue.png')) . '" alt="' . esc_attr(get_bloginfo('name')) . '" />';
                }
                ?>
            </a>
        </div>
        
        <div class="iron-security-2fa-header">
            <h1><?php esc_html_e('Two-Factor Authentication', 'iron-security'); ?></h1>
            <p><?php printf(
	            /* translators: %s: Name of user */
		            esc_html__('Hi %s, please enter the verification code from your authenticator app.', 'iron-security'), 
                    esc_html($user->display_name)); ?></p>
        </div>
        
        <?php if (!empty($error)): ?>
        <div class="iron-security-2fa-error" style="display: block;">
            <?php echo esc_html($error); ?>
        </div>
        <?php else: ?>
        <div class="iron-security-2fa-error" style="display: none;"></div>
        <?php endif; ?>
        
        <form id="iron-security-2fa-verify-form" class="iron-security-2fa-form" method="post">
            <?php wp_nonce_field('iron_security_2fa_verify', 'iron_security_2fa_verify_nonce'); ?>
            <div>
                <label for="iron_security_2fa_verify_code"><?php esc_html_e('Authentication Code', 'iron-security'); ?></label>
                <input type="text" name="code" id="iron_security_2fa_verify_code" class="iron-security-2fa-input" size="20" pattern="[0-9]*" autocomplete="off" autofocus />
            </div>

            <?php 
            // Check if remember device is enabled
            $twoFactorAuth = new WpironTwoFactorAuth(new WpironHelper());
            $settings = $twoFactorAuth->get_settings();
            $remember_device = (int) $settings['remember_device'] > 0;
            if ($remember_device): 
            ?>
            <div class="iron-security-2fa-remember">
                <label for="iron_security_2fa_remember">
                    <input name="remember" type="checkbox" id="iron_security_2fa_remember" value="1" />
                    <?php printf(
                            /* translators: %d: Name of days */
	                    esc_html__('Remember this device for %d days', 'iron-security'), 
                        absint($settings['remember_device'])); ?>
                </label>
            </div>
            <?php endif; ?>

            <div class="iron-security-2fa-actions">
                <input type="submit" class="iron-security-2fa-button" value="<?php esc_attr_e('Verify', 'iron-security'); ?>" />
                <a href="<?php echo esc_url(wp_logout_url(home_url())); ?>" class="iron-security-2fa-button secondary"><?php esc_html_e('Log Out', 'iron-security'); ?></a>
            </div>
        </form>
    </div>

    <script>
    document.addEventListener('DOMContentLoaded', function() {
        const form = document.getElementById('iron-security-2fa-verify-form');
        
        // Create error div if it doesn't exist
        let errorDiv = document.querySelector('.iron-security-2fa-error');
        if (!errorDiv) {
            errorDiv = document.createElement('div');
            errorDiv.className = 'iron-security-2fa-error';
            errorDiv.style.display = 'none';
            const formElement = document.querySelector('.iron-security-2fa-form');
            formElement.parentNode.insertBefore(errorDiv, formElement);
        } else {
            // Make sure error div is hidden by default
            errorDiv.style.display = 'none';
        }
        
        form.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // Hide any previous error messages
            errorDiv.style.display = 'none';
            
            const code = document.getElementById('iron_security_2fa_verify_code').value;
            const nonce = document.querySelector('#iron_security_2fa_verify_nonce').value;
            const remember = document.getElementById('iron_security_2fa_remember')?.checked || false;
            
            // Basic validation
            if (!code || code.length !== 6 || !/^\d+$/.test(code)) {
                errorDiv.textContent = '<?php esc_html_e('Please enter a valid 6-digit code.', 'iron-security'); ?>';
                errorDiv.style.display = 'block';
                return;
            }
            
            // Show loading state
            const submitButton = form.querySelector('input[type="submit"]');
            const originalButtonText = submitButton.value;
            submitButton.value = '<?php esc_html_e('Verifying...', 'iron-security'); ?>';
            submitButton.disabled = true;
            
            const data = new FormData();
            data.append('action', 'iron_security_verify_2fa_code');
            data.append('code', code);
            data.append('remember', remember ? '1' : '0');
            data.append('nonce', nonce);
            
            fetch('<?php echo esc_url(admin_url('admin-ajax.php')); ?>', {
                method: 'POST',
                credentials: 'same-origin',
                body: data
            })
            .then(response => response.json())
            .then(response => {
                if (response.success) {
                    window.location.href = '<?php echo esc_url(admin_url()); ?>';
                } else {
                    errorDiv.textContent = response.data || '<?php esc_html_e('Invalid verification code. Please try again.', 'iron-security'); ?>';
                    errorDiv.style.display = 'block';
                    submitButton.value = originalButtonText;
                    submitButton.disabled = false;
                    document.getElementById('iron_security_2fa_verify_code').value = '';
                    document.getElementById('iron_security_2fa_verify_code').focus();
                }
            })
            .catch(error => {
                console.error('Error:', error);
                errorDiv.textContent = '<?php esc_html_e('An error occurred. Please try again.', 'iron-security'); ?>';
                errorDiv.style.display = 'block';
                submitButton.value = originalButtonText;
                submitButton.disabled = false;
            });
        });
    });
    </script>
</body>
</html> 