<?php
require_once __DIR__ . '/../config/config.php';
require_login();

$id = (int)($_GET['id'] ?? 0);
$stmt = $pdo->prepare("SELECT g.*, po.po_number, s.name supplier_name, u.username received_by_name
                        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
                        WHERE g.id = ?");
$stmt->execute([$id]);
$grn = $stmt->fetch();
if (!$grn) { die('GRN not found.'); }

$lineStmt = $pdo->prepare("SELECT gi.*, i.name item_name, un.abbreviation unit_abbr FROM goods_received_items gi
                            JOIN items i ON i.id = gi.item_id LEFT JOIN units un ON un.id = i.unit_id
                            WHERE gi.grn_id = ?");
$lineStmt->execute([$id]);
$lines = $lineStmt->fetchAll();

$printTitle = 'Goods Received Note';
$printSubtitle = $grn['grn_number'];
include __DIR__ . '/../includes/print_header.php';
?>
<div class="grid grid-cols-1 sm:grid-cols-2 gap-4 text-sm mb-6">
  <div><span class="text-slate-500">Supplier:</span> <?= e($grn['supplier_name']) ?></div>
  <div><span class="text-slate-500">PO Number:</span> <?= e($grn['po_number']) ?></div>
  <div><span class="text-slate-500">Received By:</span> <?= e($grn['received_by_name']) ?></div>
  <div><span class="text-slate-500">Date:</span> <?= e($grn['received_date']) ?></div>
</div>

<div class="overflow-x-auto"><table class="w-full text-sm mb-6 border-collapse">
  <thead><tr class="border-b-2 border-slate-800 text-left text-xs uppercase text-slate-500">
    <th class="py-2">Item</th><th class="py-2">Qty Received</th><th class="py-2">Unit Cost</th><th class="py-2">Value</th></tr></thead>
  <tbody>
  <?php $total = 0; foreach ($lines as $l): $val = $l['quantity_received']*$l['unit_cost']; $total += $val; ?>
    <tr class="border-b border-slate-100">
      <td class="py-2"><?= e($l['item_name']) ?></td>
      <td class="py-2"><?= number_format($l['quantity_received'],2) ?> <?= e($l['unit_abbr']) ?></td>
      <td class="py-2">₦<?= number_format($l['unit_cost'],2) ?></td>
      <td class="py-2">₦<?= number_format($val,2) ?></td>
    </tr>
  <?php endforeach; ?>
  </tbody>
  <tfoot><tr class="font-semibold"><td colspan="3" class="py-2 text-right">Total Value</td><td class="py-2">₦<?= number_format($total,2) ?></td></tr></tfoot>
</table></div>

<?php if ($grn['notes']): ?><p class="text-sm mb-6"><span class="text-slate-500">Notes:</span> <?= e($grn['notes']) ?></p><?php endif; ?>

<div class="grid grid-cols-1 sm:grid-cols-2 gap-6 mt-10 text-sm">
  <div class="border-t border-slate-400 pt-2">Received By: <?= e($grn['received_by_name']) ?></div>
  <div class="border-t border-slate-400 pt-2">Store Manager Signature: ______________________</div>
</div>
<?php include __DIR__ . '/../includes/print_footer.php'; ?>
