<?php
require "db.php";

$pid = (int)($_GET['pid'] ?? 0);
if ($pid <= 0) die("Invalid receipt");

$p = mysqli_fetch_assoc(mysqli_query($conn,"
    SELECT l.*, s.sale_no, c.name customer, c.mobile
    FROM hps_customer_ledger l
    JOIN hps_sales s ON s.id = l.ref_id
    JOIN hps_customers c ON c.id = l.customer_id
    WHERE l.id = $pid
    LIMIT 1
"));

/* =========================
   CALCULATE CURRENT OUTSTANDING
========================= */

// Total Receivable (Sale Total + Doc Charges)
$recv = mysqli_fetch_assoc(mysqli_query($conn,"
    SELECT 
        (
            (
                SELECT SUM(
                    (IFNULL(down_payment,0) + (IFNULL(monthly_installment,0) * IFNULL(installments,0)))
                    * IFNULL(qty,1)
                )
                FROM hps_sale_items
                WHERE sale_id = s.id
            )
            + IFNULL(s.documentation_charges,0)
        ) AS receivable
    FROM hps_sales s
    WHERE s.id = {$p['ref_id']}
"));

$total_receivable = (float)($recv['receivable'] ?? 0);

// Total Paid
$paid = mysqli_fetch_assoc(mysqli_query($conn,"
    SELECT SUM(IFNULL(cr,0)) AS paid
    FROM hps_customer_ledger
    WHERE ref_id = {$p['ref_id']}
"));

$total_paid = (float)($paid['paid'] ?? 0);

// Outstanding
$outstanding = $total_receivable - $total_paid;



if (!$p) die("Invalid receipt");
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Payment Receipt</title>
<style>
body{width:80mm;font-family:monospace;font-size:12px;}
hr{border:1px dashed #000;}
.center{text-align:center;}
</style>
</head>
<body onload="window.print()">

<div class="center">
<b>ZEE DIGITAL</b><br>
Hire Purchase Receipt<br>
<?= date('d/m/Y H:i') ?>
</div>

<hr>

Sale #: <?= htmlspecialchars($p['sale_no']) ?><br>
Customer: <?= htmlspecialchars($p['customer']) ?><br>
Mobile: <?= htmlspecialchars($p['mobile']) ?><br>

<hr>

Payment Type: <?= htmlspecialchars($p['ref_type']) ?><br>
Remarks: <?= htmlspecialchars($p['description']) ?><br>
Amount: <?= number_format($p['cr']) ?><br>

<hr>
Total Receivable: <?= number_format($total_receivable) ?><br>
Total Paid: <?= number_format($total_paid) ?><br>
<b>Outstanding: <?= number_format($outstanding) ?></b><br>
<hr>


<div class="center">
Thank You<br>
Powered by Zee Digital
</div>


</body>
</html>
