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

require_login();
$user = current_user();

if (($user['role'] ?? '') !== 'admin') {
  http_response_code(403);
  exit('Forbidden');
}

$events = LaundryBagEvent::listAll(300);

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

<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">All Laundry Transactions</h5>
        <div class="text-muted">Latest 300 events across all units.</div>
      </div>
      <a class="btn btn-outline-primary" href="<?= BASE_URL ?>/dashboard.php">Dashboard</a>
    </div>
  </div>

  <div class="card p-4">
    <div class="table-responsive">
      <table class="table table-striped align-middle">
        <thead>
          <tr>
            <th>Date/Time</th>
            <th>Building</th>
            <th>Unit</th>
            <th>Bag #</th>
            <th>Item</th>
            <th>Action</th>
            <th>Status After</th>
            <th>By</th>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($events as $e): ?>
            <tr>
              <td><?= htmlspecialchars($e['created_at'] ?? '') ?></td>
              <td><?= htmlspecialchars($e['building_name'] ?? '') ?></td>
              <td>
                <a href="<?= BASE_URL ?>/unit.php?id=<?= (int)($e['unit_id'] ?? 0) ?>">
                  <?= htmlspecialchars($e['unit_code'] ?? '') ?>
                </a>
              </td>
              <td>
                <a href="<?= BASE_URL ?>/laundry_transactions.php?bag_id=<?= (int)($e['bag_id'] ?? 0) ?>">
                  <?= htmlspecialchars($e['bag_number'] ?? '') ?>
                </a>
              </td>
              <td><?= htmlspecialchars(ucfirst($e['item_type'] ?? '')) ?></td>
              <td><code><?= htmlspecialchars($e['action'] ?? '') ?></code></td>
              <td><?= htmlspecialchars(ucwords(str_replace('_',' ', $e['status_after'] ?? ''))) ?></td>
              <td><?= htmlspecialchars($e['staff_name'] ?? 'Unknown') ?></td>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>
  </div>

</div>

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