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

require_login();
$user = current_user();

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

$mode = (string)($_GET['mode'] ?? 'today'); // today|week|custom
$building = trim((string)($_GET['building'] ?? ''));
$print = isset($_GET['print']) ? 1 : 0;

// Date calculations
if ($mode === 'week') {
  $start = new DateTime('monday this week');
  $end = (clone $start)->modify('+7 days');
} elseif ($mode === 'custom') {
  $from = (string)($_GET['from'] ?? '');
  $to = (string)($_GET['to'] ?? '');
  $start = DateTime::createFromFormat('Y-m-d', $from) ?: new DateTime('today');
  $end = DateTime::createFromFormat('Y-m-d', $to) ?: new DateTime('today');
  $end = (clone $end)->modify('+1 day'); // include full "to" day
} else {
  $start = new DateTime('today');
  $end = (clone $start)->modify('+1 day');
}

$startStr = $start->format('Y-m-d H:i:s');
$endStr = $end->format('Y-m-d H:i:s');

// Fetch events in range
$events = LaundryBagEvent::listByDateRange($startStr, $endStr, $building ?: null, 5000);
$buildings = LaundryBag::listBuildingsWithBags();

/**
 * Deduplicate: keep latest event per (bag_id + item_type)
 * listByDateRange already orders newest first, but we’ll be safe.
 */
usort($events, function($a, $b) {
  $ta = strtotime($a['created_at'] ?? '') ?: 0;
  $tb = strtotime($b['created_at'] ?? '') ?: 0;
  if ($ta === $tb) return ((int)($b['id'] ?? 0)) <=> ((int)($a['id'] ?? 0));
  return $tb <=> $ta;
});

$latest = []; // key = "bagId|itemType" => event row
foreach ($events as $e) {
  $k = (int)($e['bag_id'] ?? 0) . '|' . (string)($e['item_type'] ?? '');
  if (!isset($latest[$k])) {
    $latest[$k] = $e;
  }
}

/**
 * Group by action bucket
 * - Pickups: action picked_up OR status_after picked_up
 * - Cleaning: action cleaning
 * - Deliveries: action delivered OR status_after delivered
 * - Other: marked_clean / marked_dirty
 */
$groups = [
  'pickups' => [],
  'cleaning' => [],
  'deliveries' => [],
  'other' => [],
];

foreach ($latest as $row) {
  $action = (string)($row['action'] ?? '');
  $statusAfter = (string)($row['status_after'] ?? '');

  if ($action === 'cleaning') {
    $groups['cleaning'][] = $row;
  } elseif ($action === 'picked_up' || $statusAfter === 'picked_up') {
    $groups['pickups'][] = $row;
  } elseif ($action === 'delivered' || $statusAfter === 'delivered') {
    $groups['deliveries'][] = $row;
  } else {
    $groups['other'][] = $row;
  }
}

function niceAction(string $a): string {
  return match($a) {
    'picked_up' => 'Picked up',
    'cleaning' => 'Cleaning',
    'delivered' => 'Delivered',
    'marked_clean' => 'Marked clean',
    'marked_dirty' => 'Marked dirty',
    default => $a,
  };
}

function niceStatus(string $s): string {
  return ucwords(str_replace('_', ' ', strtolower($s)));
}

function sectionTitle(string $key): string {
  return match($key) {
    'pickups' => 'Pickups',
    'cleaning' => 'Cleaning',
    'deliveries' => 'Deliveries',
    'other' => 'Other Updates',
    default => $key,
  };
}

$statusOptions = [
  '' => 'All buildings',
];

