<?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/LaundryBag.php';
require_once __DIR__ . '/../app/models/LaundryItemType.php';

require_login();
$user = current_user();

$building = trim((string)($_GET['building'] ?? ''));
$print = isset($_GET['print']) ? 1 : 0;

$buildings = LaundryBag::listBuildingsWithBags();

// Pull CURRENT state: every bag item row + unit/building/bag
$sql = "
  SELECT
    bi.bag_id,
    bi.item_type,
    bi.status,
    bi.updated_at,
    b.bag_number,
    b.unit_id,
    un.unit_code,
    bl.name AS building_name,
    it.name AS item_name
  FROM laundry_bag_items bi
  JOIN laundry_bags b ON b.id = bi.bag_id
  JOIN units un ON un.id = b.unit_id
  JOIN buildings bl ON bl.id = un.building_id
  LEFT JOIN laundry_item_types it ON it.code = bi.item_type
";
$params = [];
if ($building !== '') {
  $sql .= " WHERE bl.name = ? ";
  $params[] = $building;
}
$sql .= " ORDER BY bl.name ASC, un.unit_code ASC, b.bag_number ASC, bi.item_type ASC ";

$stmt = db()->prepare($sql);
$stmt->execute($params);
$rows = $stmt->fetchAll();

// Group by buckets based on CURRENT status
$groups = [
  'pickups' => [],     // dirty
  'cleaning' => [],    // picked_up
  'deliveries' => [],  // delivered
  'clean' => [],       // clean
];

foreach ($rows as $r) {
  $st = strtolower((string)($r['status'] ?? 'dirty'));
  if ($st === 'dirty') $groups['pickups'][] = $r;
  elseif ($st === 'picked_up') $groups['cleaning'][] = $r;
  elseif ($st === 'delivered') $groups['deliveries'][] = $r;
  elseif ($st === 'clean') $groups['clean'][] = $r;
}

function sectionTitle(string $key): string {
  return match($key) {
    'pickups' => 'Pickups Needed (Dirty)',
    'cleaning' => 'Cleaning Queue (Picked Up)',
    'deliveries' => 'Deliveries Needed (Delivered)',
    'clean' => 'Completed (Clean)',
    default => $key,
  };
}

$pageTitle = 'Laundry Worklist';
if (!$print) require_once __DIR__ . '/../app/views/partials/header.php';
?>

