<?php
function hps_sale_summary(mysqli $conn, int $sale_id): array {

    // Sale base
    $sale = mysqli_fetch_assoc(mysqli_query($conn,"
        SELECT sale_price, down_payment, documentation_charges
        FROM hps_sales
        WHERE id = $sale_id
        LIMIT 1
    "));

    if (!$sale) return [];

    $sale_price = (float)$sale['sale_price'];
    $down       = (float)$sale['down_payment'];
    $doc        = (float)$sale['documentation_charges'];

    // Total payable (LOCKED)
    $total_payable = $sale_price + $doc;

    // Total received (ledger)
    $pay = mysqli_fetch_assoc(mysqli_query($conn,"
        SELECT IFNULL(SUM(amount),0) total
        FROM hps_customer_ledger
        WHERE ref_type='SALE'
          AND ref_id=$sale_id
    "));
    $received = (float)$pay['total'];

    // Outstanding
    $outstanding = max(0, $total_payable - $received);

    return [
        'sale_price'     => $sale_price,
        'doc_charges'    => $doc,
        'total_payable'  => $total_payable,
        'down_payment'   => $down,
        'received'       => $received,
        'outstanding'    => $outstanding
    ];
}