$pageTitle = 'Laundry Schedule';
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: 12px; }
    h3 { margin: 18px 0 8px 0; }
    table { width: 100%; border-collapse: collapse; margin-bottom: 8px; }
    th, td { border: 1px solid #ddd; padding: 8px; font-size: 12px; }
    th { background: #f5f5f5; text-align: left; }
    .count { font-size: 12px; color: #666; }
  </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 Schedule</h5>
          <div class="text-muted">Grouped + deduplicated (latest per Bag + Item in range).</div>
          <div class="text-muted small mt-1">
            Range: <strong><?= htmlspecialchars($startStr) ?></strong> → <strong><?= htmlspecialchars($endStr) ?></strong>
          </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_transactions_all.php">All Transactions</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-3">
          <label class="form-label">View</label>
          <select class="form-select" name="mode">
            <option value="today" <?= $mode==='today' ? 'selected' : '' ?>>Today</option>
            <option value="week" <?= $mode==='week' ? 'selected' : '' ?>>This Week</option>
            <option value="custom" <?= $mode==='custom' ? 'selected' : '' ?>>Custom</option>
          </select>
        </div>

        <div class="col-md-4">
          <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-2">
          <label class="form-label">From</label>
          <input type="date" class="form-control" name="from" value="<?= htmlspecialchars((string)($_GET['from'] ?? '')) ?>">
        </div>

        <div class="col-md-2">
          <label class="form-label">To</label>
          <input type="date" class="form-control" name="to" value="<?= htmlspecialchars((string)($_GET['to'] ?? '')) ?>">
        </div>

        <div class="col-md-1 d-grid">
          <button class="btn btn-primary">Go</button>
        </div>

        <div class="col-12 d-flex gap-2 mt-2">
          <a class="btn btn-outline-secondary"
             href="<?= BASE_URL ?>/laundry_today.php?mode=<?= urlencode($mode) ?>&building=<?= urlencode($building) ?>&from=<?= urlencode((string)($_GET['from'] ?? '')) ?>&to=<?= urlencode((string)($_GET['to'] ?? '')) ?>&print=1"
             target="_blank">
            Print
          </a>
        </div>
      </form>
    </div>
  <?php else: ?>
    <h2>Laundry Schedule</h2>
    <div class="muted">
      Range: <strong><?= htmlspecialchars($startStr) ?></strong> → <strong><?= htmlspecialchars($endStr) ?></strong>
      <?php if ($building): ?> • Building: <strong><?= htmlspecialchars($building) ?></strong><?php endif; ?>
      <div class="count">Deduplicated: latest per Bag + Item</div>
    </div>
  <?php endif; ?>

  <?php
    $hasAny = false;
    foreach ($groups as $k => $rows) if ($rows) { $hasAny = true; break; }
  ?>

  <?php if (!$hasAny): ?>
    <?php if ($print): ?>
      <div class="muted">No transactions in this range.</div>
    <?php else: ?>
      <div class="card p-4">
        <div class="text-muted">No transactions in this range.</div>
      </div>
    <?php endif; ?>
  <?php else: ?>

    <?php foreach ($groups as $key => $rows): ?>
      <h3><?= htmlspecialchars(sectionTitle($key)) ?> <span class="count">(<?= (int)count($rows) ?>)</span></h3>

      <?php if (!$rows): ?>
        <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>Latest Time</th>
              <th>Building</th>
              <th>Unit</th>
              <th>Bag #</th>
              <th>Item</th>
              <th>Latest Action</th>
              <th>Status Now</th>
              <th>By</th>
            </tr>
          </thead>
          <tbody>
            <?php foreach ($rows as $e): ?>
              <tr>
                <td><?= htmlspecialchars($e['created_at'] ?? '') ?></td>
                <td><?= htmlspecialchars($e['building_name'] ?? '') ?></td>
                <td>
                  <?php if (!$print): ?>
                    <a href="<?= BASE_URL ?>/unit.php?id=<?= (int)($e['unit_id'] ?? 0) ?>">
                      <?= htmlspecialchars($e['unit_code'] ?? '') ?>
                    </a>
                  <?php else: ?>
                    <?= htmlspecialchars($e['unit_code'] ?? '') ?>
                  <?php endif; ?>
                </td>
                <td>
                  <?php if (!$print): ?>
                    <a href="<?= BASE_URL ?>/laundry_bag.php?bag_id=<?= (int)($e['bag_id'] ?? 0) ?>">
                      <?= htmlspecialchars($e['bag_number'] ?? '') ?>
                    </a>
                  <?php else: ?>
                    <?= htmlspecialchars($e['bag_number'] ?? '') ?>
                  <?php endif; ?>
                </td>
                <td><?= htmlspecialchars(ucfirst($e['item_type'] ?? '')) ?></td>
                <td><code><?= htmlspecialchars(niceAction((string)($e['action'] ?? ''))) ?></code></td>
                <td><?= htmlspecialchars(niceStatus((string)($e['status_after'] ?? ''))) ?></td>
                <td><?= htmlspecialchars($e['staff_name'] ?? 'Unknown') ?></td>
              </tr>
            <?php endforeach; ?>
          </tbody>
        </table>
      </div>

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

  <?php endif; ?>

</div>

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