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

require_login();

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

$inspections = Inspection::listByUnit($unitId);

// Load unit header info (for breadcrumb/title)
$unitStmt = db()->prepare("
  SELECT u.unit_code, b.name AS building_name
  FROM units u
  JOIN buildings b ON b.id = u.building_id
  WHERE u.id = ?
  LIMIT 1
");
$unitStmt->execute([$unitId]);
$unitInfo = $unitStmt->fetch();
if (!$unitInfo) exit('Unit not found.');

$pageTitle = 'Inspection History - ' . $unitInfo['unit_code'];
require_once __DIR__ . '/../app/views/partials/header.php';

function mapsUrl($lat, $lng): string {
  $lat = (string)$lat;
  $lng = (string)$lng;
  if ($lat === '' || $lng === '') return '';
  // Works on mobile/desktop
  return 'https://www.google.com/maps?q=' . rawurlencode($lat . ',' . $lng);
}
?>

<div class="container mb-3">
  <nav aria-label="breadcrumb">
    <ol class="breadcrumb mb-2">
      <li class="breadcrumb-item"><a href="<?= BASE_URL ?>/dashboard.php">Dashboard</a></li>
      <li class="breadcrumb-item"><a href="<?= BASE_URL ?>/units_list.php">Units</a></li>
      <li class="breadcrumb-item"><a href="<?= BASE_URL ?>/unit.php?id=<?= (int)$unitId ?>">Unit <?= htmlspecialchars($unitInfo['unit_code']) ?></a></li>
      <li class="breadcrumb-item active" aria-current="page">Inspection History</li>
    </ol>
  </nav>

  <div class="d-flex gap-2 flex-wrap">
    <a class="btn btn-sm btn-outline-primary" href="<?= BASE_URL ?>/unit.php?id=<?= (int)$unitId ?>">← Back to Unit</a>
    <a class="btn btn-sm btn-outline-primary" href="<?= BASE_URL ?>/units_list.php">Units List</a>
    <a class="btn btn-sm btn-outline-primary" href="<?= BASE_URL ?>/dashboard.php">Dashboard</a>
  </div>
</div>

<div class="container">

  <div class="card p-4 mb-3">
    <div class="d-flex justify-content-between flex-wrap gap-2">
      <div>
        <h5 class="page-title mb-1">Inspection History</h5>
        <div class="text-muted">
          <?= htmlspecialchars($unitInfo['building_name']) ?> • Unit <?= htmlspecialchars($unitInfo['unit_code']) ?>
        </div>
      </div>

      <a class="btn btn-primary"
         href="<?= BASE_URL ?>/scan.php?t=<?= urlencode(getUnitToken($unitId)) ?>">
        Start Inspection
      </a>
    </div>
  </div>

  <?php if (!$inspections): ?>
    <div class="card p-4">
      <div class="text-muted">No inspections recorded for this unit yet.</div>
    </div>
  <?php else: ?>

    <?php foreach ($inspections as $ins): ?>
      <?php
        $photos = Inspection::photosByInspection((int)$ins['id']);

        $before = [];
        $after = [];
        foreach ($photos as $p) {
          $type = strtolower($p['photo_type'] ?? '');
          if ($type === 'after') $after[] = $p;
          else $before[] = $p;
        }

        // Prefer inspected_at, fallback created_at
        $when = $ins['inspected_at'] ?? ($ins['created_at'] ?? '');

        $lat = $ins['geo_lat'] ?? null;
        $lng = $ins['geo_lng'] ?? null;
        $acc = $ins['geo_accuracy'] ?? null;
        $addr = $ins['geo_address'] ?? '';

        $hasGeo = ($lat !== null && $lng !== null && $lat !== '' && $lng !== '');
        $gUrl = $hasGeo ? mapsUrl($lat, $lng) : '';
      ?>

      <div class="card p-4 mb-3">
        <div class="d-flex justify-content-between flex-wrap gap-2">
          <div>
            <div class="fw-semibold">Inspection #<?= (int)$ins['id'] ?></div>

            <div class="text-muted small">
              <?= htmlspecialchars($when) ?>
              <?php if (!empty($ins['staff_name'])): ?>
                • By: <?= htmlspecialchars($ins['staff_name']) ?>
              <?php else: ?>
                • By: Unknown
              <?php endif; ?>
            </div>

            <!-- ✅ Geo Display -->
            <div class="mt-2">
              <?php if (!empty($addr)): ?>
                <div class="small">
                  <span class="text-muted">📍 Address:</span>
                  <span><?= htmlspecialchars($addr) ?></span>
                </div>
              <?php elseif ($hasGeo): ?>
                <div class="small">
                  <span class="text-muted">📍 Location:</span>
                  <span><?= htmlspecialchars($lat) ?>, <?= htmlspecialchars($lng) ?></span>
                  <?php if (!empty($acc)): ?>
                    <span class="text-muted"> (±<?= (int)$acc ?>m)</span>
                  <?php endif; ?>
                </div>
              <?php else: ?>
                <div class="small text-muted">📍 Location: Not captured</div>
              <?php endif; ?>

              <?php if ($gUrl): ?>
                <div class="mt-2">
                  <a class="btn btn-sm btn-outline-primary" target="_blank" href="<?= htmlspecialchars($gUrl) ?>">
                    Open in Google Maps
                  </a>
                </div>
              <?php endif; ?>
            </div>
          </div>

          <?php if (!empty($ins['notes'])): ?>
            <span class="badge badge-soft">Has Notes</span>
          <?php endif; ?>
        </div>

        <?php if (!empty($ins['notes'])): ?>
          <div class="mt-2 small">
            <div class="text-muted">Notes:</div>
            <div><?= nl2br(htmlspecialchars($ins['notes'])) ?></div>
          </div>
        <?php endif; ?>

        <hr>

        <div class="row g-3">
          <div class="col-md-6">
            <div class="fw-semibold mb-2">Before</div>
            <?php if (!$before): ?>
              <div class="text-muted small">No before photos.</div>
            <?php else: ?>
              <div class="d-flex flex-wrap gap-2">
                <?php foreach ($before as $p): ?>
                  <?php $path = $p['file_path'] ?? ''; ?>
                  <?php if ($path): ?>
                    <a href="<?= BASE_URL ?>/<?= ltrim($path, '/') ?>" target="_blank">
                      <img src="<?= BASE_URL ?>/<?= ltrim($path, '/') ?>"
                           style="width:130px;height:90px;object-fit:cover;border-radius:10px;border:1px solid #e6eefc;">
                    </a>
                  <?php endif; ?>
                <?php endforeach; ?>
              </div>
            <?php endif; ?>
          </div>

          <div class="col-md-6">
            <div class="fw-semibold mb-2">After</div>
            <?php if (!$after): ?>
              <div class="text-muted small">No after photos.</div>
            <?php else: ?>
              <div class="d-flex flex-wrap gap-2">
                <?php foreach ($after as $p): ?>
                  <?php $path = $p['file_path'] ?? ''; ?>
                  <?php if ($path): ?>
                    <a href="<?= BASE_URL ?>/<?= ltrim($path, '/') ?>" target="_blank">
                      <img src="<?= BASE_URL ?>/<?= ltrim($path, '/') ?>"
                           style="width:130px;height:90px;object-fit:cover;border-radius:10px;border:1px solid #e6eefc;">
                    </a>
                  <?php endif; ?>
                <?php endforeach; ?>
              </div>
            <?php endif; ?>
          </div>
        </div>

      </div>
    <?php endforeach; ?>

  <?php endif; ?>

</div>

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

<?php
function getUnitToken(int $unitId): string {
  try {
    $s = db()->prepare("SELECT qr_token FROM units WHERE id=? LIMIT 1");
    $s->execute([$unitId]);
    $r = $s->fetch();
    return (string)($r['qr_token'] ?? '');
  } catch (Throwable $e) {
    return '';
  }
}
?>
