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

require_login();

// Accept both ?t= and ?token=
$token = trim($_GET['t'] ?? ($_GET['token'] ?? ''));

$pageTitle = 'Unit Scan';
require_once __DIR__ . '/../app/views/partials/header.php';

if ($token === ''): ?>
  <div class="container-narrow mx-auto">
    <div class="card p-4">
      <h5 class="page-title mb-2">Invalid QR</h5>
      <div class="text-muted">
        This page must be opened from a QR code scan.
      </div>
      <div class="mt-3">
        Ask your admin to generate a Unit QR and scan it again.
      </div>
    </div>
  </div>
<?php
require_once __DIR__ . '/../app/views/partials/footer.php';
exit;
endif;

$unit = Unit::findByToken($token);

if (!$unit): ?>
  <div class="container-narrow mx-auto">
    <div class="card p-4">
      <h5 class="page-title mb-2">QR Not Found</h5>
      <div class="text-muted">
        This QR token is not registered in the system.
      </div>
      <div class="mt-3">
        Please contact admin to reprint the correct QR code for this unit.
      </div>
    </div>
  </div>
<?php
require_once __DIR__ . '/../app/views/partials/footer.php';
exit;
endif;
?>

<div class="container-narrow mx-auto">
  <div class="card p-4">
    <h5 class="page-title mb-3">Unit Information</h5>

    <ul class="list-group list-group-flush mb-3">
      <li class="list-group-item"><strong>Building:</strong> <?= htmlspecialchars($unit['building_name']) ?></li>
      <li class="list-group-item"><strong>Unit:</strong> <?= htmlspecialchars($unit['unit_code']) ?></li>
      <li class="list-group-item"><strong>Floor:</strong> <?= htmlspecialchars($unit['floor']) ?></li>
      <li class="list-group-item"><strong>Status:</strong> <?= htmlspecialchars($unit['status']) ?></li>
    </ul>

    <a href="inspection_new.php?unit_id=<?= (int)$unit['id'] ?>" class="btn btn-primary w-100 mb-2">
      Start Inspection
    </a>

    <a href="unit.php?id=<?= (int)$unit['id'] ?>" class="btn btn-outline-primary w-100">
      View Full Unit Profile
    </a>
  </div>
</div>

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