<?php
require_once __DIR__ . '/../config/config.php';
require_permission('purchase_orders.manage');

$pos = $pdo->query("SELECT po.*, s.name supplier_name, pr.pr_number, u.username created_by_name
                     FROM purchase_orders po
                     JOIN suppliers s ON s.id = po.supplier_id
                     JOIN purchase_requisitions pr ON pr.id = po.pr_id
                     JOIN users u ON u.id = po.created_by
                     ORDER BY po.created_at DESC")->fetchAll();

$pageTitle = 'Purchase Orders';
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-6">Purchase Orders</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">PO Number</th><th class="text-left px-5 py-2">From PR</th>
      <th class="text-left px-5 py-2">Supplier</th><th class="text-left px-5 py-2">Total Cost</th>
      <th class="text-left px-5 py-2">Status</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 ($pos as $po): ?>
      <?php $badge = ['open'=>'bg-amber-100 text-amber-700','partially_received'=>'bg-blue-100 text-blue-700',
                      'received'=>'bg-emerald-100 text-emerald-700','cancelled'=>'bg-slate-200 text-slate-500'][$po['status']]; ?>
      <tr class="border-t border-slate-100">
        <td class="px-5 py-2.5 font-medium"><?= e($po['po_number']) ?></td>
        <td class="px-5 py-2.5"><?= e($po['pr_number']) ?></td>
        <td class="px-5 py-2.5"><?= e($po['supplier_name']) ?></td>
        <td class="px-5 py-2.5">₦<?= number_format($po['total_cost'],2) ?></td>
        <td class="px-5 py-2.5"><span class="px-2 py-0.5 rounded-full text-xs <?= $badge ?> capitalize"><?= str_replace('_',' ',$po['status']) ?></span></td>
        <td class="px-5 py-2.5 text-slate-500"><?= date('d M Y', strtotime($po['created_at'])) ?></td>
        <td class="px-5 py-2.5 text-right"><a href="view.php?id=<?= $po['id'] ?>" class="text-blue-600 hover:underline">View →</a></td>
      </tr>
    <?php endforeach; ?>
    <?php if (empty($pos)): ?><tr><td colspan="7" class="px-5 py-6 text-center text-slate-400">No purchase orders yet.</td></tr><?php endif; ?>
    </tbody>
  </table></div>
</div>
<?php include __DIR__ . '/../includes/footer.php'; ?>
