<?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/LaundryBagEvent.php';

require_login();
$user = current_user();

$pageTitle = 'Laundry Transactions';
require_once __DIR__ . '/../app/views/partials/header.php';

$bagId = (int)($_GET['bag_id'] ?? 0);

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);
}

$rows = [];
$bagInfo = null;

try {
  if ($bagId > 0) {
    // Bag-specific list
    $rows = LaundryBagEvent::listForBag($bagId, 300);

    $s = db()->prepare("
      SELECT b.bag_number, u.unit_code, bl.name AS building_name
      FROM laundry_bags b
      JOIN units u ON u.id = b.unit_id
      JOIN buildings bl ON bl.id = u.building_id
      WHERE b.id = ?
      LIMIT 1
    ");
    $s->execute([$bagId]);
    $bagInfo = $s->fetch();

  } else {
    // All transactions
    if (method_exists('LaundryBagEvent', 'listAll')) {
      $rows = LaundryBagEvent::listAll(400);
    } else {
      // fallback if listAll doesn't exist
      $stmt = db()->query("
        SELECT e.*, u.full_name AS staff_name
        FROM laundry_bag_events e
        LEFT JOIN users u ON u.id = e.changed_by_user_id
        ORDER BY e.created_at DESC, e.id DESC
        LIMIT 400
      ");
      $rows = $stmt->fetchAll();
    }
  }
} catch (Throwable $e) {
  $rows = [];
}
?>

<div class="container mb-3">
  <div class="d-flex justify-content-between flex-wrap gap-2 align-items-start">
    <div>
      <h5 class="page-title mb-1">Laundry Transactions</h5>
      <div class="text-muted">
        <?php if ($bagInfo): ?>
          <?= htmlspecialchars($bagInfo['building_name'] ?? '') ?> • Unit <?= htmlspecialchars($bagInfo['unit_code'] ?? '') ?> • Bag <?= htmlspecialchars($bagInfo['bag_number'] ?? '') ?>
        <?php else: ?>
          Latest laundry activity across the system.
        <?php endif; ?>
      </div>
    </div>

    <div class="d-flex gap-2 flex-wrap">
      <a class="btn btn-outline-primary" href="<?= BASE_URL ?>/laundry.php">Laundry Dashboard</a>
      <a class="btn btn-outline-secondary" href="<?= BASE_URL ?>/laundry_worklist.php">Worklist</a>
      <?php if ($bagId > 0): ?>
        <a class="btn btn-outline-secondary" href="<?= BASE_URL ?>/laundry_bag.php?bag_id=<?= (int)$bagId ?>">Back to Bag</a>
      <?php endif; ?>
    </div>
  </div>
</div>

<div class="container">

  <div class="card p-4">
    <?php if (!$rows): ?>
      <div class="text-muted">No transactions found.</div>
    <?php else: ?>

      <div class="table-responsive">
        <table class="table align-middle">
          <thead>
            <tr>
              <th style="min-width:160px;">Date</th>
              <th>Bag / Unit</th>
              <th>Item</th>
              <th>Action</th>
              <th>Status After</th>
              <th>Staff</th>
              <th style="min-width:280px;">Location</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($rows as $r): ?>
              <?php
                $lat = $r['geo_lat'] ?? null;
                $lng = $r['geo_lng'] ?? null;
                $acc = $r['geo_accuracy'] ?? null;
                $addr = $r['geo_address'] ?? '';
                $hasGeo = ($lat !== null && $lng !== null && $lat !== '' && $lng !== '');
                $gUrl = $hasGeo ? mapsUrl($lat, $lng) : '';

                // When listAll is used we likely have these extra fields
                $unitCode = $r['unit_code'] ?? '';
                $building = $r['building_name'] ?? '';
                $bagNum = $r['bag_number'] ?? '';
              ?>
              <tr>
                <td class="text-muted small"><?= htmlspecialchars($r['created_at'] ?? '') ?></td>

                <td>
                  <?php if ($bagNum || $unitCode || $building): ?>
                    <div class="fw-semibold"><?= htmlspecialchars(trim($building . ' • ' . $unitCode)) ?></div>
                    <div class="text-muted small">Bag: <?= htmlspecialchars($bagNum ?: ('#' . ($r['bag_id'] ?? ''))) ?></div>
                  <?php else: ?>
                    <div class="text-muted">Bag #<?= (int)($r['bag_id'] ?? 0) ?></div>
                  <?php endif; ?>
                </td>

                <td><?= htmlspecialchars($r['item_type'] ?? '') ?></td>
                <td><?= htmlspecialchars($r['action'] ?? '') ?></td>
                <td><?= htmlspecialchars($r['status_after'] ?? '') ?></td>
                <td><?= htmlspecialchars($r['staff_name'] ?? '—') ?></td>

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

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

    <?php endif; ?>
  </div>

</div>

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