<?php
session_start();
require_once("public/connection.php");

// Check if staff is logged in
if (!isset($_SESSION['staff'])) {
    header("Location: login.php");
    exit;
}

$staff_id = $_SESSION['staff'];

// Fetch logged-in staff info
$staff = $connection->query("SELECT id, name FROM staff WHERE id='$staff_id' LIMIT 1")->fetch_assoc();
if (!$staff) {
    die("<div class='container mt-5'><div class='alert alert-danger'>Staff not found.</div></div>");
}

// Generate new QR token if requested
$qr_token = '';
if (isset($_POST['generate_qr'])) {
    $qr_token = hash('sha256', uniqid('EDUFLOW_QR_', true));

    $ins = $connection->prepare("
        INSERT INTO attendance_qr (qr_token, created_by)
        VALUES (?, ?)
    ");
    $ins->bind_param("si", $qr_token, $staff_id);
    $ins->execute();
} else {
    // Fetch last active QR
    $qr_token = $connection->query("
        SELECT qr_token FROM attendance_qr 
        ORDER BY id DESC LIMIT 1
    ")->fetch_assoc()['qr_token'] ?? '';
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Print School Attendance QR</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
<style>
    body { background:#f8f9fa; }
    .card { border-radius:15px; box-shadow:0 8px 25px rgba(0,0,0,.1); }
    .qr-container { text-align:center; padding:30px; }
    .qr-container img { max-width:300px; }
    .btn-print { margin-top:15px; }
</style>
</head>
<body>

<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-md-6">

            <div class="card p-4">
                <h4 class="text-center mb-3">📷 School Attendance QR Code</h4>

                <div class="qr-container">
                    <?php if($qr_token): ?>
                        <img src="https://api.qrserver.com/v1/create-qr-code/?size=300x300&data=<?= $qr_token ?>" alt="Attendance QR">
                        <p class="mt-2"><strong>Scan this QR at the school gate</strong></p>
                        <button class="btn btn-success btn-block btn-print" onclick="window.print()">🖨 Print QR Code</button>
                    <?php else: ?>
                        <p class="text-center text-danger">No active QR code. Generate one below.</p>
                    <?php endif; ?>
                </div>

                <form method="POST" class="mt-4 text-center">
                    <button name="generate_qr" class="btn btn-primary btn-block">Generate New QR Code</button>
                </form>

                <div class="mt-3 text-center">
                    <small class="text-muted">This QR is for marking staff attendance.</small>
                </div>
            </div>

        </div>
    </div>
</div>

</body>
</html>
