<?php
require 'vendor/autoload.php';
require 'db.php'; // Database connection file
use OTPHP\TOTP;

session_start();
if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

$user_id = $_SESSION['user_id'];

// Retrieve all scanned QR codes linked to this user
$stmt = $conn->prepare("SELECT id, app_name, secret FROM scanned_auths WHERE user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$result = $stmt->get_result();

$scannedApps = [];
while ($row = $result->fetch_assoc()) {
    if (!empty($row['secret'])) {
        $totp = TOTP::create($row['secret']);
        $scannedApps[] = [
            'id' => $row['id'],
            'app_name' => htmlspecialchars($row['app_name']),
            'otp' => $totp->now()
        ];
    }
}

$stmt->close();
$conn->close();
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Scanned QR Codes & OTPs</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
        }
        .container {
            max-width: 600px;
            margin-top: 50px;
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
        }
        .otp-box {
            font-size: 24px;
            font-weight: bold;
            color: #28a745;
            padding: 10px;
            border: 2px dashed #28a745;
            text-align: center;
            border-radius: 5px;
        }
    </style>
</head>
<body>

<div class="container">
    <h2 class="text-center">🔐 Your Scanned QR Codes & OTPs</h2>

    <?php if (empty($scannedApps)) : ?>
        <div class="alert alert-warning text-center">⚠ No scanned QR codes found. Please scan one first.</div>
    <?php else: ?>
        <ul class="list-group">
            <?php foreach ($scannedApps as $app): ?>
                <li class="list-group-item d-flex justify-content-between align-items-center">
                    <strong><?= $app['app_name']; ?></strong>
                    <span class="otp-box"><?= $app['otp']; ?></span>
                </li>
            <?php endforeach; ?>
        </ul>
    <?php endif; ?>

    <div class="text-center mt-3">
        <a href="dashboard.php" class="btn btn-primary">🔙 Back to Dashboard</a>
    </div>
</div>

</body>
</html>
