<?php
// ---------- allow iframe from same origin ----------
header('X-Frame-Options: SAMEORIGIN');
header("Content-Security-Policy: frame-ancestors 'self'");

// ---------- minimal boot ----------
if (session_status() === PHP_SESSION_NONE) session_start();
require_once __DIR__ . '/../../includes/db.php';
$mysqli = isset($conn) && $conn instanceof mysqli ? $conn : new mysqli("localhost","root","","edencamp_edencampus");
$mysqli->set_charset("utf8mb4");
$student_id = (int)($_GET['student_id'] ?? $_POST['student_id'] ?? 0);

// (optional) load existing schedule rows here if you have them…
$rows = [
  ['n'=>1,'c'=>0,'r'=>0,'u'=>0,'d'=>''],
];
?>
<!doctype html><html lang="en"><head>
<meta charset="utf-8">
<title>Customize Installment Plan</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/assets/css/bootstrap.min.css">
<link rel="stylesheet" href="/assets/css/bootstrap-icons.css">
<style>
  body{padding:12px;background:#fff}
  .kp-card{border:1px solid #e9ecef;border-radius:.65rem}
  .table thead th{background:#f8f9fa}
  .btn-icon{width:32px;height:32px;padding:0}
</style>
</head><body>
<?php if (isset($_GET['embed'])): ?>
  <!-- Compact embed skin (Bootstrap + styling + light DOM polish) -->
  <link rel="stylesheet" href="/assets/css/bootstrap.min.css">
  <style>
    body{background:#fff;margin:0}
    .ec-embed{padding:16px}
    .ec-embed h1,.ec-embed h2,.ec-embed h3{display:none} /* We use the parent modal title */
    .ec-embed table{width:100%}
    .ec-embed .table thead th{background:#f8f9fa}
    /* Make all plain inputs look modern even if they have no classes */
    .ec-embed input[type="text"], .ec-embed input[type="number"],
    .ec-embed input[type="date"], .ec-embed select, .ec-embed textarea{
      border:1px solid #dee2e6; border-radius:.5rem; padding:.45rem .6rem; font-size:.95rem; width:100%;
    }
    .ec-embed .btn{border-radius:.55rem}
    .ec-embed .hint{color:#6c757d; font-size:.85rem}
    /* Two-column layout helper (used by Add Payment to match your screenshot) */
    .ec-grid{display:grid; grid-template-columns:1fr 1fr; gap:16px}
    @media (max-width: 900px){ .ec-grid{grid-template-columns:1fr} }
  </style>
  <script>
    (function(){
      // Wrap page
      var wrap = document.createElement('div'); wrap.className='ec-embed'; 
      while (document.body.firstChild) wrap.appendChild(document.body.firstChild);
      document.body.appendChild(wrap);

      // Make any tables pretty
      document.querySelectorAll('table').forEach(function(t){
        t.classList.add('table','table-bordered','table-sm','align-middle');
      });

      // Upgrade buttons
      document.querySelectorAll('button, input[type=button], input[type=submit]').forEach(function(b){
        var txt=(b.value||b.textContent||'').trim();
        b.classList.add('btn','btn-sm');
        if (/close/i.test(txt)) { b.classList.add('btn-secondary'); }
        else if (/add|\+|save|send/i.test(txt)) { b.classList.add('btn-primary'); }
        else { b.classList.add('btn-outline-secondary'); }
      });

      // --- Add Payment page: auto split "Balance Payments" + form into two columns ---
      var balHdr = Array.from(document.querySelectorAll('b,strong,h4,h5'))
        .find(x=>/balance payments/i.test((x.textContent||'').trim()));
      if (balHdr){
        var table = balHdr.parentElement.querySelector('table');
        var grid  = document.createElement('div'); grid.className='ec-grid';
        var L = document.createElement('div'), R = document.createElement('div');
        L.appendChild(balHdr); if (table) L.appendChild(table);

        // move everything after the table into the right side (form)
        var start = (table && table.nextElementSibling) ? table.nextElementSibling : balHdr.nextElementSibling;
        while (start){ var next = start.nextElementSibling; R.appendChild(start); start = next; }

        wrap.innerHTML=''; wrap.appendChild(grid); grid.appendChild(L); grid.appendChild(R);
      }
    })();
  </script>
<?php endif; ?>

<h5 class="mb-3">Customize Installment Plan</h5>

<div class="kp-card p-3 mb-3">
  <div class="table-responsive">
    <table class="table table-bordered align-middle text-center m-0" id="planTbl">
      <thead>
        <tr>
          <th style="width:64px">#</th>
          <th>Course Fee (LKR)</th>
          <th>Reg Fee (LKR)</th>
          <th>Cert Fee (USD)</th>
          <th style="width:190px">Due Date</th>
          <th style="width:52px"></th>
        </tr>
      </thead>
      <tbody>
      <?php foreach ($rows as $r): ?>
        <tr>
          <td><input class="form-control form-control-sm text-center" value="<?= (int)$r['n'] ?>"></td>
          <td><input class="form-control form-control-sm text-end" value="<?= number_format((float)$r['c'],2) ?>"></td>
          <td><input class="form-control form-control-sm text-end" value="<?= number_format((float)$r['r'],2) ?>"></td>
          <td><input class="form-control form-control-sm text-end" value="<?= number_format((float)$r['u'],2) ?>"></td>
          <td><input type="date" class="form-control form-control-sm" value="<?= htmlspecialchars($r['d']) ?>"></td>
          <td><button class="btn btn-outline-danger btn-sm btn-icon rm-row"><i class="bi bi-x"></i></button></td>
        </tr>
      <?php endforeach; ?>
      </tbody>
    </table>
  </div>
  <button class="btn btn-outline-secondary btn-sm mt-2" id="addRow"><i class="bi bi-plus-lg"></i> + row</button>
</div>

<div class="mb-2 fw-semibold">Reason for requesting a custom installment plan? <span class="text-danger">*</span></div>
<textarea class="form-control mb-2" id="reason" rows="3" placeholder="Please provide a valid reason"></textarea>

<div class="alert alert-secondary small">
  The student was clearly informed that the requested plan must be authorized by the Branch Manager.
  If authorization fails, they revert to the pre-defined plan.
</div>

<div class="form-check mb-3">
  <input class="form-check-input" type="checkbox" id="confirm">
  <label class="form-check-label" for="confirm">I confirm I informed the student about the above.</label>
</div>

<div class="d-flex gap-2 justify-content-end">
  <button class="btn btn-secondary" id="btnClose">Close</button>
  <button class="btn btn-primary" id="btnSend"><i class="bi bi-send"></i> Send for Authorization</button>
</div>

<script src="/assets/js/bootstrap.bundle.min.js"></script>
<script>
const tbody = document.querySelector('#planTbl tbody');
document.getElementById('addRow').onclick = () => {
  const tr = document.createElement('tr');
  tr.innerHTML = `
    <td><input class="form-control form-control-sm text-center" value="${tbody.children.length+1}"></td>
    <td><input class="form-control form-control-sm text-end" value="0.00"></td>
    <td><input class="form-control form-control-sm text-end" value="0.00"></td>
    <td><input class="form-control form-control-sm text-end" value="0.00"></td>
    <td><input type="date" class="form-control form-control-sm"></td>
    <td><button class="btn btn-outline-danger btn-sm btn-icon rm-row"><i class="bi bi-x"></i></button></td>`;
  tbody.appendChild(tr);
};
tbody.addEventListener('click', e=>{
  if(e.target.closest('.rm-row')){
    e.preventDefault();
    e.target.closest('tr').remove();
    [...tbody.querySelectorAll('tr')].forEach((tr,i)=> tr.querySelector('td:first-child input').value = i+1);
  }
});

function collect(){
  const rows=[];
  tbody.querySelectorAll('tr').forEach(tr=>{
    const [n,c,r,u,d] = [...tr.querySelectorAll('input')].map(i=>i.value.trim());
    rows.push({ n:parseInt(n||'0',10)||0, c:parseFloat(c||'0')||0, r:parseFloat(r||'0')||0, u:parseFloat(u||'0')||0, d });
  });
  return rows;
}

document.getElementById('btnSend').onclick = async ()=>{
  const reason = document.getElementById('reason').value.trim();
  if(!reason){ alert('Please enter a reason.'); return; }
  if(!document.getElementById('confirm').checked){ alert('Please confirm you informed the student.'); return; }

  const fd = new FormData();
  fd.append('student_id', '<?= (int)$student_id ?>');
  fd.append('rows', JSON.stringify(collect()));
  fd.append('reason', reason);

  try{
    const res = await fetch('/edenrms/ajax/request_custom_plan.php', { method:'POST', body:fd });
    const j = await res.json().catch(()=>({ok:false}));
    if(!res.ok || j.ok===false) throw new Error(j.message || 'Server error');
    // tell parent to close and refresh payments tab
    window.parent.postMessage({type:'ec:close-remote-modal', studentId: <?= (int)$student_id ?>, afterTab:'#payments'}, location.origin);
  }catch(err){ alert('Failed: '+(err.message||'Unknown error')); }
};

document.getElementById('btnClose').onclick = ()=>{
  window.parent.postMessage({type:'ec:close-remote-modal'}, location.origin);
};
</script>
</body></html>
