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

require_login();
$user = current_user();

// Admin should not use staff dashboard
if (($user['role'] ?? '') === 'admin') {
  header('Location: ' . BASE_URL . '/dashboard.php');
  exit;
}

$pageTitle = 'Staff Dashboard';
require_once __DIR__ . '/../app/views/partials/header.php';

$recentInspections = [];
$recentLaundry = [];

try {
  $s = db()->prepare("
    SELECT i.id, i.unit_id, i.inspected_at, i.geo_address, i.geo_lat, i.geo_lng, i.geo_accuracy,
           u.unit_code, b.name AS building_name
    FROM inspections i
    JOIN units u ON u.id = i.unit_id
    JOIN buildings b ON b.id = u.building_id
    WHERE i.staff_user_id = ?
    ORDER BY i.inspected_at DESC, i.id DESC
    LIMIT 10
  ");
  $s->execute([(int)$user['id']]);
  $recentInspections = $s->fetchAll();
} catch (Throwable $e) {}

try {
  $s = db()->prepare("
    SELECT e.id, e.bag_id, e.item_type, e.action, e.status_after, e.created_at,
           e.geo_address, e.geo_lat, e.geo_lng, e.geo_accuracy,
           lb.bag_number, u.unit_code, b.name AS building_name
    FROM laundry_bag_events e
    JOIN laundry_bags lb ON lb.id = e.bag_id
    JOIN units u ON u.id = lb.unit_id
    JOIN buildings b ON b.id = u.building_id
    WHERE e.changed_by_user_id = ?
    ORDER BY e.created_at DESC, e.id DESC
    LIMIT 10
  ");
  $s->execute([(int)$user['id']]);
  $recentLaundry = $s->fetchAll();
} catch (Throwable $e) {}

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

function locText($addr, $lat, $lng, $acc): string {
  $addr = trim((string)$addr);
  if ($addr !== '') return $addr;
  if ($lat !== null && $lng !== null && $lat !== '' && $lng !== '') {
    $t = $lat . ', ' . $lng;
    if (!empty($acc)) $t .= " (±" . (int)$acc . "m)";
    return $t;
  }
  return 'Not captured';
}
?>

<div class="container">

  <div class="card p-4 mb-3">
    <div class="d-flex justify-content-between align-items-start flex-wrap gap-2">
      <div>
        <h5 class="page-title mb-1">Staff Dashboard</h5>
        <div class="text-muted"><?= htmlspecialchars($user['full_name'] ?? '') ?></div>
      </div>
      <div>
        <span class="badge bg-light text-dark"><?= htmlspecialchars($user['role'] ?? '') ?></span>
      </div>
    </div>
  </div>

  <!-- Quick actions -->
  <div class="row g-3 mb-3">
    <div class="col-md-4">
      <div class="card p-4 h-100">
        <h6 class="mb-2">Inspection</h6>
        <a href="<?= BASE_URL ?>/scan_camera.php" class="btn btn-primary w-100">Scan QR (Camera)</a>
        <div class="text-muted small mt-2">Scan a unit QR to start an inspection.</div>
      </div>
    </div>

    <div class="col-md-4">
      <div class="card p-4 h-100">
        <h6 class="mb-2">Laundry</h6>
        <a href="<?= BASE_URL ?>/laundry.php" class="btn btn-outline-primary w-100 mb-2">Laundry Dashboard</a>
        <a href="<?= BASE_URL ?>/laundry_worklist.php" class="btn btn-outline-secondary w-100">Worklist</a>
        <div class="text-muted small mt-2">Update bag status and record transactions.</div>
      </div>
    </div>

    <div class="col-md-4">
      <div class="card p-4 h-100">
        <h6 class="mb-2">Transactions</h6>
        <a href="<?= BASE_URL ?>/laundry_transactions.php" class="btn btn-outline-primary w-100">View All Laundry Transactions</a>
        <div class="text-muted small mt-2">Includes address when captured.</div>
      </div>
    </div>
  </div>

  <!-- Recent inspections -->
  <div class="card p-4 mb-3">
    <h6 class="mb-0">Your Latest Inspections</h6>
    <hr>

    <?php if (!$recentInspections): ?>
      <div class="text-muted">No inspections yet.</div>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table align-middle">
          <thead>
            <tr>
              <th>Date</th>
              <th>Unit</th>
              <th style="min-width:320px;">Location</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($recentInspections as $r): ?>
              <?php
                $loc = locText($r['geo_address'] ?? '', $r['geo_lat'] ?? null, $r['geo_lng'] ?? null, $r['geo_accuracy'] ?? null);
                $m = mapsUrl($r['geo_lat'] ?? '', $r['geo_lng'] ?? '');
              ?>
              <tr>
                <td class="text-muted small"><?= htmlspecialchars($r['inspected_at'] ?? '') ?></td>
                <td>
                  <div class="fw-semibold"><?= htmlspecialchars($r['building_name'] ?? '') ?> • <?= htmlspecialchars($r['unit_code'] ?? '') ?></div>
                  <div class="text-muted small">Inspection #<?= (int)$r['id'] ?></div>
                </td>
                <td class="small"><?= htmlspecialchars($loc) ?></td>
                <td class="text-end">
                  <?php if ($m): ?>
                    <a class="btn btn-sm btn-outline-primary" target="_blank" href="<?= htmlspecialchars($m) ?>">Maps</a>
                  <?php endif; ?>
                  <a class="btn btn-sm btn-outline-secondary" href="<?= BASE_URL ?>/unit_inspections.php?unit_id=<?= (int)$r['unit_id'] ?>">History</a>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </div>

  <!-- Recent laundry -->
  <div class="card p-4 mb-3">
    <h6 class="mb-0">Your Latest Laundry Activity</h6>
    <hr>

    <?php if (!$recentLaundry): ?>
      <div class="text-muted">No laundry actions yet.</div>
    <?php else: ?>
      <div class="table-responsive">
        <table class="table align-middle">
          <thead>
            <tr>
              <th>Date</th>
              <th>Bag / Unit</th>
              <th>Action</th>
              <th style="min-width:320px;">Location</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($recentLaundry as $r): ?>
              <?php
                $loc = locText($r['geo_address'] ?? '', $r['geo_lat'] ?? null, $r['geo_lng'] ?? null, $r['geo_accuracy'] ?? null);
                $m = mapsUrl($r['geo_lat'] ?? '', $r['geo_lng'] ?? '');
              ?>
              <tr>
                <td class="text-muted small"><?= htmlspecialchars($r['created_at'] ?? '') ?></td>
                <td>
                  <div class="fw-semibold"><?= htmlspecialchars($r['building_name'] ?? '') ?> • <?= htmlspecialchars($r['unit_code'] ?? '') ?></div>
                  <div class="text-muted small">Bag <?= htmlspecialchars($r['bag_number'] ?? '') ?></div>
                </td>
                <td>
                  <div class="small">
                    <strong><?= htmlspecialchars($r['action'] ?? '') ?></strong>
                    — <?= htmlspecialchars($r['item_type'] ?? '') ?>
                    (<?= htmlspecialchars($r['status_after'] ?? '') ?>)
                  </div>
                </td>
                <td class="small"><?= htmlspecialchars($loc) ?></td>
                <td class="text-end">
                  <?php if ($m): ?>
                    <a class="btn btn-sm btn-outline-primary" target="_blank" href="<?= htmlspecialchars($m) ?>">Maps</a>
                  <?php endif; ?>
                  <a class="btn btn-sm btn-outline-secondary" href="<?= BASE_URL ?>/laundry_bag.php?bag_id=<?= (int)$r['bag_id'] ?>">Open Bag</a>
                </td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>
    <?php endif; ?>
  </div>

</div>

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