<?php
require 'auth.php';
requireLoginBefore2FA();

require 'vendor/autoload.php';
require 'db.php';

$ga = new PHPGangsta_GoogleAuthenticator();
$message = '';
$user_id = $_SESSION['user_id'] ?? null;

// Fetch user info
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$user_id]);
$user = $stmt->fetch();

if (!$user) {
    die('User not found.');
}

// Load or generate secret
if (empty($user['totp_secret']) && empty($_SESSION['totp_secret_temp'])) {
    // First-time login: generate temp secret and store in session
    $_SESSION['totp_secret_temp'] = $ga->createSecret();
}

$secret = $_SESSION['totp_secret'] ?? $_SESSION['totp_secret_temp'] ?? null;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $code = $_POST['code'] ?? '';

    if (!$secret) {
        die('No secret found.');
    }

    if ($ga->verifyCode($secret, $code, 2)) {
        // First-time setup: store the verified secret
        if (empty($user['totp_secret'])) {
            $stmt = $pdo->prepare("UPDATE users SET totp_secret = ? WHERE id = ?");
            $stmt->execute([$secret, $user_id]);
        }

        $_SESSION['2fa_verified'] = true;
        $_SESSION['totp_secret'] = $secret;
        unset($_SESSION['totp_secret_temp']);

        header('Location: index.php');
        exit;
    } else {
        $message = 'Invalid 2FA code.';
    }
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>2FA Verification - SuperArc</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="bg-light d-flex align-items-center justify-content-center vh-100">
    <div class="card shadow p-4" style="width: 100%; max-width: 400px;">
        <h3 class="text-center mb-3">2FA Verification</h3>

        <?php if ($message): ?>
            <div class="alert alert-danger"><?= htmlspecialchars($message) ?></div>
        <?php endif; ?>

        <?php if (!empty($_SESSION['totp_secret_temp'])): ?>
            <div class="mb-3 text-center">
                <p>Scan this QR code in your authenticator app:</p>
                <img src="<?= htmlspecialchars($ga->getQRCodeGoogleUrl('AlarmDrift', $_SESSION['totp_secret_temp'])) ?>" alt="QR Code">
            </div>
        <?php endif; ?>

        <form method="POST">
            <div class="mb-3">
                <label for="code" class="form-label">Enter your 2FA code</label>
                <input type="text" name="code" id="code" class="form-control" required autofocus>
            </div>
            <button type="submit" class="btn btn-primary w-100">Verify</button>
        </form>
    </div>
</body>
</html>
