<?php
require "db.php";

error_reporting(E_ALL);
ini_set('display_errors', 1);

if (!isset($_GET['sale_id']) || !is_numeric($_GET['sale_id'])) {
    exit("Invalid Sale");
}

$sale_id = (int)$_GET['sale_id'];

/* =========================
   SALE + CUSTOMER INFO
========================= */
$sale = mysqli_fetch_assoc(mysqli_query($conn,"
    SELECT s.sale_no, s.sale_date, s.documentation_charges,
           c.id AS customer_id,
           c.name, c.mobile
    FROM hps_sales s
    JOIN hps_customers c ON c.id = s.customer_id
    WHERE s.id = $sale_id
    LIMIT 1
"));

if (!$sale) exit("Sale not found");

$customer_id = (int)$sale['customer_id'];

echo "<div class='mb-2'>";
echo "<strong>Customer:</strong> ".htmlspecialchars($sale['name'])."<br>";
echo "<strong>Mobile:</strong> ".htmlspecialchars($sale['mobile'])."<br>";
echo "<strong>Sale Date:</strong> ".date('d-M-Y', strtotime($sale['sale_date']));
echo "</div>";

/* =========================
   CALCULATE TOTAL SALE
========================= */

$total_sale = 0;

$items = mysqli_query($conn,"
    SELECT *
    FROM hps_sale_items
    WHERE sale_id = $sale_id
");

while($i = mysqli_fetch_assoc($items)){

    $base = (float)$i['price'] * (float)$i['qty'];

    $finance = $base - (float)$i['down_payment'];
    if ($finance < 0) $finance = 0;

    $app_markup = (float)$i['markup_rate'] * ((float)$i['installments'] / 12);
    $markup_amt = ($app_markup / 100) * $finance;

    $hp_amount = $finance + $markup_amt;

    $total_sale += $hp_amount;
}

$total_sale += (float)$sale['documentation_charges'];

/* =========================
   LEDGER ENTRIES
========================= */

$ledger = mysqli_query($conn,"
    SELECT trans_date, description, dr, cr
    FROM hps_customer_ledger
    WHERE ref_id = $sale_id
    ORDER BY trans_date ASC, id ASC
");

echo "<h6 class='mt-3'>Installment Schedule</h6>";

echo "<table class='table table-bordered table-sm'>";
echo "<tr>
        <th>Qty</th>
        <th>Price</th>
        <th>Installments</th>
        <th>Monthly</th>
      </tr>";

$items = mysqli_query($conn,"
    SELECT qty, price, installments, monthly_installment
    FROM hps_sale_items
    WHERE sale_id = $sale_id
");

while($r = mysqli_fetch_assoc($items)){
    echo "<tr>
        <td>{$r['qty']}</td>
        <td>".number_format($r['price'])."</td>
        <td>{$r['installments']}</td>
        <td>".number_format($r['monthly_installment'])."</td>
    </tr>";
}

echo "</table>";

echo "<h6 class='mt-3'>Payment Ledger</h6>";

echo "<table class='table table-bordered table-sm'>";
echo "<tr>
        <th>Date</th>
        <th>Description</th>
        <th class='text-end'>Debit</th>
        <th class='text-end'>Credit</th>
        <th class='text-end'>Balance</th>
      </tr>";

$balance = 0;

/* Opening Sale Entry */
echo "<tr class='table-secondary'>
        <td>".date('d-M-Y', strtotime($sale['sale_date']))."</td>
        <td><b>HP SALE</b></td>
        <td class='text-end'>".number_format($total_sale,2)."</td>
        <td class='text-end'></td>
        <td class='text-end'>";

$balance += $total_sale;
echo number_format($balance,2);

echo "</td></tr>";

$total_paid = 0;

while($l = mysqli_fetch_assoc($ledger)){

    $credit = (float)$l['cr'];
    $debit  = (float)$l['dr'];

    $balance += $debit;
    $balance -= $credit;

    $total_paid += $credit;

    echo "<tr>
        <td>".date('d-M-Y', strtotime($l['trans_date']))."</td>
        <td>".htmlspecialchars($l['description'])."</td>
        <td class='text-end'>".number_format($debit,2)."</td>
        <td class='text-end'>".number_format($credit,2)."</td>
        <td class='text-end'>".number_format($balance,2)."</td>
    </tr>";
}

echo "</table>";

echo "<div class='mt-3'>
        <strong>Total Sale:</strong> ".number_format($total_sale,2)."<br>
        <strong>Total Paid:</strong> ".number_format($total_paid,2)."<br>
        <strong>Outstanding:</strong>
        <span class='text-danger fw-bold'>".number_format($balance,2)."</span>
      </div>";
