<?php
ob_start();
require_once '../layouts/session.php';
require_once '../layouts/dbconn.php';
ob_end_clean();
header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) { echo json_encode(['success' => false]); exit; }

$grn_id = (int)($_GET['grn_id'] ?? 0);
if (!$grn_id) { echo json_encode(['success' => false, 'message' => 'Invalid GRN']); exit; }

$g = $conn->prepare("
    SELECT g.*, s.supplier_name, u.full_name AS received_by_name
    FROM pharmacy_grn g
    JOIN pharmacy_suppliers s ON s.supplier_id = g.supplier_id
    JOIN users u ON u.user_id = g.received_by
    WHERE g.grn_id = ?
");
$g->bind_param('i', $grn_id);
$g->execute();
$grn = $g->get_result()->fetch_assoc();
$g->close();

if (!$grn) { echo json_encode(['success' => false, 'message' => 'GRN not found']); exit; }

$i = $conn->prepare("
    SELECT gi.*, pi.item_name, pi.strength, pi.dosage_form
    FROM pharmacy_grn_items gi
    JOIN pharmacy_inventory pi ON pi.inventory_id = gi.inventory_id
    WHERE gi.grn_id = ?
    ORDER BY gi.grn_item_id
");
$i->bind_param('i', $grn_id);
$i->execute();
$items = $i->get_result()->fetch_all(MYSQLI_ASSOC);
$i->close();

echo json_encode(['success' => true, 'grn' => $grn, 'items' => $items]);
?>