<?php
// hps_sale_approved.php
error_reporting(E_ALL);
ini_set('display_errors', 1);

session_start();
require "db.php";

/* =========================
   FETCH APPROVED SALES
========================= */
$sql = "
SELECT
    s.id AS sale_id,
    s.sale_no,
    s.sale_ref,
    s.sale_date,
    s.documentation_charges,

    c.name   AS customer,
    c.mobile AS mobile,
    c.cnic   AS cnic,

    /* BASE PRICE */
    (
        SELECT IFNULL(SUM(price * qty),0)
        FROM hps_sale_items
        WHERE sale_id = s.id
    ) AS base_price,

    /* MARKUP (PER BUSINESS RULE) */
    (
        SELECT IFNULL(SUM(
            (IFNULL(si.price,0) - IFNULL(si.down_payment,0))
            * ((IFNULL(si.markup_rate,0)/100) * (IFNULL(si.installments,0)/12))
        ),0)
        FROM hps_sale_items si
        WHERE si.sale_id = s.id
    ) AS total_markup,

    /* TOTAL PAID (ALL PAYMENTS) */
    (
        SELECT IFNULL(SUM(cr),0)
        FROM hps_customer_ledger
        WHERE ref_id = s.id
          AND cr > 0
    ) AS total_paid

FROM hps_sales s
JOIN hps_customers c ON c.id = s.customer_id
WHERE s.status = 'Approved'
ORDER BY s.id DESC
";

$res = mysqli_query($conn, $sql);
if (!$res) die(mysqli_error($conn));
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Approved HP Sales</title>
<style>
body{font-family:Arial,Helvetica,sans-serif;background:#f5f5f5;margin:0}
.header{background:#0d6efd;color:#fff;padding:10px 20px}
.container{padding:20px}
table{width:100%;border-collapse:collapse;background:#fff}
th,td{border:1px solid #ddd;padding:8px;font-size:14px}
th{background:#212529;color:#fff}
.text-right{text-align:right}
.text-danger{color:#dc3545;font-weight:bold}
.btn{padding:6px 10px;text-decoration:none;border-radius:4px;font-size:13px}
.btn-success{background:#198754;color:#fff}
.btn-danger{background:#dc3545;color:#fff}
.search{width:100%;padding:8px;margin-bottom:10px}
</style>
</head>

<body>

<div class="header">
    <b>Zee Digital</b>
    <span style="float:right"><?= date('d/m/Y H:i:s') ?></span>
</div>

<div class="container">
<h2>Approved HP Sales</h2>

<input type="text" class="search" placeholder="Search sale / customer / CNIC..."
       onkeyup="filterTable(this.value)">

<table id="salesTable">
<thead>
<tr>
    <th>Sale Ref</th>
    <th>Date</th>
    <th>Customer</th>
    <th>Mobile</th>
    <th>CNIC</th>
    <th class="text-right">Outstanding</th>
    <th>Action</th>
</tr>
</thead>
<tbody>

<?php while($r = mysqli_fetch_assoc($res)):

    $base   = (float)$r['base_price'];
    $markup = (float)$r['total_markup'];
    $doc    = (float)$r['documentation_charges'];
    $paid   = (float)$r['total_paid'];

    $total_sale = $base + $markup + $doc;
    $outstanding = $total_sale - $paid;
?>

<tr>
    <td><?= htmlspecialchars($r['sale_ref'] ?: 'HP-'.$r['sale_id']) ?></td>
    <td><?= htmlspecialchars($r['sale_date']) ?></td>
    <td><?= htmlspecialchars($r['customer']) ?></td>
    <td><?= htmlspecialchars($r['mobile']) ?></td>
    <td><?= htmlspecialchars($r['cnic']) ?></td>

    <td class="text-right text-danger">
        <?= number_format($outstanding,0) ?>
    </td>

    <td>
        <?php if ($outstanding > 0): ?>
            <a class="btn btn-success"
               href="hps_sale_payment.php?sale_id=<?= (int)$r['sale_id'] ?>">
               Receive Payment
            </a>
        <?php else: ?>
            <span class="btn btn-danger">PAID</span>
        <?php endif; ?>
    </td>
</tr>

<?php endwhile; ?>

</tbody>
</table>
</div>

<script>
function filterTable(v){
    v=v.toLowerCase();
    document.querySelectorAll("#salesTable tbody tr").forEach(r=>{
        r.style.display = r.innerText.toLowerCase().includes(v) ? "" : "none";
    });
}
</script>

</body>
</html>
