<?php
// pages/payment_plan_add.php
include('../includes/db.php');
mysqli_set_charset($conn,'utf8mb4');

$editing = isset($_GET['id']);
$plan = null;
if ($editing) {
  $pid = (int)$_GET['id'];
  $plan = $conn->query("SELECT * FROM payment_plans WHERE id={$pid}")->fetch_assoc();
}
$courses = $conn->query("SELECT id, course_name FROM courses ORDER BY course_name");
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title><?= $editing?'Edit':'Add' ?> Payment Plan</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<style>body{background:#f5f7fb}.container{max-width:900px}</style>
</head>
<body>
<div class="container py-5">
  <div class="d-flex justify-content-between align-items-center mb-4">
    <h3 class="fw-bold mb-0"><?= $editing?'Edit':'Add' ?> Payment Plan</h3>
    <div class="d-flex gap-2">
      <a class="btn btn-outline-secondary" href="payment_manager.php">Manager</a>
      <a class="btn btn-outline-secondary" href="payment_plan_list.php">Plans</a>
      <a class="btn btn-outline-secondary" href="dashboard.php">Dashboard</a>
    </div>
  </div>

  <form id="planForm" class="card p-3">
    <input type="hidden" name="id" value="<?= $editing? (int)$plan['id'] : '' ?>">
    <div class="mb-3">
      <label class="form-label">Course</label>
      <select name="course_id" class="form-select" required <?= $editing?'disabled':'' ?>>
        <option value="">-- Select --</option>
        <?php while($c=$courses->fetch_assoc()): ?>
          <option value="<?= $c['id'] ?>" <?= ($plan && $plan['course_id']==$c['id'])?'selected':'' ?>>
            <?= htmlspecialchars($c['course_name']) ?>
          </option>
        <?php endwhile; ?>
      </select>
      <?php if(!$editing && isset($_GET['course_id'])): ?>
        <script>document.addEventListener('DOMContentLoaded',()=>{document.querySelector('[name=course_id]').value='<?= (int)$_GET['course_id'] ?>'});</script>
      <?php endif; ?>
    </div>

    <div class="mb-3">
      <label class="form-label">Plan Type</label>
      <select name="plan_name" class="form-select" required <?= $editing?'disabled':'' ?>>
        <?php
          $pref = $_GET['type'] ?? '';
          $types = ['Standard','Discounted','Installment'];
          foreach($types as $t){
            $sel = ($plan && $plan['plan_name']===$t) || (!$plan && $pref===$t) ? 'selected':'';
            echo "<option $sel>$t</option>";
          }
        ?>
      </select>
    </div>

    <div class="row g-3">
      <div class="col-md-4">
        <label class="form-label">Course Fee (LKR)</label>
        <input name="course_fee_lkr" type="number" step="0.01" class="form-control" value="<?= $plan['course_fee_lkr'] ?? '' ?>">
      </div>
      <div class="col-md-4">
        <label class="form-label">Registration Fee (LKR)</label>
        <input name="registration_fee_lkr" type="number" step="0.01" class="form-control" value="<?= $plan['registration_fee_lkr'] ?? '' ?>">
      </div>
      <div class="col-md-4">
        <label class="form-label">Certificate Fee (USD)</label>
        <input name="certificate_fee_usd" type="number" step="0.01" class="form-control" value="<?= $plan['certificate_fee_usd'] ?? '' ?>">
      </div>
    </div>

    <hr>
    <h6>Installments</h6>
    <div class="table-responsive">
      <table class="table table-bordered align-middle" id="instTbl">
        <thead class="table-light">
          <tr><th>#</th><th>Due Date</th><th>Course Fee</th><th>Reg Fee</th><th>Cert Fee (USD)</th><th>Action</th></tr>
        </thead>
        <tbody></tbody>
      </table>
    </div>
    <div class="mb-3">
      <button class="btn btn-outline-primary" type="button" onclick="addRow()">+ Add</button>
      <button class="btn btn-outline-secondary" type="button" onclick="copyRow()">Copy last</button>
    </div>

    <div class="d-flex justify-content-end gap-2">
      <button class="btn btn-success" type="submit">Save Plan</button>
    </div>
  </form>
</div>

<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script>
let rows=0;
function addRow(no='', dd='', cf='', rf='', uf=''){
  $('#instTbl tbody').append(`
    <tr>
      <td><input class="form-control" type="number" value="${no||rows+1}"></td>
      <td><input class="form-control" type="date" value="${dd||''}"></td>
      <td><input class="form-control" type="number" step="0.01" value="${cf||''}"></td>
      <td><input class="form-control" type="number" step="0.01" value="${rf||''}"></td>
      <td><input class="form-control" type="number" step="0.01" value="${uf||''}"></td>
      <td><button class="btn btn-sm btn-danger" onclick="$(this).closest('tr').remove()">Delete</button></td>
    </tr>`); rows++;
}
function copyRow(){
  const tr=$('#instTbl tbody tr').last(); if(!tr.length) return;
  const v=tr.find('input').map(function(){return this.value}).get();
  addRow(Number(v[0]||0)+1, v[1], v[2], v[3], v[4]);
}
<?php if($editing): ?>
// load current installments
$.getJSON('payment_api.php',{action:'get_plan', plan_id: <?= (int)$plan['id'] ?>}, d=>{
  (d.installments||[]).forEach(i=> addRow(i.installment_no, i.due_date, i.course_fee_lkr, i.registration_fee_lkr, i.certificate_fee_usd));
});
<?php endif; ?>

$('#planForm').on('submit', function(e){
  e.preventDefault();
  const fd = Object.fromEntries(new FormData(this).entries());
  fd.status = 'Active';
  // build installments
  fd.installments = $('#instTbl tbody tr').map(function(){
    const v=$(this).find('input').map(function(){return this.value}).get();
    return {installment_no:v[0], due_date:v[1], course_fee_lkr:v[2], registration_fee_lkr:v[3], certificate_fee_usd:v[4]};
  }).get();
  $.ajax({
    url:'payment_api.php?action=save_plan',
    method:'POST',
    data: JSON.stringify(fd),
    contentType:'application/json',
    success: d => { alert('Saved'); window.location='payment_manager.php'; },
    error: xhr => alert('Save failed:\n'+xhr.responseText)
  });
});
</script>
</body>
</html>
