<?php
require_once __DIR__ . '/../config/config.php';
require_permission('reports.view');

$days = (int)($_GET['days'] ?? 30);
$batches = get_expiring_batches($pdo, $days);

$pageTitle = 'Expiring Items';
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-6">Expiring Items</h1>

<div class="flex gap-2 mb-4 text-sm">
  <?php foreach ([7 => '7 days', 30 => '30 days', 60 => '60 days', 90 => '90 days'] as $val => $label): ?>
    <a href="?days=<?= $val ?>" class="px-3 py-1.5 rounded-full <?= $days===$val ? 'bg-blue-700 text-white' : 'bg-white border border-slate-200 text-slate-600' ?>">Next <?= $label ?></a>
  <?php endforeach; ?>
</div>

<div class="bg-white rounded-xl shadow-sm border border-slate-200">
  <div class="overflow-x-auto"><table class="w-full text-sm">
    <thead class="bg-slate-50 text-slate-500 text-xs uppercase"><tr>
      <th class="text-left px-5 py-2">Code</th><th class="text-left px-5 py-2">Item</th>
      <th class="text-left px-5 py-2">Qty Remaining</th><th class="text-left px-5 py-2">Expiry Date</th>
      <th class="text-left px-5 py-2">Status</th></tr></thead>
    <tbody>
    <?php foreach ($batches as $b):
        $daysLeft = (int)((strtotime($b['expiry_date']) - strtotime(date('Y-m-d'))) / 86400);
        if ($daysLeft < 0) { $badge = 'bg-red-100 text-red-700'; $label = 'Expired ' . abs($daysLeft) . 'd ago'; }
        elseif ($daysLeft <= 7) { $badge = 'bg-red-100 text-red-700'; $label = "$daysLeft days left"; }
        elseif ($daysLeft <= 30) { $badge = 'bg-amber-100 text-amber-700'; $label = "$daysLeft days left"; }
        else { $badge = 'bg-slate-100 text-slate-600'; $label = "$daysLeft days left"; }
    ?>
      <tr class="border-t border-slate-100 <?= $daysLeft < 0 ? 'bg-red-50' : '' ?>">
        <td class="px-5 py-2.5"><?= e($b['item_code']) ?></td>
        <td class="px-5 py-2.5 font-medium"><?= e($b['item_name']) ?></td>
        <td class="px-5 py-2.5"><?= number_format($b['quantity_remaining'],2) ?> <?= e($b['unit_abbr']) ?></td>
        <td class="px-5 py-2.5"><?= date('M j, Y', strtotime($b['expiry_date'])) ?></td>
        <td class="px-5 py-2.5"><span class="px-2 py-0.5 rounded-full text-xs <?= $badge ?>"><?= e($label) ?></span></td>
      </tr>
    <?php endforeach; ?>
    <?php if (empty($batches)): ?><tr><td colspan="5" class="px-5 py-6 text-center text-slate-400">No items expiring in this window 🎉</td></tr><?php endif; ?>
    </tbody>
  </table></div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
