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

$grns = $pdo->query("SELECT g.*, po.po_number, s.name supplier_name, u.username received_by_name,
                      (SELECT SUM(quantity_received) FROM goods_received_items WHERE grn_id=g.id) total_qty,
                      (SELECT SUM(quantity_received*unit_cost) FROM goods_received_items WHERE grn_id=g.id) total_value
                      FROM goods_received_notes g
                      JOIN purchase_orders po ON po.id = g.po_id
                      JOIN suppliers s ON s.id = po.supplier_id
                      JOIN users u ON u.id = g.received_by
                      ORDER BY g.created_at DESC")->fetchAll();

$pageTitle = 'Goods Received';
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-6">Goods Received Notes</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">GRN Number</th><th class="text-left px-5 py-2">PO Number</th>
      <th class="text-left px-5 py-2">Supplier</th><th class="text-left px-5 py-2">Received By</th>
      <th class="text-left px-5 py-2">Total Qty</th><th class="text-left px-5 py-2">Total Value</th>
      <th class="text-left px-5 py-2">Date</th><th class="text-right px-5 py-2">Action</th></tr></thead>
    <tbody>
    <?php foreach ($grns as $g): ?>
      <tr class="border-t border-slate-100">
        <td class="px-5 py-2.5 font-medium"><?= e($g['grn_number']) ?></td>
        <td class="px-5 py-2.5"><?= e($g['po_number']) ?></td>
        <td class="px-5 py-2.5"><?= e($g['supplier_name']) ?></td>
        <td class="px-5 py-2.5"><?= e($g['received_by_name']) ?></td>
        <td class="px-5 py-2.5"><?= number_format($g['total_qty'],2) ?></td>
        <td class="px-5 py-2.5">₦<?= number_format($g['total_value'],2) ?></td>
        <td class="px-5 py-2.5 text-slate-500"><?= e($g['received_date']) ?></td>
        <td class="px-5 py-2.5 text-right"><a href="view.php?id=<?= $g['id'] ?>" class="text-blue-600 hover:underline">View →</a></td>
      </tr>
    <?php endforeach; ?>
    <?php if (empty($grns)): ?><tr><td colspan="8" class="px-5 py-6 text-center text-slate-400">No goods received yet.</td></tr><?php endif; ?>
    </tbody>
  </table></div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
