<?php
require_once '../includes/auth.php';
require_once '../db.php';

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

$po_id = (int)($_GET['po_id'] ?? 0);
if ($po_id <= 0) { echo json_encode(['error' => 'Invalid purchase order']); exit; }

/* PO header */
$po = $conn->query("
    SELECT po.po_no, po.purchase_date, po.supplier_invoice_no, po.status,
           po.net_amount, po.gst_amount, po.total_amount,
           v.name AS vendor_name
    FROM purchase_orders po
    LEFT JOIN vendors v ON v.id = po.vendor_id
    WHERE po.id = $po_id AND po.status = 'final'
    LIMIT 1
")->fetch_assoc();

if (!$po) { echo json_encode(['error' => 'Purchase order not found']); exit; }

/* All items in this PO */
$itemsRes = $conn->query("
    SELECT
        p.name AS product_name,
        pi.batch_no,
        pi.quantity,
        pi.available_qty,
        pi.purchase_price,
        pi.gst_percent,
        ROUND(pi.purchase_price * (1 + pi.gst_percent / 100), 2) AS purchase_price_incl,
        ROUND(pi.purchase_price * pi.quantity, 2)                 AS taxable_amount,
        ROUND(pi.purchase_price * pi.quantity * pi.gst_percent / 100, 2) AS gst_amount,
        ROUND(pi.purchase_price * (1 + pi.gst_percent / 100) * pi.quantity, 2) AS net_amount,
        pi.mrp,
        pi.expiry_date
    FROM purchase_items pi
    JOIN products p ON p.id = pi.product_id
    WHERE pi.purchase_order_id = $po_id
    ORDER BY pi.id ASC
");

$items = [];
$grandTaxable = 0;
$grandGst     = 0;
$grandNet     = 0;

while ($item = $itemsRes->fetch_assoc()) {
    if ($item['expiry_date']) {
        $item['expiry_date'] = date('d-m-Y', strtotime($item['expiry_date']));
    }
    $grandTaxable += (float)$item['taxable_amount'];
    $grandGst     += (float)$item['gst_amount'];
    $grandNet     += (float)$item['net_amount'];
    $items[] = $item;
}

echo json_encode([
    'po' => [
        'po_no'               => $po['po_no'],
        'purchase_date'       => date('d-m-Y', strtotime($po['purchase_date'])),
        'vendor_name'         => $po['vendor_name'] ?? '—',
        'supplier_invoice_no' => $po['supplier_invoice_no'] ?: '—',
    ],
    'items'         => $items,
    'grand_taxable' => round($grandTaxable, 2),
    'grand_gst'     => round($grandGst, 2),
    'grand_net'     => round($grandNet, 2),
]);
