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

 include '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;
}



$msg = "";
if ($_SERVER['REQUEST_METHOD'] === 'GET' && isset($_GET['del']) && isset($_GET['id']) ) {
//if (isset($_GET['id'])) {
    $id = $_GET['id'];

    // Delete test record
    $sql = "DELETE FROM scanned_auths WHERE id='$id'";
    if ($conn->query($sql) === TRUE) {
        $msg= "App deleted successfully";
    } else {
        $msg =  "Error: " . $conn->error;
    }


    header("Location: generate_scanned_otp.php?success_message=" . urlencode($msg));
    exit();
}



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

?>

<?php ?>

<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>
            
            
            <?php if (isset($_GET['success_message'])): ?>
        <div class="alert alert-success">
            <?= htmlspecialchars($_GET['success_message']) ?>
        </div>
    <?php endif; ?>

    
        </div>
        <div class="alert alert-info mt-2" role="alert">
                Click on the app name to edit it. Once done, click outside the text to save changes automatically.
            </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">
                                <!-- Instructions for user -->
                                

                                <div class="card-header bg-dark text-white">
                                    <h5 contenteditable="true" id="appName" onblur="updateAppName(<?= $app['id'] ?>)">
                                        <?= 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>
                                    <a href="generate_scanned_otp.php?id=<?= $app['id'] ?>&del=ture" class="btn btn-outline-danger">Delete Scanned App</a>
                                </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>

<script>
    function updateAppName(id) {
        const appName = document.getElementById("appName").innerText;

        fetch("update_app_name.php", {
            method: "POST",
            headers: {
                "Content-Type": "application/x-www-form-urlencoded",
            },
            body: `id=${encodeURIComponent(id)}&app_name=${encodeURIComponent(appName)}`
        })
        .then(response => response.text())
        .then(data => {
            console.log("Updated:", data);
            // Optionally show a message to user
        })
        .catch(error => {
            console.error("Error updating:", error);
        });
    }
</script>


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