<?php
// get_pr_items.php

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

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

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

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

$stmt = $conn->prepare("
    SELECT 
        pri.item_id,
        pri.requested_qty,
        im.name AS item_name,
        im.uom AS unit
    FROM procurement_request_items pri
    LEFT JOIN inventory_master im ON pri.item_id = im.id
    WHERE pri.pr_id = ?
    ORDER BY pri.id ASC
");

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

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

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

echo json_encode($items);
?>