<?php
session_start();
require __DIR__ . "/db.php";

/* =========================
   GET SALE ID (STRICT)
========================= */
if (!isset($_SESSION['hps_sale_id'])) {
    header("Location: hps_sale_customer.php");
    exit;
}

$sale_id = (int)$_SESSION['hps_sale_id'];

if ($sale_id <= 0) {
    die("Invalid Sale");
}

/* =========================
   FETCH SALE ITEMS
========================= */
$q = mysqli_query($conn,"
    SELECT p.name,
           i.monthly_installment,
           i.installments
    FROM hps_sale_items i
    JOIN hps_products p ON p.id=i.product_id
    WHERE i.sale_id = $sale_id
");

$items = [];
$max_inst = 0;

while ($r = mysqli_fetch_assoc($q)) {
    $items[] = $r;
    if ($r['installments'] > $max_inst) {
        $max_inst = $r['installments'];
    }
}

/* =========================
   GENERATE MERGED SCHEDULE
========================= */
$schedule = [];

$start_date = date('Y-m-05'); // later: use sale_date

for ($i = 1; $i <= $max_inst; $i++) {

    $amount = 0;

    foreach ($items as $it) {
        if ($it['installments'] >= $i) {
            $amount += $it['monthly_installment'];
        }
    }

    if ($amount > 0) {
        $schedule[] = [
            'no'     => $i,
            'date'   => date('d-M-Y', strtotime("+".($i-1)." months", strtotime($start_date))),
            'amount' => round($amount, 0)
        ];
    }
}
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Step 3 — Payment Schedule</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>

<div class="container py-3">

<h4 class="mb-3">Step 3 — Payment Schedule</h4>

<div class="progress mb-3">
  <div class="progress-bar bg-info" style="width:40%">
    Step 3 of 7
  </div>
</div>

<table class="table table-bordered table-sm">
<thead class="table-dark">
<tr>
  <th>#</th>
  <th>Due Date</th>
  <th class="text-end">Amount</th>
</tr>
</thead>
<tbody>
<?php if (count($schedule) == 0): ?>
<tr>
  <td colspan="3" class="text-center text-muted">
    No installment schedule generated
  </td>
</tr>
<?php endif; ?>

<?php foreach ($schedule as $row): ?>
<tr>
  <td><?= $row['no'] ?></td>
  <td><?= $row['date'] ?></td>
  <td class="text-end"><?= number_format($row['amount'], 0) ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>

<div class="d-flex justify-content-between mt-3">
  <a href="hps_sale_products.php" class="btn btn-secondary btn-sm">
    ← Back
  </a>

  <a href="hps_sale_checklist.php?sale_id=<?= $sale_id ?>"
     class="btn btn-success btn-sm">
    Save & Next →
  </a>
</div>

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