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

require_once 'api_header.php';

use OTPHP\TOTP;

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

$user_id = $_SESSION['user_id'];

// Fetch all scanned QR codes for 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();

$authApps = [];
while ($row = $result->fetch_assoc()) {
    $authApps[] = $row;
}
$stmt->close();
$conn->close();
?>



<div class="container mt-5">
    <div class="card shadow-sm">
        <div class="card-header bg-primary text-white text-center">
            <h3><i class="fas fa-key"></i> Time-Based OTPs</h3>
        </div>
        <div class="card-body">
            <?php if (empty($authApps)): ?>
                <div class="alert alert-warning text-center">
                    <i class="fas fa-exclamation-circle"></i> No scanned QR codes found. Please scan a QR code first.
                </div>
            <?php else: ?>
                <div class="row">
                    <?php foreach ($authApps as $app): ?>
                        <div class="col-md-6 col-lg-4">
                            <div class="card text-center shadow-sm mb-4">
                                <div class="card-header bg-dark text-white">
                                    <h5><?= htmlspecialchars($app['app_name']) ?></h5>
                                </div>
                                <div class="card-body">
                                    <h4 class="text-success fw-bold" id="otp-<?= $app['id'] ?>">Generating...</h4>
                                    <p class="text-muted">Expires in <span id="timer-<?= $app['id'] ?>">30</span> seconds</p>
                                    <button class="btn btn-outline-primary" onclick="updateOTPs()">Refresh OTP</button>
                                </div>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
    function updateOTPs() {
        fetch('../fetch_scanned_otp.php')
            .then(response => response.json())
            .then(data => {
                data.forEach(app => {
                    document.getElementById('otp-' + app.id).innerText = app.otp;
                });
            })
            .catch(error => console.error("Error fetching OTPs:", error));
    }

    function startTimer() {
        let seconds = 30;
        setInterval(() => {
            seconds--;
            document.querySelectorAll("[id^='timer-']").forEach(el => el.innerText = seconds);
            if (seconds === 0) {
                updateOTPs();
                seconds = 30;
            }
        }, 1000);
    }

    updateOTPs();
    startTimer();
</script>

<?php require_once 'api_footer.php'; ?>
