<?php
if (! defined('ABSPATH')) {
    exit; // Exit if accessed directly.
}

$ultimate_security_options = \WPUltimateSecurity\UltimateSecurity\Support\Helpers\Utils::ultimate_security_get_option();

// Get error message if it exists (should be set by the calling function)
$otp_error = isset($GLOBALS['otp_error']) ? $GLOBALS['otp_error'] : '';

// Get user info for backup codes
$user_id = isset($_COOKIE['ultimate_security_2fa_user_id']) ? intval($_COOKIE['ultimate_security_2fa_user_id']) : 0;
$backup_codes_count = 0;

// Check if user has backup codes (only if BackupCodeService exists - PRO feature)
if (\WPUltimateSecurity\UltimateSecurity\Support\Validation\ProValidation::ultimate_security_is_pro() && class_exists('\WPUltimateSecurity\UltimateSecurityPro\Modules\Authentication\TwoFactor\Services\BackupCodeService')) {
    $backup_codes_count = \WPUltimateSecurity\UltimateSecurityPro\Modules\Authentication\TwoFactor\Services\BackupCodeService::get_remaining_count($user_id);
}
?>
<!doctype html>
<html <?php language_attributes(); ?>>

<head>
    <meta charset="<?php bloginfo('charset'); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?php wp_head(); ?>
    <style>
        #wpadminbar {
            display: none;
        }
        .login {
            background: #f1f1f1;
        }
        .login form {
            margin-top: 20px;
            margin-left: 0;
            padding: 26px 24px 46px;
            font-weight: 400;
            overflow: hidden;
            background: #fff;
            border: 1px solid #ddd;
            box-shadow: 0 1px 3px rgba(0,0,0,.04);
        }
        .login form p {
            margin-bottom: 16px;
        }
        .login input[type=text] {
            font-size: 24px;
            width: 100%;
            border: 1px solid #ddd;
            padding: 3px 5px;
            margin: 2px 6px 16px 0;
        }
        .login input[type=checkbox] {
            margin: 0 8px 0 0;
            vertical-align: middle;
        }
        .login label {
            vertical-align: middle;
        }
        .backup-codes-section {
            margin: 20px 0;
            padding: 15px 0;
            border-top: 1px solid #ddd;
        }
        .backup-codes-info {
            font-size: 12px;
            color: #666;
            margin-left: 20px;
        }
        .code-input-group {
            position: relative;
        }
        .code-input-group.backup-mode input {
            font-family: monospace;
            letter-spacing: 1px;
            text-transform: uppercase;
        }
        .login .button-primary {
            float: right;
        }
    </style>
</head>

