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

$id = (int)($_GET['id'] ?? 0);
if ($id <= 0) exit('Invalid ID');

$po = $conn->query("
    SELECT po.*,
           v.name AS vendor_name, v.phone AS vendor_phone,
           v.mobile AS vendor_mobile, v.address AS vendor_address,
           v.city AS vendor_city, v.state AS vendor_state,
           v.gstin AS vendor_gstin
    FROM purchase_orders po
    JOIN vendors v ON v.id = po.vendor_id
    WHERE po.id = $id
")->fetch_assoc();
if (!$po) exit('PO not found');

$company = getCompany($conn, $po['company_id']);

$prefRow = $conn->query("SELECT invoice_prefix FROM company_master WHERE id = {$po['company_id']} LIMIT 1")->fetch_assoc();
$companyPrefix = $prefRow['invoice_prefix'] ?? '';

$items = $conn->query("
    SELECT pi.*, p.name AS product_name
    FROM purchase_items pi
    JOIN products p ON p.id = pi.product_id
    WHERE pi.purchase_order_id = $id
");

require 'layout_a4.php';
