<?php
header('X-Frame-Options: SAMEORIGIN');
header("Content-Security-Policy: frame-ancestors 'self'");
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);
$plan_id    = (int)($_GET['plan_id'] ?? 0);
?>
<!doctype html><html lang="en"><head>
<meta charset="utf-8">
<title>Add Payment</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}
</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">Add Payment</h5>

<div class="row g-3">
  <div class="col-lg-6">
    <div class="kp-card p-3">
      <div class="d-flex align-items-center mb-2"><i class="bi bi-journal-text me-2"></i><strong>Balance Payments</strong></div>
      <table class="table table-bordered m-0 text-end align-middle">
        <thead><tr><th class="text-start"></th><th>LKR</th><th>USD</th></tr></thead>
        <tbody>
          <tr><td class="text-start">Course Fee</td><td id="b_course">0.00</td><td>0.00</td></tr>
          <tr><td class="text-start">UK Awards Fee</td><td>0.00</td><td id="b_uk">0.00</td></tr>
          <tr class="table-secondary"><td class="text-start">Sub Total</td><td id="b_sub">0.00</td><td id="b_sub_usd">0.00</td></tr>
          <tr><td class="text-start">Late Charges (Penalty)</td><td id="b_late">0.00</td><td>0.00</td></tr>
          <tr class="fw-bold"><td class="text-start">Total Outstanding</td><td id="b_out">0.00</td><td id="b_out_usd">0.00</td></tr>
          <tr><td class="text-start">Accumulated Dues</td><td id="b_due">0.00</td><td id="b_due_usd">0.00</td></tr>
        </tbody>
      </table>
    </div>
  </div>

  <div class="col-lg-6">
    <div class="kp-card p-3">
      <div class="mb-2"><label class="form-label">Fee Type <span class="text-danger">*</span></label>
        <select class="form-select" id="feeType">
          <option value="">Select an Option</option>
          <option>Course Fee</option>
          <option>Registration Fee</option>
          <option>UK Awards Fee</option>
          <option>Late Charges</option>
          <option>Other</option>
        </select>
      </div>

      <div class="mb-2">
        <label class="form-label">Amount <span class="text-danger">*</span></label>
        <div class="input-group">
          <button class="btn btn-outline-secondary dropdown-toggle" data-bs-toggle="dropdown" id="ccyBtn">LKR</button>
          <ul class="dropdown-menu">
            <li><a class="dropdown-item choose-ccy" data-v="LKR">LKR</a></li>
            <li><a class="dropdown-item choose-ccy" data-v="USD">USD</a></li>
          </ul>
          <input type="text" class="form-control text-end" id="amount" value="0.00">
          <button class="btn btn-success" id="addItem"><i class="bi bi-plus-lg"></i></button>
        </div>
      </div>

      <div class="mb-2">
        <label class="form-label">Payment Method</label>
        <select class="form-select" id="method">
          <option>Cash</option><option>Bank Transfer</option><option>Card (Visa/Master)</option><option>Online</option>
        </select>
      </div>

      <div class="mb-2"><label class="form-label">Reference No (optional)</label>
        <input class="form-control" id="ref" placeholder="e.g., slip/txn no">
      </div>

      <div class="mb-3"><label class="form-label">Notes (optional)</label>
        <textarea class="form-control" id="notes" rows="2" placeholder="Any note for this payment"></textarea>
      </div>

      <div class="alert alert-info small">
        You can add multiple items with the <strong>+</strong> before saving.
        The system will save a single payment equal to the total LKR amount (USD is kept separately).
      </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="btnSave"><i class="bi bi-save"></i> Save Payment</button>
      </div>
    </div>
  </div>
</div>

<script src="/assets/js/bootstrap.bundle.min.js"></script>
<script>
let CCY = 'LKR';
const items = [];
document.querySelectorAll('.choose-ccy').forEach(a=>{
  a.onclick = ()=>{ CCY=a.dataset.v; document.getElementById('ccyBtn').textContent=CCY; };
});
document.getElementById('addItem').onclick = ()=>{
  const t = document.getElementById('feeType').value.trim();
  const a = parseFloat((document.getElementById('amount').value || '0').replace(/[^0-9.\-]/g,''))||0;
  if(!t){ alert('Choose Fee Type'); return; }
  if(a<=0){ alert('Enter amount'); return; }
  items.push({type:t, currency:CCY, amount:a});
  document.getElementById('amount').value='0.00';
  alert('Item added: '+t+' '+CCY+' '+a.toFixed(2));
};

document.getElementById('btnSave').onclick = async ()=>{
  if(items.length===0){ alert('Add at least one item'); return; }
  const fd = new FormData();
  fd.append('student_id','<?= (int)$student_id ?>');
  fd.append('plan_id','<?= (int)$plan_id ?>');
  fd.append('items', JSON.stringify(items));
  fd.append('method', document.getElementById('method').value);
  fd.append('reference', document.getElementById('ref').value.trim());
  fd.append('notes', document.getElementById('notes').value.trim());
  try{
    const res = await fetch('/edenrms/ajax/save_payment.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');
    // close & refresh parent 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>
