<?php
$adminTitle = 'Purchase Orders';
require_once __DIR__ . '/includes/header.php';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $id     = (int)$_POST['po_id'];
    $status = sanitize($_POST['status'] ?? '');
    $notes  = sanitize($_POST['notes'] ?? '');
    $delDate = sanitize($_POST['delivery_date'] ?? '');
    Database::execute("UPDATE purchase_orders SET status=?, notes=?, delivery_date=?, updated_at=NOW() WHERE id=?",
        [$status, $notes, $delDate ?: null, $id]);
    $_SESSION['flash']['success'] = 'Purchase order updated.';
    header('Location: /admin/orders.php');
    exit;
}

$filter = trim($_GET['status'] ?? '');
$where  = $filter ? "WHERE po.status=?" : "";
$params = $filter ? [$filter] : [];
$total  = (int)(Database::fetchOne("SELECT COUNT(*) as c FROM purchase_orders po $where", $params)['c'] ?? 0);
$pag    = paginate($total, ADMIN_PER_PAGE, (int)($_GET['page'] ?? 1), '/admin/orders.php?' . http_build_query(array_filter(['status'=>$filter])));
$orders = Database::fetchAll(
    "SELECT po.*, c.company_name, c.contact_name FROM purchase_orders po LEFT JOIN customers c ON po.customer_id=c.id $where ORDER BY po.created_at DESC LIMIT ? OFFSET ?",
    array_merge($params, [$pag['per_page'], $pag['offset']])
);
?>
<div class="flex items-center justify-between mb-6">
  <h2 class="text-lg font-semibold">Purchase Orders (<?= $total ?>)</h2>
  <div class="flex gap-2">
    <?php foreach ([''=>'All','pending'=>'Pending','confirmed'=>'Confirmed','processing'=>'Processing','shipped'=>'Shipped','delivered'=>'Delivered'] as $v=>$l): ?>
    <a href="?status=<?= $v ?>" class="text-xs px-3 py-1.5 rounded <?= $filter===$v?'bg-orange-600 text-white':'bg-navy-700 text-gray-300' ?>"><?= $l ?></a>
    <?php endforeach; ?>
  </div>
</div>
<div class="card-dark overflow-hidden">
  <table class="data-table">
    <thead><tr><th>PO #</th><th>Customer</th><th>Total</th><th>Status</th><th>Delivery</th><th>Action</th></tr></thead>
    <tbody>
    <?php foreach ($orders as $po): ?>
    <tr>
      <td class="font-mono text-xs text-orange-400"><?= e($po['po_number']) ?></td>
      <td class="text-sm"><?= e($po['company_name'] ?: $po['contact_name']) ?></td>
      <td class="font-semibold text-sm"><?= formatPrice($po['total']) ?></td>
      <td><?= statusBadge($po['status']) ?></td>
      <td class="text-xs text-gray-400"><?= $po['delivery_date'] ? formatDate($po['delivery_date']) : '—' ?></td>
      <td>
        <button onclick="document.getElementById('po-update-<?= $po['id'] ?>').classList.toggle('hidden')" class="text-xs text-orange-500 hover:underline">Update</button>
      </td>
    </tr>
    <tr id="po-update-<?= $po['id'] ?>" class="hidden">
      <td colspan="6" class="bg-navy-600 p-4">
        <form method="POST" class="flex flex-wrap gap-3 items-end">
          <input type="hidden" name="po_id" value="<?= $po['id'] ?>">
          <div><label class="text-xs text-gray-400 block mb-1">Status</label>
          <select name="status" class="text-sm py-1">
            <?php foreach (['pending','confirmed','processing','shipped','delivered','cancelled'] as $s): ?>
            <option value="<?= $s ?>" <?= $po['status']===$s?'selected':'' ?>><?= ucwords($s) ?></option>
            <?php endforeach; ?>
          </select></div>
          <div><label class="text-xs text-gray-400 block mb-1">Delivery Date</label><input type="date" name="delivery_date" value="<?= $po['delivery_date'] ?? '' ?>" class="text-sm py-1"></div>
          <div class="flex-1"><label class="text-xs text-gray-400 block mb-1">Notes</label><input type="text" name="notes" value="<?= e($po['notes'] ?? '') ?>" class="text-sm py-1"></div>
          <button class="btn-primary text-xs py-1.5">Save</button>
        </form>
      </td>
    </tr>
    <?php endforeach; ?>
    </tbody>
  </table>
</div>
<?= paginationHtml($pag) ?>
<?php include __DIR__ . '/includes/footer.php'; ?>
