<?php
require 'vendor/autoload.php';
require 'db_config.php'; // Database connection file
include 'header.php';

use OTPHP\TOTP;

// Ensure the user is logged in
//session_start();
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id'];

// Get user's secret from the database
$stmt = $pdo->prepare("SELECT secret FROM authentications WHERE user_id = ?");
$stmt->execute([$user_id]);
$auth = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$auth) {
    die("<div class='container mt-5 text-center'>
            <div class='alert alert-danger'>❌ No authentication found. Please generate a QR code first.</div>
        </div>");
}

$secret = $auth['secret'];
$totp = TOTP::create($secret);

// Generate the current OTP
$current_otp = $totp->now();
?>

<div class="container mt-5">
    <div class="card shadow-lg p-4">
        <h2 class="text-center mb-4">🔐 One-Time Password (OTP)</h2>

        <div class="alert alert-info text-center">
            <h3 class="display-4"><?= $current_otp; ?></h3>
            <p class="mb-0">This OTP expires in <strong>30 seconds</strong>. Use it quickly!</p>
        </div>

        <div class="text-center mt-3">
            <a href="generate_otp.php" class="btn btn-primary">🔄 Generate New OTP</a>
            <a href="dashboard.php" class="btn btn-secondary">🏠 Back to Dashboard</a>
        </div>
    </div>
</div>

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