<?php
require_once __DIR__ . '/../config/config.php';
require_permission('purchase_orders.manage');
$u = current_user();

$poId = (int)($_GET['po_id'] ?? $_POST['po_id'] ?? 0);
$stmt = $pdo->prepare("SELECT * FROM purchase_orders WHERE id = ?");
$stmt->execute([$poId]);
$po = $stmt->fetch();
if (!$po) { flash('error', 'Purchase order not found.'); redirect('purchase_orders/list.php'); }

$lineStmt = $pdo->prepare("SELECT poi.*, i.name item_name, i.track_expiry FROM purchase_order_items poi
                            JOIN items i ON i.id=poi.item_id WHERE poi.po_id=?");
$lineStmt->execute([$poId]);
$lines = $lineStmt->fetchAll();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $qtys = $_POST['quantity_received'] ?? [];
    $itemIds = $_POST['item_id'] ?? [];
    $costs = $_POST['unit_cost'] ?? [];
    $expiryDates = $_POST['expiry_date'] ?? [];
    $notes = trim($_POST['notes'] ?? '');
    $receivedDate = $_POST['received_date'] ?: date('Y-m-d');

    $anyReceived = false;
    foreach ($qtys as $q) if ((float)$q > 0) $anyReceived = true;

    if (!$anyReceived) {
        flash('error', 'Enter at least one received quantity.');
    } else {
        $pdo->beginTransaction();
        try {
            $grnNumber = generate_doc_number($pdo, 'goods_received_notes', 'grn_number', 'GRN');
            $pdo->prepare("INSERT INTO goods_received_notes (grn_number, po_id, received_by, received_date, notes) VALUES (?,?,?,?,?)")
                ->execute([$grnNumber, $poId, $u['id'], $receivedDate, $notes]);
            $grnId = $pdo->lastInsertId();

            $insGrnItem = $pdo->prepare("INSERT INTO goods_received_items (grn_id, item_id, quantity_received, unit_cost) VALUES (?,?,?,?)");
            $updPoItem = $pdo->prepare("UPDATE purchase_order_items SET quantity_received = quantity_received + ? WHERE po_id=? AND item_id=?");

            foreach ($itemIds as $i => $itemId) {
                $qty = (float)($qtys[$i] ?? 0);
                if ($qty <= 0) continue;
                $cost = (float)($costs[$i] ?? 0);
                $insGrnItem->execute([$grnId, $itemId, $qty, $cost]);
                $updPoItem->execute([$qty, $poId, $itemId]);
                $expiryDate = trim($expiryDates[$i] ?? '') ?: null;
                main_store_stock_in($pdo, $itemId, $qty, $cost, 'GRN', $grnId, $u['id'], "GRN $grnNumber", $expiryDate, $receivedDate);
            }

            // Determine PO status: received in full or partial
            $check = $pdo->prepare("SELECT SUM(quantity) ordered, SUM(quantity_received) received FROM purchase_order_items WHERE po_id=?");
            $check->execute([$poId]);
            $tot = $check->fetch();
            $newStatus = $tot['received'] >= $tot['ordered'] ? 'received' : 'partially_received';
            $pdo->prepare("UPDATE purchase_orders SET status=? WHERE id=?")->execute([$newStatus, $poId]);
            if ($newStatus === 'received') {
                $pdo->prepare("UPDATE purchase_requisitions SET status='received' WHERE id=?")->execute([$po['pr_id']]);
            }

            $pdo->commit();
            flash('success', "Goods received note $grnNumber recorded and main store stock updated.");
            redirect('purchase_orders/view.php?id=' . $poId);
        } catch (Exception $ex) {
            $pdo->rollBack();
            flash('error', 'Failed: ' . $ex->getMessage());
        }
    }
}

$pageTitle = 'Receive Goods';
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<h1 class="text-2xl font-bold mb-2">Receive Goods</h1>
<p class="text-slate-500 text-sm mb-6">Against purchase order <?= e($po['po_number']) ?></p>

<form method="POST" class="bg-white rounded-xl shadow-sm border border-slate-200 p-6">
  <input type="hidden" name="po_id" value="<?= $poId ?>">
  <div class="mb-6 max-w-xs">
    <label class="text-sm font-medium block mb-1">Received Date</label>
    <input type="date" name="received_date" value="<?= date('Y-m-d') ?>" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm">
  </div>

  <div class="overflow-x-auto"><table class="w-full text-sm mb-6">
    <thead class="bg-slate-50 text-slate-500 text-xs uppercase"><tr>
      <th class="text-left px-3 py-2">Item</th><th class="text-left px-3 py-2">Ordered</th>
      <th class="text-left px-3 py-2">Already Received</th><th class="text-left px-3 py-2">Qty Now Received</th>
      <th class="text-left px-3 py-2">Unit Cost</th><th class="text-left px-3 py-2">Expiry Date</th></tr></thead>
    <tbody>
    <?php foreach ($lines as $l): $remaining = $l['quantity'] - $l['quantity_received']; ?>
      <tr class="border-t border-slate-100">
        <td class="px-3 py-2"><?= e($l['item_name']) ?><input type="hidden" name="item_id[]" value="<?= $l['item_id'] ?>"></td>
        <td class="px-3 py-2"><?= number_format($l['quantity'],2) ?></td>
        <td class="px-3 py-2"><?= number_format($l['quantity_received'],2) ?></td>
        <td class="px-3 py-2"><input type="number" step="0.01" max="<?= $remaining ?>" name="quantity_received[]" placeholder="0" class="w-24 border border-slate-300 rounded-lg px-2 py-1.5"></td>
        <td class="px-3 py-2"><input type="number" step="0.01" name="unit_cost[]" value="<?= $l['unit_cost'] ?>" class="w-28 border border-slate-300 rounded-lg px-2 py-1.5"></td>
        <td class="px-3 py-2">
          <?php if ($l['track_expiry']): ?>
            <input type="date" name="expiry_date[]" class="border border-slate-300 rounded-lg px-2 py-1.5">
          <?php else: ?>
            <input type="hidden" name="expiry_date[]" value="">
            <span class="text-slate-300 text-xs">n/a</span>
          <?php endif; ?>
        </td>
      </tr>
    <?php endforeach; ?>
    </tbody>
  </table></div>
  <textarea name="notes" placeholder="Notes (delivery condition, invoice ref, etc.)" class="w-full border border-slate-300 rounded-lg px-3 py-2 text-sm mb-6"></textarea>

  <button type="submit" class="bg-blue-700 hover:bg-blue-800 text-white text-sm font-medium px-5 py-2.5 rounded-lg">Confirm Receipt</button>
</form>
<?php include __DIR__ . '/../includes/footer.php'; ?>