<?php if ($print): ?>
<html>
<head>
  <meta charset="utf-8">
  <title><?= htmlspecialchars($pageTitle) ?></title>
  <style>
    body { font-family: Arial, sans-serif; padding: 16px; }
    h2 { margin: 0 0 8px 0; }
    .muted { color:#666; font-size:12px; margin-bottom:10px; }
    h3 { margin: 18px 0 8px 0; }
    table { width: 100%; border-collapse: collapse; }
    th, td { border: 1px solid #ddd; padding: 8px; font-size: 12px; }
    th { background: #f5f5f5; text-align: left; }
  </style>
</head>
<body>
<?php endif; ?>

<div class="<?= $print ? '' : 'container' ?>">

  <?php if (!$print): ?>
    <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">Laundry Worklist</h5>
          <div class="text-muted">Based on CURRENT bag item status (not events).</div>
        </div>
        <div class="d-flex gap-2">
          <a class="btn btn-outline-primary" href="<?= BASE_URL ?>/laundry.php">Laundry Dashboard</a>
          <a class="btn btn-outline-secondary" href="<?= BASE_URL ?>/laundry_today.php">Schedule</a>
          <a class="btn btn-outline-secondary" href="<?= BASE_URL ?>/laundry_items.php">Bag Items (CRUD)</a>
        </div>
      </div>
    </div>

    <div class="card p-4 mb-3">
      <form method="get" class="row g-2 align-items-end">
        <div class="col-md-6">
          <label class="form-label">Building</label>
          <select class="form-select" name="building">
            <option value="">All buildings</option>
            <?php foreach ($buildings as $b): ?>
              <?php $bn = (string)($b['building_name'] ?? ''); ?>
              <option value="<?= htmlspecialchars($bn) ?>" <?= $bn === $building ? 'selected' : '' ?>>
                <?= htmlspecialchars($bn) ?>
              </option>
            <?php endforeach; ?>
          </select>
        </div>

        <div class="col-md-6 d-flex gap-2">
          <button class="btn btn-primary">Apply</button>
          <a class="btn btn-outline-secondary" href="<?= BASE_URL ?>/laundry_worklist.php">Reset</a>
          <a class="btn btn-outline-secondary" target="_blank"
             href="<?= BASE_URL ?>/laundry_worklist.php?building=<?= urlencode($building) ?>&print=1">
            Print
          </a>
        </div>
      </form>
    </div>
  <?php else: ?>
    <h2>Laundry Worklist</h2>
    <div class="muted">
      Current status view
      <?php if ($building): ?> • Building: <strong><?= htmlspecialchars($building) ?></strong><?php endif; ?>
    </div>
  <?php endif; ?>

  <?php foreach ($groups as $key => $list): ?>
    <h3><?= htmlspecialchars(sectionTitle($key)) ?> (<?= (int)count($list) ?>)</h3>

    <?php if (!$list): ?>
      <div class="<?= $print ? 'muted' : 'text-muted small' ?>">None.</div>
      <?php continue; ?>
    <?php endif; ?>

    <?php if (!$print): ?><div class="card p-0 mb-3"><?php endif; ?>

    <div class="table-responsive">
      <table class="table table-striped align-middle mb-0">
        <thead>
          <tr>
            <th>Building</th>
            <th>Unit</th>
            <th>Bag #</th>
            <th>Item</th>
            <th>Status</th>
            <th>Last Updated</th>
            <?php if (!$print): ?><th>Actions</th><?php endif; ?>
          </tr>
        </thead>
        <tbody>
          <?php foreach ($list as $r): ?>
            <tr>
              <td><?= htmlspecialchars($r['building_name'] ?? '') ?></td>
              <td>
                <?php if (!$print): ?>
                  <a href="<?= BASE_URL ?>/unit.php?id=<?= (int)($r['unit_id'] ?? 0) ?>">
                    <?= htmlspecialchars($r['unit_code'] ?? '') ?>
                  </a>
                <?php else: ?>
                  <?= htmlspecialchars($r['unit_code'] ?? '') ?>
                <?php endif; ?>
              </td>
              <td>
                <?php if (!$print): ?>
                  <a href="<?= BASE_URL ?>/laundry_bag.php?bag_id=<?= (int)($r['bag_id'] ?? 0) ?>">
                    <?= htmlspecialchars($r['bag_number'] ?? '') ?>
                  </a>
                <?php else: ?>
                  <?= htmlspecialchars($r['bag_number'] ?? '') ?>
                <?php endif; ?>
              </td>
              <td><?= htmlspecialchars($r['item_name'] ?: $r['item_type']) ?></td>
              <td><?= htmlspecialchars(ucwords(str_replace('_',' ', (string)($r['status'] ?? '')))) ?></td>
              <td><?= htmlspecialchars($r['updated_at'] ?? '') ?></td>
              <?php if (!$print): ?>
                <td>
                  <a class="btn btn-sm btn-primary" href="<?= BASE_URL ?>/laundry_bag.php?bag_id=<?= (int)($r['bag_id'] ?? 0) ?>">
                    Open
                  </a>
                  <a class="btn btn-sm btn-outline-secondary" href="<?= BASE_URL ?>/laundry_transactions.php?bag_id=<?= (int)($r['bag_id'] ?? 0) ?>">
                    Transactions
                  </a>
                </td>
              <?php endif; ?>
            </tr>
          <?php endforeach; ?>
        </tbody>
      </table>
    </div>

    <?php if (!$print): ?></div><?php endif; ?>

  <?php endforeach; ?>

</div>

<?php if ($print): ?></body></html><?php else: ?>
<?php require_once __DIR__ . '/../app/views/partials/footer.php'; ?>
<?php endif; ?>
