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

session_start();
require "db.php";
require "hps_core.php";

$res = mysqli_query($conn, "
  SELECT s.id, s.sale_no, s.sale_date, c.name customer, c.mobile
  FROM hps_sales s
  JOIN hps_customers c ON c.id=s.customer_id
  WHERE s.status='Approved'
  ORDER BY s.id DESC
  LIMIT 2000
");

$grand_out = 0;
?>
<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Outstanding Clients</title>
  <link href="assets/bootstrap.min.css" rel="stylesheet">
</head>
<body class="p-3">
<div class="container">

  <div class="card border-dark">
    <div class="card-header bg-light fw-bold">Outstanding Clients (HP Outstanding)</div>
    <div class="card-body p-0">
      <div class="table-responsive">
        <table class="table table-sm mb-0">
          <thead class="table-light">
            <tr>
              <th>Sale#</th>
              <th>Date</th>
              <th>Customer</th>
              <th>Mobile</th>
              <th class="text-end">HP Sale</th>
              <th class="text-end">Outstanding</th>
            </tr>
          </thead>
          <tbody>
          <?php while($r=mysqli_fetch_assoc($res)): ?>
            <?php
              $calc = hps_sale_calc($conn, (int)$r['id']);
              $out = (float)$calc['outstanding_hp'];
              if ($out <= 0) continue;
              $grand_out += $out;
            ?>
            <tr>
              <td><?= htmlspecialchars($r['sale_no'] ?? $r['id']) ?></td>
              <td><?= htmlspecialchars($r['sale_date'] ?? '') ?></td>
              <td><?= htmlspecialchars($r['customer']) ?></td>
              <td><?= htmlspecialchars($r['mobile'] ?? '') ?></td>
              <td class="text-end"><?= number_format($calc['hp_total']) ?></td>
              <td class="text-end fw-bold text-danger"><?= number_format($out) ?></td>
            </tr>
          <?php endwhile; ?>
          </tbody>
          <tfoot class="table-light">
            <tr>
              <th colspan="5" class="text-end">Grand Outstanding</th>
              <th class="text-end"><?= number_format($grand_out) ?></th>
            </tr>
          </tfoot>
        </table>
      </div>
    </div>
  </div>

</div>
</body>
</html>
