<?php
// get_po_items_for_grn.php

require_once("../config/config.php");

header('Content-Type: application/json');

$po_id = isset($_GET['po_id']) ? (int)$_GET['po_id'] : 0;

if ($po_id <= 0) {
    echo json_encode([]);
    exit;
}

$stmt = $conn->prepare("
    SELECT 
        poi.item_id,
        poi.ordered_qty,
        poi.rate,
        poi.unit,
        im.name AS item_name
    FROM purchase_order_items poi
    LEFT JOIN inventory_master im ON poi.item_id = im.id
    WHERE poi.po_id = ?
    ORDER BY poi.id ASC
");

$stmt->bind_param("i", $po_id);
$stmt->execute();
$result = $stmt->get_result();

$items = [];
while ($row = $result->fetch_assoc()) {
    $items[] = [
        'item_id'     => (int)$row['item_id'],
        'ordered_qty' => (float)$row['ordered_qty'],
        'rate'        => (float)$row['rate'],
        'unit'        => $row['unit'] ?? 'NOS',
        'item_name'   => $row['item_name'] ?? 'Unknown Item'
    ];
}

$stmt->close();
$conn->close();

echo json_encode($items);
?>