<?php
// purchase_lookup.php
require_once "db.php";

header('Content-Type: application/json; charset=utf-8');

$invoice = isset($_GET['invoice_no']) ? trim($_GET['invoice_no']) : '';
if ($invoice === '') {
    echo json_encode(['ok'=>false,'msg'=>'Invoice number required']);
    exit;
}

// find purchase by invoice_no
$stmt = $conn->prepare("
  SELECT p.purchase_id, p.invoice_no, p.supplier_id, p.purchase_date, p.total, p.paid, p.due, s.supplier_name
  FROM purchases p
  LEFT JOIN suppliers s ON p.supplier_id = s.supplier_id
  WHERE p.invoice_no = ? LIMIT 1
");
$stmt->bind_param("s", $invoice);
$stmt->execute();
$purchase = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$purchase) {
    echo json_encode(['ok'=>false,'msg'=>'Invoice not found']);
    exit;
}

// fetch items optionally
$stmt2 = $conn->prepare("SELECT product, size, rate, qty, subtotal FROM purchase_items WHERE purchase_id = ?");
$stmt2->bind_param("i", $purchase['purchase_id']);
$stmt2->execute();
$itemsRes = $stmt2->get_result();
$items = [];
while ($r = $itemsRes->fetch_assoc()) $items[] = $r;
$stmt2->close();

echo json_encode(['ok'=>true,'purchase'=>$purchase,'items'=>$items]);
exit;
