<?php
include 'includes/config.php';

$query = "SELECT 
        p.ref_no,
        p.purchase_date AS Date,
        c.name AS Supplier,
        pr.name AS Product,
        CONCAT(p.quantity, ' ', u.actual_name) AS Quantity,
        p.quantity AS QuantityValue,
        p.purchase_price AS UnitPurchasePrice,
        (p.purchase_price * p.quantity) AS SubTotal,
        p.purchase_status AS PurchaseStatus
    FROM 
        purchase_lines p
    JOIN 
        contacts c ON p.supplier_id = c.id AND c.type = 'supplier'
    JOIN 
        products pr ON p.product_id = pr.id
    JOIN 
        units u ON pr.unit_id = u.id
";

$stmt = $conn->prepare($query);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Format individual prices
foreach ($results as &$row) {
    $row['UnitPurchasePrice'] = number_format($row['UnitPurchasePrice'], 2);
    $row['SubTotal'] = number_format($row['SubTotal'], 2);
}

echo json_encode($results);
?>
