<?php
/**
 * Two-Factor Authentication Verification Page
 * OBGYN Research & Collaboration Platform
 */

require_once 'config/config.php';

// Check if 2FA is pending
if (!isset($_SESSION['2fa_pending']) || !isset($_SESSION['2fa_user_id'])) {
    redirect(SITE_URL . '/login.php');
}

// Redirect if already logged in
if (isLoggedIn()) {
    redirect(SITE_URL . '/researcher/dashboard.php');
}

$pageTitle = 'Two-Factor Authentication';
$error = '';
$success = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    validateCSRF();
    
    $code = sanitize($_POST['code'] ?? '');
    
    if (empty($code)) {
        $error = 'Please enter the verification code.';
    } elseif (!preg_match('/^\d{6}$/', $code)) {
        $error = 'Verification code must be 6 digits.';
    } else {
        $result = verify2FAAndLogin($code);
        
        if ($result['success']) {
            // Redirect based on role
            if (isSuperAdmin() || isInstitutionAdmin()) {
                redirect(SITE_URL . '/admin/dashboard.php');
            } else {
                redirect(SITE_URL . '/researcher/dashboard.php');
            }
        } else {
            $error = $result['message'];
        }
    }
}

// Handle cancel
if (isset($_GET['cancel'])) {
    unset($_SESSION['2fa_pending']);
    unset($_SESSION['2fa_user_id']);
    redirect(SITE_URL . '/login.php');
}

include 'templates/header.php';
?>

<div class="container">
    <div class="row justify-content-center">
        <div class="col-md-6 col-lg-5">
            <div class="card shadow-lg mt-5">
                <div class="card-body p-5">
                    <div class="text-center mb-4">
                        <i class="fas fa-shield-alt fa-3x text-primary mb-3"></i>
                        <h2 class="fw-bold">Two-Factor Authentication</h2>
                        <p class="text-muted">Enter the 6-digit code from your authenticator app</p>
                    </div>
                    
                    <?php if ($error): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="fas fa-exclamation-circle"></i> <?php echo e($error); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <form method="POST" action="" class="needs-validation" novalidate>
                        <?php echo csrfField(); ?>
                        
                        <div class="mb-4">
                            <label for="code" class="form-label">Verification Code</label>
                            <div class="input-group input-group-lg">
                                <span class="input-group-text"><i class="fas fa-key"></i></span>
                                <input type="text" class="form-control text-center" id="code" name="code" 
                                       placeholder="000000" maxlength="6" pattern="\d{6}" 
                                       autocomplete="off" required autofocus
                                       style="letter-spacing: 0.5em; font-size: 1.5rem;">
                                <div class="invalid-feedback">
                                    Please enter a valid 6-digit code.
                                </div>
                            </div>
                            <small class="form-text text-muted">
                                <i class="fas fa-info-circle"></i> Open your authenticator app (Google Authenticator, Authy, etc.) to get the code.
                            </small>
                        </div>
                        
                        <div class="alert alert-info" role="alert">
                            <i class="fas fa-clock"></i> <strong>Note:</strong> The code expires every 30 seconds. Make sure to enter it quickly.
                        </div>
                        
                        <button type="submit" class="btn btn-primary w-100 py-2 mb-3">
                            <i class="fas fa-check"></i> Verify & Login
                        </button>
                        
                        <div class="text-center">
                            <a href="?cancel=1" class="text-decoration-none text-danger">
                                <i class="fas fa-times"></i> Cancel & Return to Login
                            </a>
                        </div>
                    </form>
                    
                    <hr class="my-4">
                    
                    <div class="text-center">
                        <p class="mb-2 text-muted small">
                            <i class="fas fa-question-circle"></i> <strong>Having trouble?</strong>
                        </p>
                        <p class="mb-0 text-muted small">
                            If you've lost access to your authenticator app, please contact support.
                        </p>
                    </div>
                </div>
            </div>
            
            <div class="text-center mt-3">
                <a href="<?php echo SITE_URL; ?>/index.php" class="text-decoration-none">
                    <i class="fas fa-home"></i> Back to Home
                </a>
            </div>
        </div>
    </div>
</div>

<script>
// Auto-format code input (digits only)
document.getElementById('code').addEventListener('input', function(e) {
    this.value = this.value.replace(/\D/g, '');
    
    // Auto-submit when 6 digits are entered
    if (this.value.length === 6) {
        // Optional: Auto-submit the form
        // this.form.submit();
    }
});

// Prevent paste of non-numeric characters
document.getElementById('code').addEventListener('paste', function(e) {
    e.preventDefault();
    const pastedText = (e.clipboardData || window.clipboardData).getData('text');
    const numericOnly = pastedText.replace(/\D/g, '').substring(0, 6);
    this.value = numericOnly;
    
    // Trigger input event for auto-submit
    this.dispatchEvent(new Event('input'));
});

// Focus on input when page loads
window.addEventListener('load', function() {
    document.getElementById('code').focus();
});

// Add countdown timer for code expiry (optional enhancement)
let timeLeft = 30;
const timerElement = document.createElement('div');
timerElement.className = 'text-center mt-3';
timerElement.innerHTML = '<small class="text-muted"><i class="fas fa-hourglass-half"></i> Code refreshes in: <span id="countdown" class="fw-bold">30</span>s</small>';

// Uncomment to add timer
// document.querySelector('.card-body').appendChild(timerElement);

// const countdown = setInterval(function() {
//     timeLeft--;
//     document.getElementById('countdown').textContent = timeLeft;
//     
//     if (timeLeft <= 0) {
//         timeLeft = 30;
//     }
// }, 1000);
</script>

<?php include 'templates/footer.php'; ?>
