<?php
require_once __DIR__ . '/../app/config/config.php';
require_once __DIR__ . '/../app/middleware/auth.php';
require_once __DIR__ . '/../app/config/db.php';

require_login();

// Admin only (can change later if needed)
if ($_SESSION['user']['role'] !== 'admin') {
    http_response_code(403);
    exit('Forbidden');
}

$unitId = (int)($_GET['id'] ?? 0);
if (!$unitId) exit('Invalid unit.');

$stmt = db()->prepare("
  SELECT u.id, u.unit_code, u.qr_token, b.name AS building_name
  FROM units u
  JOIN buildings b ON b.id = u.building_id
  WHERE u.id = ?
  LIMIT 1
");
$stmt->execute([$unitId]);
$unit = $stmt->fetch();

if (!$unit) exit('Unit not found.');
if (!$unit['qr_token']) exit('This unit has no QR token.');

$qrUrl = BASE_URL . '/scan.php?t=' . $unit['qr_token'];
$qrImg = 'https://api.qrserver.com/v1/create-qr-code/?size=320x320&data=' . urlencode($qrUrl);

$pageTitle = 'Unit QR';
require_once __DIR__ . '/../app/views/partials/header.php';
?>

<div class="container-narrow mx-auto">
  <div class="mb-3">
    <a class="btn btn-sm btn-outline-primary" href="<?= BASE_URL ?>/unit.php?id=<?= (int)$unit['id'] ?>">
      ← Back to Unit Profile
    </a>
  </div>

  <div class="card p-4">
    <h5 class="page-title mb-1">QR Code</h5>
    <div class="text-muted mb-3">
      <?= htmlspecialchars($unit['building_name']) ?> • Unit <?= htmlspecialchars($unit['unit_code']) ?>
    </div>

    <div class="alert alert-info">
      <div class="small mb-1">QR Scan URL:</div>
      <a href="<?= htmlspecialchars($qrUrl) ?>" target="_blank"><?= htmlspecialchars($qrUrl) ?></a>
    </div>

    <div class="text-center">
      <img src="<?= htmlspecialchars($qrImg) ?>" class="img-fluid rounded border" style="max-width: 320px;" alt="QR Code">
      <div class="mt-3 d-flex justify-content-center gap-2 flex-wrap">
        <a class="btn btn-outline-primary" href="<?= htmlspecialchars($qrImg) ?>" target="_blank">
          Open QR Image
        </a>
        <button class="btn btn-primary" type="button" onclick="window.print()">
          Print QR
        </button>
      </div>
      <div class="small text-muted mt-2">Print and place this on the unit door.</div>
    </div>
  </div>
</div>

<?php require_once __DIR__ . '/../app/views/partials/footer.php'; ?>
