<?php
define('SECURE_ACCESS', true);
require_once __DIR__ . '/../includes/config.php';
require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/auth.php';

if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

if (!isset($_SESSION['2fa_pending_user_id'])) {
    header("Location: login");
    exit();
}

$error = '';
$user_id = $_SESSION['2fa_pending_user_id'];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $code = trim($_POST['code'] ?? '');
    
    if (empty($code)) {
        $error = "Please enter the 6-digit code.";
    } else {
        try {
            $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
            $stmt->execute([$user_id]);
            $user = $stmt->fetch();

            if (!$user) {
                $error = "User not found.";
            } elseif ($user['two_factor_code'] !== $code) {
                $error = "Invalid verification code.";
            } elseif (strtotime($user['two_factor_expires']) < time()) {
                $error = "Verification code has expired. Please log in again to request a new code.";
            } else {
                // Clear the 2fa token
                $pdo->prepare("UPDATE users SET two_factor_code = NULL, two_factor_expires = NULL WHERE id = ?")->execute([$user_id]);
                
                // Populate session
                session_regenerate_id(true);
                $_SESSION['user_id'] = $user['id'];
                $_SESSION['username'] = $user['username'];
                $_SESSION['email'] = $user['email'];
                $_SESSION['role'] = $user['role'];
                $_SESSION['status'] = $user['status'];
                
                $redirect = $_SESSION['2fa_redirect'] ?? '';
                
                // Unset temp vars
                unset($_SESSION['2fa_pending_user_id']);
                unset($_SESSION['2fa_redirect']);
                
                if (!empty($redirect) && preg_match('/^[a-z0-9_\-\.\/]+\.php(\?[a-z0-9_&=\-\.\/\%]*)?$/i', $redirect)) {
                    header("Location: " . $redirect);
                } else {
                    header("Location: dashboard");
                }
                exit();
            }
        } catch (PDOException $e) {
            $error = "Database error: " . $e->getMessage();
        }
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Two-Factor Authentication</title>
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css" rel="stylesheet">
</head>
<body class="d-flex align-items-center min-vh-100 bg-light">
    <div class="container">
        <div class="row justify-content-center">
            <div class="col-md-6 col-lg-5">
                <div class="card shadow-sm border-0 rounded-4">
                    <div class="card-body p-4 p-md-5">
                        <div class="text-center mb-4">
                            <i class="bi bi-shield-lock-fill text-primary display-4"></i>
                            <h2 class="h4 mt-3 fw-bold text-dark">Two-Factor Authentication</h2>
                            <p class="text-secondary small">We've sent a 6-digit code to your email address.</p>
                        </div>
                        
                        <?php if ($error): ?>
                            <div class="alert alert-danger small rounded-3 py-2">
                                <i class="bi bi-exclamation-triangle me-1"></i><?= htmlspecialchars($error) ?>
                            </div>
                        <?php endif; ?>
                        
                        <form method="POST" action="">
                            <div class="mb-4">
                                <label for="code" class="form-label fw-semibold small text-dark">Verification Code</label>
                                <input type="text" name="code" id="code" class="form-control form-control-lg bg-light border-0" placeholder="123456" required autofocus autocomplete="off" maxlength="6" pattern="\d{6}">
                            </div>
                            <div class="d-grid">
                                <button type="submit" class="btn btn-primary btn-lg fw-bold rounded-3 shadow-sm">Verify & Log In</button>
                            </div>
                        </form>
                        
                        <div class="text-center mt-4">
                            <a href="login" class="text-decoration-none small text-secondary">Back to Login</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
