<?php
// /edenrms/pages/payment_manager.php
declare(strict_types=1);

require_once __DIR__ . '/../includes/auth.php';
ec_require_login();

require_once __DIR__ . '/../includes/db.php';
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$conn->set_charset('utf8mb4');

// courses for dropdown
$courses = $conn->query("SELECT id, course_name FROM courses ORDER BY course_name ASC");
?>
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Payment Manager</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    :root{ --card-radius:12px; }
    body{background:#f7f9fc}
    .ec-main{margin-left:var(--sidebar-width,260px)}
    .card{border-radius:var(--card-radius); box-shadow:0 6px 18px rgba(0,0,0,.06)}
    .section-card .card-header{background:#f1f3f7; border-top-left-radius:var(--card-radius); border-top-right-radius:var(--card-radius)}
    .summary-row div{min-width:160px}
    .table-tight td,.table-tight th{padding:.4rem .55rem}
    .muted{color:#6c757d}
    .w-120{width:120px}.w-140{width:140px}.w-160{width:160px}
    .nowrap{white-space:nowrap}.cursor-pointer{cursor:pointer}
    .badge-soft{background:#eef2f8; color:#41576b}
  </style>
  <style>
    .ec-main { font-size: 0.90rem; }
    .ec-main h3 { font-size: 1.15rem; margin-bottom: .5rem; }
    .ec-main .card .card-header { padding: .5rem 1rem; }
    .ec-main .card .card-body   { padding: .75rem 1rem; }
    .ec-main .form-control,
    .ec-main .form-select,
    .ec-main .input-group-text { font-size: .9rem; padding: .35rem .6rem; }
    .ec-main .btn { font-size: .875rem; padding: .35rem .65rem; }
    .ec-main .table{ font-size: .9rem; }
    .ec-main .table-tight th,.ec-main .table-tight td{ padding: .3rem .45rem; }
    .ec-main .modal .modal-body { font-size: .95rem; }
 
 
 
 
 /* ===== PAYMENT PAGE HERO ===== */
.pm-shell{
  padding: 0 6px;
}

.pm-hero{
  background: #ffffff;
  border: 1px solid #e7ebf3;
  border-radius: 22px;
  box-shadow: 0 8px 24px rgba(15, 23, 42, 0.05);
  padding: 20px 22px;
  margin-bottom: 16px;
}

.pm-hero-title{
  margin: 0;
  font-size: 2rem;
  font-weight: 800;
  letter-spacing: -0.02em;
  color: #16233c;
}

.pm-hero-subtitle{
  margin: 6px 0 0;
  font-size: .95rem;
  color: #6f7b91;
}

.pm-hero-actions{
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
  align-items: center;
}

.pm-top-card{
  background: #fff;
  border: 1px solid #e7ebf3;
  border-radius: 20px;
  box-shadow: 0 8px 24px rgba(15, 23, 42, 0.05);
  padding: 16px;
  margin-bottom: 16px;
}

.pm-meta-box{
  background: #ffffff;
  border: 1px solid #e7ebf3;
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(15, 23, 42, 0.04);
}

.pm-meta-box .muted{
  color: #74819a;
}

.section-card{
  border: 1px solid #e7ebf3 !important;
  border-radius: 20px !important;
  box-shadow: 0 8px 24px rgba(15, 23, 42, 0.05) !important;
  overflow: hidden;
}

.section-card .card-header{
  background: #f8faff !important;
  border-bottom: 1px solid #e7ebf3 !important;
  padding: 14px 16px !important;
}

.section-card .card-body{
  padding: 16px !important;
}

@media (max-width: 991.98px){
  .pm-hero{
    padding: 16px;
  }

  .pm-hero-title{
    font-size: 1.55rem;
  }

  .pm-hero-actions{
    width: 100%;
  }

  .pm-hero-actions .btn{
    flex: 1 1 auto;
  }
}
 
  </style>
</head>
<body>
<?php
$ACTIVE = 'Payment Manager';
include __DIR__ . '/../includes/header.php';
include __DIR__ . '/../includes/sidebar.php';
?>
<main class="ec-main">
<div class="container-fluid py-4 pm-shell">

  <div class="pm-hero">
    <div class="d-flex justify-content-between align-items-center gap-3 flex-wrap">
      <div>
        <h1 class="pm-hero-title">Payment Manager</h1>
        <p class="pm-hero-subtitle">
          Manage standard fees, discounts, installment plans, and payment structures by course.
        </p>
      </div>

      
    </div>
  </div>

  <!-- Course Selection + top meta -->
  <div class="pm-top-card">
    <div class="row g-3 align-items-end">
      <div class="col-md-6">
        <label class="form-label">Course</label>
        <select id="pmCourse" class="form-select">
          <option value="">-- Select Course --</option>
          <?php while($c = $courses->fetch_assoc()): ?>
            <option value="<?= (int)$c['id'] ?>"><?= htmlspecialchars($c['course_name'] ?? '') ?></option>
          <?php endwhile; ?>
        </select>
      </div>
      <div class="col-md-6 text-end">
        <span id="hint" class="text-muted">Choose a course to manage fees, discounts and installments.</span>
      </div>
    </div>

    <div id="courseMeta" class="row g-3 mt-3 d-none">
      <div class="col-lg-3 col-md-6">
        <div class="p-3 pm-meta-box">
          <div class="muted small">Course Name</div>
          <div id="mCourseName" class="fw-semibold"></div>
        </div>
      </div>
      <div class="col-lg-3 col-md-6">
        <div class="p-3 bg-white rounded border">
          <div class="muted small">Standard Fee (LKR)</div>
          <div id="mStandardFee" class="fw-semibold"></div>
        </div>
      </div>
      <div class="col-lg-3 col-md-6">
        <div class="p-3 bg-white rounded border">
          <div class="muted small">Duration</div>
          <div id="mDuration" class="fw-semibold"></div>
        </div>
      </div>
      <div class="col-lg-3 col-md-6">
        <div class="p-3 bg-white rounded border">
          <div class="muted small">Currency</div>
          <div id="mCurrency" class="fw-semibold"></div>
        </div>
      </div>
    </div>
  </div>

  <!-- Standard Fee Section -->
  <div class="card section-card mb-3" id="cardStandard">
    <div class="card-header d-flex justify-content-between align-items-center">
      <div class="fw-semibold">2) Standard Fee</div>
      <button type="button" class="btn btn-primary btn-sm d-none" id="btnEditStandard">Update / Edit</button>
    </div>
    <div class="card-body">
      <div id="stdBody" class="text-muted">Select a course.</div>
    </div>
  </div>

  <!-- Discount Offers Section -->
  <div class="card section-card mb-3" id="cardDiscounts">
    <div class="card-header d-flex justify-content-between align-items-center">
      <div class="fw-semibold">3) Discount Offers</div>
      <div>
        <button type="button" class="btn btn-outline-primary btn-sm d-none" id="btnAddDiscount">Add New Discount Offer</button>
        <button type="button" class="btn btn-primary btn-sm d-none" id="btnSaveDiscounts">Save All</button>
      </div>
    </div>
    <div class="card-body">
      <div id="discBody" class="text-muted">Select a course.</div>
      <div class="table-responsive d-none" id="discTableWrap">
        <table class="table table-bordered table-tight align-middle mb-0" id="discTable">
          <thead class="table-light">
            <tr>
              <th class="w-160">Offer Name</th>
              <th class="w-140">Type</th>
              <th class="w-120">% Discount</th>
              <th class="w-140">Payable Fee (LKR)</th>
              <th>Remarks</th>
              <th class="w-150">Status</th>
              <th class="w-120">Sort</th>
              <th class="w-160">Action</th>
            </tr>
          </thead>
          <tbody id="discTbody"></tbody>
        </table>
      </div>
      <div class="small text-muted mt-2 d-none" id="discHint">
        Payable Fee is auto-calculated from the course’s Standard Fee (Course Fee + Registration Fee). You can still adjust it if needed.
      </div>
    </div>
  </div>

  <!-- Installment Plans Section -->
  <div class="card section-card mb-3" id="cardInstallments">
    <div class="card-header d-flex justify-content-between align-items-center">
      <div class="fw-semibold">4) Installment Plans</div>
      <button type="button" class="btn btn-primary btn-sm d-none" id="btnAddPlan">Add New Installment Plan</button>
    </div>
    <div class="card-body">
      <div id="instBody" class="text-muted">Select a course.</div>
      <div class="table-responsive d-none" id="instTableWrap">
        <table class="table table-bordered table-tight align-middle mb-0" id="instTable">
          <thead class="table-light">
            <tr>
              <th>Plan Name</th>
              <th class="w-120 text-center">#Inst</th>
              <th class="w-140 text-end">Total Fee (LKR)</th>
              <th class="w-140 text-end">Registration Fee</th>
              <th class="w-140 text-end">Certificate Fee (USD)</th>
              <th class="w-120 text-center">Duration</th>
              <th>Remarks</th>
              <th class="w-150">Status</th>
              <th class="w-120">Sort</th>
              <th class="w-160">Action</th>
            </tr>
          </thead>
          <tbody id="instTbody"></tbody>
        </table>
      </div>
    </div>
  </div>

</div>
</main>

<!-- Standard Fee Modal -->
<div class="modal fade" id="standardModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content rounded-4">
      <div class="modal-header">
        <h5 class="modal-title">Update Standard Fee</h5>
        <button class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" id="stdPlanId" value="0">
        <div class="mb-2">
          <label class="form-label">Plan Name</label>
          <input type="text" class="form-control" id="stdPlanName" placeholder="Standard">
        </div>
        <div class="row g-3">
          <div class="col-md-4">
            <label class="form-label">Course Fee (LKR)</label>
            <input type="number" step="0.01" class="form-control" id="stdCourseFee">
          </div>
          <div class="col-md-4">
            <label class="form-label">Registration Fee (LKR)</label>
            <input type="number" step="0.01" class="form-control" id="stdRegFee">
          </div>
          <div class="col-md-4">
            <label class="form-label">Certificate Fee (USD) <span class="muted">(optional)</span></label>
            <input type="number" step="0.01" class="form-control" id="stdCertFee">
          </div>
        </div>
        <div class="form-text mt-2">Currency: LKR for course/registration; USD for certificate by default.</div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary" id="stdSaveBtn">Save</button>
        <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<!-- Discount Offer Modal -->
<div class="modal fade" id="discountModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content rounded-4">
      <div class="modal-header">
        <h5 class="modal-title">Discount Offer</h5>
        <button class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" id="discRowIndex" value="-1">
        <div class="mb-2">
          <label class="form-label">Offer Name</label>
          <input type="text" class="form-control" id="dOfferName" placeholder="Early Bird 25%">
        </div>
        <div class="row g-3">
          <div class="col-md-5">
            <label class="form-label">Type</label>
            <select class="form-select" id="dType">
              <option value="full">Full Payment</option>
              <option value="part">Part Payment</option>
            </select>
          </div>
          <div class="col-md-3">
            <label class="form-label">Discount %</label>
            <input type="number" class="form-control" id="dPct" min="0" max="100" step="0.01" value="0">
          </div>
          <div class="col-md-4">
            <label class="form-label">Payable Fee (LKR)</label>
            <input type="number" class="form-control" id="dPayable" step="0.01">
          </div>
        </div>
        <div class="mt-2">
          <label class="form-label">Remarks / Notes</label>
          <textarea class="form-control" id="dRemarks" rows="2" placeholder="Valid before course start date"></textarea>
        </div>
        <div class="row g-3 mt-2">
          <div class="col-md-6">
            <label class="form-label">Status</label>
            <select class="form-select" id="dStatus">
              <option value="active">active</option>
              <option value="inactive">inactive</option>
            </select>
          </div>
          <div class="col-md-6">
            <label class="form-label">Sort</label>
            <input type="number" class="form-control" id="dSort" value="0" step="1">
          </div>
        </div>
        <div class="form-text mt-2">Payable is auto-calculated from the course’s Standard Fee. You can override it.</div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary" id="discSaveOne">Save</button>
        <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<!-- Installment Plan Modal -->
<div class="modal fade" id="planModal" tabindex="-1" aria-hidden="true">
  <div class="modal-dialog modal-xl">
    <div class="modal-content rounded-4">
      <div class="modal-header">
        <h5 class="modal-title">Installment Plan</h5>
        <button class="btn-close" data-bs-dismiss="modal"></button>
      </div>
      <div class="modal-body">
        <input type="hidden" id="pId" value="0">
        <div class="row g-3">
          <div class="col-lg-4">
            <label class="form-label">Plan Name</label>
            <input type="text" class="form-control" id="pName" placeholder="6-Month Plan">
          </div>
          <div class="col-lg-2">
            <label class="form-label"># Installments</label>
            <input type="number" class="form-control" id="pCount" min="1" value="1">
          </div>
          <div class="col-lg-3">
            <label class="form-label">Total Fee (LKR)</label>
            <input type="number" class="form-control" id="pTotal" step="0.01" value="0">
          </div>
          <div class="col-lg-3">
  <label class="form-label">Registration Fee (LKR)</label>
  <input type="number" class="form-control" id="pRegFee" step="0.01" value="0">
</div>
          <div class="col-lg-3">
  <label class="form-label">Certificate Fee (USD) <span class="muted">(optional)</span></label>
  <input type="number" class="form-control" id="pCert" step="0.01" value="0">
</div>

          <div class="col-lg-3">
            <label class="form-label">Duration</label>
            <div class="input-group">
              <input type="number" class="form-control" id="pDuration" min="0" value="0">
              <span class="input-group-text">months</span>
            </div>
          </div>
        </div>
        <div class="row g-3 mt-2">
          <div class="col-md-3">
            <label class="form-label">Status</label>
            <select class="form-select" id="pStatus">
              <option value="active">active</option>
              <option value="inactive">inactive</option>
            </select>
          </div>
          <div class="col-md-3">
            <label class="form-label">Sort</label>
            <input type="number" class="form-control" id="pSort" value="0" step="1">
          </div>
        </div>

        <hr>

        <div class="d-flex align-items-center gap-2 mb-2">
          <button class="btn btn-outline-primary btn-sm" id="pAddRow">+ Add Installment</button>
          <button class="btn btn-outline-secondary btn-sm" id="pCopyLast">Copy last</button>
          <div class="ms-auto small">
            Sum of Amounts: <b id="pSum">0</b> LKR
            <span class="badge ms-2" id="pSumBadge"></span>
          </div>
        </div>

        <div class="table-responsive">
          <table class="table table-bordered table-tight align-middle" id="pTable">
            <thead class="table-light">
              <tr>
                <th class="w-120">Installment No</th>
                <th class="w-160">Due Date</th>
                <th class="w-140">Amount (LKR)</th>
                <th>Notes</th>
                <th class="w-120">Action</th>
              </tr>
            </thead>
            <tbody id="pTbody"></tbody>
          </table>
        </div>
        <div class="form-text">Validation: total of installment amounts must equal the plan Total Fee.</div>
      </div>
      <div class="modal-footer">
        <button class="btn btn-primary" id="pSave">Save Plan</button>
        <button class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
      </div>
    </div>
  </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
(function(){
  const API = '/edenrms/pages/payment_manager_api.php';
  let ctx = { courseId:0, courseName:'', standard:{ course_fee_lkr:0, registration_fee_lkr:0 } };
  let discRows = [];
  const money = n => Number(n||0).toLocaleString(undefined,{maximumFractionDigits:2});

  function getStdTotalLKR(){
    return (ctx.standard.course_fee_lkr || 0) + (ctx.standard.registration_fee_lkr || 0);
  }
  function enableSectionButtons(on){
    const m = on ? 'removeClass' : 'addClass';
    $('#btnEditStandard')[m]('d-none');
    $('#btnAddDiscount')[m]('d-none');
    $('#btnSaveDiscounts')[m]('d-none');
    $('#btnAddPlan')[m]('d-none');
  }
  function showCourseMeta(meta){
    $('#mCourseName').text(meta.course_name || '');
    $('#mStandardFee').text(money(meta.standard_total_lkr || 0));
    $('#mDuration').text(meta.duration || '—');
    $('#mCurrency').text(meta.currency || 'LKR');
    $('#courseMeta').removeClass('d-none');
  }
  function escapeHtml(s){ const d=document.createElement('div'); d.textContent=(s==null?'':s); return d.innerHTML; }

  function loadAll(){
    if(!ctx.courseId){ 
      enableSectionButtons(false);
      $('#courseMeta').addClass('d-none');
      $('#stdBody').text('Select a course.');
      $('#discBody').text('Select a course.');
      $('#instBody').text('Select a course.');
      $('#discTableWrap,#instTableWrap').addClass('d-none');
      return;
    }
    enableSectionButtons(true);

    $.getJSON(API, {action:'course_overview', course_id:ctx.courseId}, function(r){
      ctx.standard = {
  course_fee_lkr: +r.standard.course_fee_lkr || 0,
  registration_fee_lkr: +r.standard.registration_fee_lkr || 0,
  certificate_fee_usd: +r.standard.certificate_fee_usd || 0
};

      showCourseMeta(r.meta);

      $('#stdBody').html(`
        <div class="summary-row d-flex flex-wrap gap-4">
          <div><b>Plan:</b> ${escapeHtml(r.standard.plan_name||'Standard')}</div>
          <div><b>Course Fee:</b> ${money(r.standard.course_fee_lkr)}</div>
          <div><b>Registration Fee:</b> ${money(r.standard.registration_fee_lkr)}</div>
          <div><b>Certificate Fee (USD):</b> ${money(r.standard.certificate_fee_usd)}</div>
          <div><span class="badge badge-soft">Currency: LKR (+ USD cert)</span></div>
        </div>
      `);

      $.getJSON(API, {action:'get_discount_offers', course_id:ctx.courseId}, function(d){
        discRows = Array.isArray(d.rows) ? d.rows : [];
        renderDiscountTable();
      });

      $.getJSON(API, {action:'get_installment_plans', course_id:ctx.courseId}, function(d){
        renderPlansTable(Array.isArray(d.rows)?d.rows:[]);
      });
    });
  }

  $('#pmCourse').on('change', function(){
    const id = +($(this).val()||0);
    const name = $('#pmCourse option:selected').text();
    ctx.courseId = id; ctx.courseName = name || '';
    $('#hint').text(id ? ('Managing: ' + ctx.courseName) : 'Choose a course to manage fees, discounts and installments.');
    loadAll();
  });

  /* ---------------- STANDARD FEE ---------------- */
  $('#btnEditStandard').on('click', function(){
    $.getJSON(API, {action:'get_standard_fee', course_id:ctx.courseId})
      .done(function(r){
        $('#stdPlanId').val(r.plan_id||0);
        $('#stdPlanName').val(r.plan_name||'Standard');
        $('#stdCourseFee').val(r.course_fee_lkr||0);
        $('#stdRegFee').val(r.registration_fee_lkr||0);
        $('#stdCertFee').val(r.certificate_fee_usd||0);
        new bootstrap.Modal(document.getElementById('standardModal')).show();
      })
      .fail(function(xhr){
        alert('API error: ' + (xhr.responseText || xhr.status + ' ' + xhr.statusText));
      });
  });

  $('#stdSaveBtn').on('click', function(){
    const payload = {
      course_id: ctx.courseId,
      plan_id: +$('#stdPlanId').val()||0,
      plan_name: $('#stdPlanName').val()||'Standard',
      course_fee_lkr: parseFloat($('#stdCourseFee').val()||0),
      registration_fee_lkr: parseFloat($('#stdRegFee').val()||0),
      certificate_fee_usd: parseFloat($('#stdCertFee').val()||0),
    };
    $.ajax({
      url: API + '?action=save_standard_fee',
      method: 'POST',
      data: { payload: JSON.stringify(payload) } // form-encoded to avoid 415
    })
    .done(function(){
      bootstrap.Modal.getInstance(document.getElementById('standardModal')).hide();
      loadAll();
    })
    .fail(function(xhr){
      alert('Save failed:\n' + (xhr.responseText||''));
    });
  });

  /* ---------------- DISCOUNTS ---------------- */
  function renderDiscountTable(){
    const has = discRows.length>0;
    $('#discBody')[has?'addClass':'removeClass']('d-none');
    $('#discTableWrap,#discHint')[has?'removeClass':'addClass']('d-none');
    if(!has){ $('#discBody').text('No discount offers yet. Click “Add New Discount Offer”.'); return; }

    const tb = $('#discTbody').empty();
    discRows.forEach((r, i)=>{
      tb.append(`
        <tr data-i="${i}">
          <td>${escapeHtml(r.offer_name||'')}</td>
          <td class="nowrap">${r.offer_type==='part'?'Part Payment':'Full Payment'}</td>
          <td class="text-end">${Number(r.discount_pct||0).toFixed(2)}</td>
          <td class="text-end">${money(r.payable_fee_lkr||0)}</td>
          <td>${escapeHtml(r.remarks||'')}</td>
          <td class="nowrap">${escapeHtml(r.status||'active')}</td>
          <td class="text-end">${parseInt(r.sort_order||0,10)}</td>
          <td>
            <button class="btn btn-sm btn-outline-secondary me-1 btnDiscEdit">Edit</button>
            <button class="btn btn-sm btn-outline-danger btnDiscDel">Delete</button>
          </td>
        </tr>
      `);
    });
  }

  $('#btnAddDiscount').on('click', function(){
    $('#discRowIndex').val(-1);
    $('#dOfferName').val('');
    $('#dType').val('full');
    $('#dPct').val(0);
    const base = (ctx.standard.course_fee_lkr||0) + (ctx.standard.registration_fee_lkr||0);
    $('#dPayable').val(base.toFixed(2));
    $('#dRemarks').val('');
    $('#dStatus').val('active');
    $('#dSort').val(discRows.length);
    new bootstrap.Modal(document.getElementById('discountModal')).show();
    recomputePayable();
  });

  $(document).on('click','.btnDiscEdit', function(){
    const i = +($(this).closest('tr').attr('data-i'));
    const r = discRows[i];
    $('#discRowIndex').val(i);
    $('#dOfferName').val(r.offer_name||'');
    $('#dType').val(r.offer_type||'full');
    $('#dPct').val(r.discount_pct||0);
    $('#dPayable').val((r.payable_fee_lkr||0).toFixed(2));
    $('#dRemarks').val(r.remarks||'');
    $('#dStatus').val(r.status||'active');
    $('#dSort').val(r.sort_order||0);
    new bootstrap.Modal(document.getElementById('discountModal')).show();
  });

  $(document).on('click','.btnDiscDel', function(){
    const i = +($(this).closest('tr').attr('data-i'));
    discRows.splice(i,1);
    renderDiscountTable();
  });

  function recomputePayable(){
    const pct = parseFloat($('#dPct').val()||0);
    const base = (ctx.standard.course_fee_lkr||0) + (ctx.standard.registration_fee_lkr||0);
    let payable = base * (1 - (pct/100));
    if (payable < 0) payable = 0;
    if (!$('#dPayable').data('touched')) {
      $('#dPayable').val(payable.toFixed(2));
    }
  }
  $('#dPct').on('input', recomputePayable);
  $('#dPayable').on('input', ()=>$('#dPayable').data('touched', true));

  $('#discSaveOne').on('click', function(){
    const i = +$('#discRowIndex').val();
    const r = {
      offer_name: ($('#dOfferName').val()||'').trim(),
      offer_type: $('#dType').val()==='part' ? 'part':'full',
      discount_pct: parseFloat($('#dPct').val()||0),
      payable_fee_lkr: parseFloat($('#dPayable').val()||0),
      remarks: ($('#dRemarks').val()||'').trim(),
      status: $('#dStatus').val()==='inactive' ? 'inactive' : 'active',
      sort_order: parseInt($('#dSort').val()||0,10)
    };
    if(!r.offer_name){ alert('Offer Name is required.'); return; }
    if(r.discount_pct<0 || r.discount_pct>100){ alert('Discount % must be between 0 and 100.'); return; }
    if (i>=0) discRows[i] = r; else discRows.push(r);
    bootstrap.Modal.getInstance(document.getElementById('discountModal')).hide();
    renderDiscountTable();
  });

  $('#btnSaveDiscounts').on('click', function(){
    $.ajax({
      url: API + '?action=save_discount_offers',
      method: 'POST',
      contentType: 'application/json',
      data: JSON.stringify({ course_id: ctx.courseId, offers: discRows })
    })
    .done(function(){ loadAll(); })
    .fail(function(xhr){ alert('Save failed:\n' + (xhr.responseText||'')); });
  });

  /* ---------------- INSTALLMENT PLANS ---------------- */
  function renderPlansTable(rows){
    const has = rows.length>0;
    $('#instBody')[has?'addClass':'removeClass']('d-none');
    $('#instTableWrap')[has?'removeClass':'addClass']('d-none');
    if(!has){ $('#instBody').text('No installment plans yet. Click “Add New Installment Plan”.'); return; }

    const tb = $('#instTbody').empty();
    rows.forEach(r=>{
      tb.append(`
        <tr data-id="${r.id}">
          <td>${escapeHtml(r.plan_name||'')}</td>
          <td class="text-center">${r.installments_count||0}</td>
          <td class="text-end">${money(r.total_fee_lkr||0)}</td>
          <td class="text-end">${money(r.registration_fee_lkr||0)}</td>
<td class="text-end">${money(r.certificate_fee_usd||0)}</td>
          <td class="text-center">${r.duration_months ? (r.duration_months+' mo'):'—'}</td>
          <td>${escapeHtml(r.remarks||'')}</td>
          <td class="nowrap">${escapeHtml(r.status||'active')}</td>
          <td class="text-end">${parseInt(r.sort_order||0,10)}</td>
          <td>
            <button class="btn btn-sm btn-outline-secondary me-1 btnPlanEdit">Edit</button>
            <button class="btn btn-sm btn-outline-danger btnPlanDel">Delete</button>
          </td>
        </tr>
      `);
    });
  }

  $('#btnAddPlan').on('click', function(){
    const base = getStdTotalLKR();
    fillPlanModal({
  id: 0,
  plan_name: '',
  installments_count: 1,
  total_fee_lkr: base,
  certificate_fee_usd: (ctx.standard.certificate_fee_usd || 0),
  duration_months: 0,
  remarks: '',
  status: 'active',
  sort_order: 0,
  lines: []
});

    new bootstrap.Modal(document.getElementById('planModal')).show();
    sumCheck();
  });

  $(document).on('click','.btnPlanEdit', function(){
    const id = +($(this).closest('tr').attr('data-id'));
    $.getJSON(API, {action:'get_installment_plan', plan_id:id}, function(r){
      r.lines = Array.isArray(r.lines)?r.lines:[];
      fillPlanModal(r);
      new bootstrap.Modal(document.getElementById('planModal')).show();
      sumCheck();
    });
  });

  $(document).on('click','.btnPlanDel', function(){
    if(!confirm('Delete this plan?')) return;
    const id = +($(this).closest('tr').attr('data-id'));
    $.post(API + '?action=delete_installment_plan', { plan_id:id })
      .done(loadAll)
      .fail(xhr=>alert('Delete failed:\n' + (xhr.responseText||'')));
  });

  function fillPlanModal(p){
      $('#pRegFee').val(p.registration_fee_lkr || 0);
    $('#pId').val(p.id||0);
    $('#pName').val(p.plan_name||'');
    $('#pCount').val(p.installments_count||1);
    $('#pTotal').val(p.total_fee_lkr||0);
$('#pCert').val(p.certificate_fee_usd || 0);
$('#pDuration').val(p.duration_months||0);
    $('#pStatus').val(p.status||'active');
    $('#pSort').val(p.sort_order||0);

    const tb = $('#pTbody').empty();
    (p.lines||[]).forEach(line=>{
      tb.append(lineRowHtml(line.installment_no, line.due_date, line.amount_lkr, line.notes));
    });
    if ((p.lines||[]).length===0){
      tb.append(lineRowHtml(1,'', p.total_fee_lkr || 0, ''));
    }
  }

  function lineRowHtml(no,due,amt,notes){
    return `
      <tr>
        <td><input type="number" class="form-control form-control-sm l-no" value="${no||1}" min="1"></td>
        <td><input type="date" class="form-control form-control-sm l-due" value="${due||''}"></td>
        <td><input type="number" class="form-control form-control-sm l-amt" step="0.01" value="${amt||0}"></td>
        <td><input type="text" class="form-control form-control-sm l-notes" value="${notes||''}"></td>
        <td><button class="btn btn-outline-danger btn-sm l-del" type="button">Delete</button></td>
      </tr>
    `;
  }
  function renumberLines(){ $('#pTbody tr').each(function(i){ $(this).find('.l-no').val(i+1); }); }
  function sumCheck(){
  let sum = 0;
  $('#pTbody .l-amt').each(function(){
    sum += parseFloat($(this).val() || 0);
  });

  $('#pSum').text(money(sum));

  const total = parseFloat($('#pTotal').val() || 0);
  const reg   = parseFloat($('#pRegFee').val() || 0);
  const grand = total + reg;

  const badge = $('#pSumBadge').removeClass('text-bg-success text-bg-danger');

  if (Math.abs(sum - grand) < 0.005){
    badge.addClass('text-bg-success').text('OK');
  } else {
    badge.addClass('text-bg-danger').text('Mismatch');
  }
}
  $(document).on('input','#pTotal, #pRegFee, #pTbody .l-amt', sumCheck);

  $('#pAddRow').on('click', function(){
    $('#pTbody').append(lineRowHtml($('#pTbody tr').length+1,'','', ''));
    sumCheck();
  });
  $('#pCopyLast').on('click', function(){
    const last = $('#pTbody tr:last');
    if(!last.length){ $('#pAddRow').click(); return; }
    $('#pTbody').append(lineRowHtml(
      $('#pTbody tr').length+1,
      last.find('.l-due').val(),
      last.find('.l-amt').val(),
      last.find('.l-notes').val()
    ));
    sumCheck();
  });
  $(document).on('click','.l-del', function(){
    $(this).closest('tr').remove(); renumberLines(); sumCheck();
  });

  $('#pSave').on('click', function(){
    const plan = {
  id: +($('#pId').val()||0),
  course_id: ctx.courseId,
  plan_name: ($('#pName').val()||'').trim(),
  installments_count: parseInt($('#pCount').val()||0,10),
  total_fee_lkr: parseFloat($('#pTotal').val()||0),
  registration_fee_lkr: parseFloat($('#pRegFee').val()||0),
  certificate_fee_usd: parseFloat($('#pCert').val()||0),
  duration_months: parseInt($('#pDuration').val()||0,10),
  status: $('#pStatus').val()==='inactive' ? 'inactive' : 'active',
  sort_order: parseInt($('#pSort').val()||0,10),
  lines: []
};

    if (!plan.plan_name){ alert('Plan Name is required.'); return; }
    if (plan.installments_count<=0){ alert('# Installments must be >= 1.'); return; }
    $('#pTbody tr').each(function(){
      plan.lines.push({
        installment_no: parseInt($(this).find('.l-no').val()||0,10),
        due_date: $(this).find('.l-due').val()||null,
        amount_lkr: parseFloat($(this).find('.l-amt').val()||0),
        notes: ($(this).find('.l-notes').val()||'').trim()
      });
    });
    const sum = plan.lines.reduce((a,b)=>a+(+b.amount_lkr||0),0);
    const grandTotal = plan.total_fee_lkr + plan.registration_fee_lkr;

if (Math.abs(sum - grandTotal) > 0.005){
  alert('Validation failed: Sum of installment amounts must equal Total Fee + Registration Fee.');
  return;
}
    $.ajax({
      url: API + '?action=save_installment_plan',
      method: 'POST',
      data: { payload: JSON.stringify(plan) } // form-encoded to avoid 415
    })
    .done(function(){
      bootstrap.Modal.getInstance(document.getElementById('planModal')).hide();
      loadAll();
    })
    .fail(function(xhr){
      alert('Save failed:\n' + (xhr.responseText||''));
    });
  });

  // initial
  enableSectionButtons(false);
})();
</script>
</body>
</html>