<body class="login wp-core-ui">
    <div id="login">
        <h1 role="presentation" class="wp-login-logo">
            <a href="<?php echo esc_url(home_url('/')); ?>">
                <?php bloginfo('name'); ?>
            </a>
        </h1>
        
        <?php if ($otp_error): ?>
            <div id="login_error" class="notice notice-error">
                <p><strong><?php echo esc_html__('Error:', 'ultimate-security'); ?></strong> <?php echo esc_html($otp_error); ?></p>
            </div>
        <?php endif; ?>

        <form method="POST" action="" id="ultimate-security-2fa-form">
            <?php wp_nonce_field('ultimate_security_login_form_action', 'ultimate_security_login_form_field'); ?>
            <?php // echo $_COOKIE['ultimate_security_2fa_user_id'] ?>
            <p class="code-input-group" id="code-input-group">
                <label for="ultimate_security_2fa_code" id="code-label"><?php echo esc_html__('Enter your verification code:', 'ultimate-security'); ?></label>
                <input type="text"
                       name="ultimate_security_2fa_code"
                       id="ultimate_security_2fa_code"
                       class="input"
                       size="20"
                       autocomplete="off"
                       placeholder="<?php echo esc_attr__('6-digit code', 'ultimate-security'); ?>"
                       required>
            </p>

            <?php if (\WPUltimateSecurity\UltimateSecurity\Support\Validation\ProValidation::ultimate_security_is_pro() && $backup_codes_count > 0): ?>
            <div class="backup-codes-section">
                <p>
                    <input type="checkbox" name="use_backup_code" id="use_backup_code" value="1" onchange="toggleBackupMode()">
                    <label for="use_backup_code">
                        <?php echo esc_html__('Use backup code', 'ultimate-security'); ?>
                        <span class="backup-codes-info">
                            (<?php printf(esc_html__('%d codes remaining', 'ultimate-security'), $backup_codes_count); ?>)
                        </span>
                    </label>
                </p>
            </div>
            <?php endif; ?>

            <p class="submit">
                <input type="submit"
                       id="wp-submit"
                       class="button button-primary button-large"
                       value="<?php echo esc_attr__('Verify & Log In', 'ultimate-security'); ?>">
            </p>
        </form>

        <p id="nav">
            <a href="<?php echo esc_url(wp_login_url()); ?>"><?php echo esc_html__('← Back to Login', 'ultimate-security'); ?></a>
            <span style="float: right;">
                <a href="#" id="resend-code-link"><?php echo esc_html__('Resend Code', 'ultimate-security'); ?></a>
            </span>
        </p>

        <div id="resend-message" style="display: none; margin-top: 10px;"></div>
    </div>

    <script type="text/javascript">
        function toggleBackupMode() {
            const checkbox = document.getElementById('use_backup_code');
            const input = document.getElementById('ultimate_security_2fa_code');
            const label = document.getElementById('code-label');
            const inputGroup = document.getElementById('code-input-group');
            
            if (checkbox && checkbox.checked) {
                input.placeholder = '<?php echo esc_attr__('8-character backup code', 'ultimate-security'); ?>';
                label.textContent = '<?php echo esc_html__('Enter your backup code:', 'ultimate-security'); ?>';
                inputGroup.classList.add('backup-mode');
                input.maxLength = 8;
                input.style.textTransform = 'uppercase';
            } else {
                input.placeholder = '<?php echo esc_attr__('6-digit code', 'ultimate-security'); ?>';
                label.textContent = '<?php echo esc_html__('Enter your verification code:', 'ultimate-security'); ?>';
                inputGroup.classList.remove('backup-mode');
                input.maxLength = '';
                input.style.textTransform = '';
            }
        }

        document.addEventListener('DOMContentLoaded', function() {
            // Focus on the OTP input field
            document.getElementById('ultimate_security_2fa_code').focus();

            // Auto-format backup codes to uppercase
            document.getElementById('ultimate_security_2fa_code').addEventListener('input', function(e) {
                const checkbox = document.getElementById('use_backup_code');
                if (checkbox && checkbox.checked) {
                    e.target.value = e.target.value.toUpperCase();
                }
            });

            // Handle resend code link
            var resendLink = document.getElementById('resend-code-link');
            var resendMessage = document.getElementById('resend-message');
            var resendCooldown = false;

            if (resendLink) {
                resendLink.addEventListener('click', function(e) {
                    e.preventDefault();

                    if (resendCooldown) {
                        return;
                    }

                    // Disable link temporarily
                    resendCooldown = true;
                    resendLink.style.pointerEvents = 'none';
                    resendLink.style.opacity = '0.5';

                    // Make AJAX request
                    var xhr = new XMLHttpRequest();
                    xhr.open('POST', '<?php echo esc_url(admin_url('admin-ajax.php')); ?>', true);
                    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

                    xhr.onload = function() {
                        if (xhr.status === 200) {
                            try {
                                var response = JSON.parse(xhr.responseText);

                                if (response.success) {
                                    resendMessage.innerHTML = '<div class="notice notice-success"><p>' + response.data.success_message + '</p></div>';
                                    resendMessage.style.display = 'block';
                                } else {
                                    resendMessage.innerHTML = '<div class="notice notice-error"><p>' + response.data.error_message + '</p></div>';
                                    resendMessage.style.display = 'block';
                                }
                            } catch (e) {
                                resendMessage.innerHTML = '<div class="notice notice-error"><p><?php echo esc_html__('An error occurred. Please try again.', 'ultimate-security'); ?></p></div>';
                                resendMessage.style.display = 'block';
                            }
                        }

                        // Re-enable link after 60 seconds
                        setTimeout(function() {
                            resendCooldown = false;
                            resendLink.style.pointerEvents = '';
                            resendLink.style.opacity = '';
                        }, 60000);
                    };

                    xhr.send('action=ultimate_security_resend_2fa_code&nonce=<?php echo esc_js(wp_create_nonce('ultimate_security_resend_2fa_code')); ?>');
                });
            }
        });
    </script>

    <?php wp_footer(); ?>
</body>
</html>
