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

$lowStock = $pdo->query("SELECT i.name, i.code, u.abbreviation unit_abbr, i.reorder_level, COALESCE(s.quantity,0) qty
                          FROM items i
                          LEFT JOIN units u ON u.id=i.unit_id
                          LEFT JOIN main_store_stock s ON s.item_id=i.id
                          WHERE i.is_active=1 AND COALESCE(s.quantity,0) <= i.reorder_level
                          ORDER BY i.name")->fetchAll();

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

<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">Current Qty</th><th class="text-left px-5 py-2">Reorder Level</th>
      <th class="text-right px-5 py-2">Action</th></tr></thead>
    <tbody>
    <?php foreach ($lowStock as $s): ?>
      <tr class="border-t border-slate-100 bg-amber-50">
        <td class="px-5 py-2.5"><?= e($s['code']) ?></td>
        <td class="px-5 py-2.5 font-medium"><?= e($s['name']) ?></td>
        <td class="px-5 py-2.5"><?= number_format($s['qty'],2) ?> <?= e($s['unit_abbr']) ?></td>
        <td class="px-5 py-2.5"><?= number_format($s['reorder_level'],2) ?></td>
        <td class="px-5 py-2.5 text-right"><a href="../purchase_requisitions/create.php" class="text-blue-600 hover:underline">Raise PR →</a></td>
      </tr>
    <?php endforeach; ?>
    <?php if (empty($lowStock)): ?><tr><td colspan="5" class="px-5 py-6 text-center text-slate-400">All items are above reorder level 🎉</td></tr><?php endif; ?>
    </tbody>
  </table></div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
