<?php
/** Event & excursion accounts — costs and per-student billing. */
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id'])) { header('Location: ../index.php'); exit; }

require_once '../config.php';
requireModule('finance_suite');
require_once __DIR__ . '/inc/finance_lib.php';
require_once __DIR__ . '/inc/layout.php';

$conn = getDBConnection();
finance_ensure_tables($conn);

finance_page_header('Events & Excursions', 'events');
?>
<div class="d-flex justify-content-between align-items-center mb-3">
    <p class="text-muted small mb-0">Dedicated accounts for trips, excursions and extracurricular projects.</p>
    <button class="btn btn-success btn-sm" onclick="openEvent()"><i class="fas fa-plus me-1"></i>New Event</button>
</div>

<div class="row g-3" id="eventGrid">
    <div class="col-12 text-center text-muted py-4">Loading…</div>
</div>

<!-- Event editor modal -->
<div class="modal fade" id="eventModal" tabindex="-1"><div class="modal-dialog"><div class="modal-content">
    <form id="eventForm">
        <div class="modal-header"><h5 class="modal-title" id="eventModalTitle">New Event</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
        <div class="modal-body">
            <input type="hidden" name="action" value="save"><input type="hidden" name="id" id="ev_id" value="0">
            <div class="row g-2">
                <div class="col-12"><label class="form-label small">Event name *</label><input class="form-control" name="name" id="ev_name" required></div>
                <div class="col-6"><label class="form-label small">Date</label><input type="date" class="form-control" name="event_date" id="ev_date"></div>
                <div class="col-6"><label class="form-label small">Budget (GHS)</label><input type="number" step="0.01" class="form-control" name="budget" id="ev_budget" value="0"></div>
                <div class="col-6"><label class="form-label small">Location</label><input class="form-control" name="location" id="ev_loc"></div>
                <div class="col-6"><label class="form-label small">Status</label>
                    <select class="form-select" name="status" id="ev_status">
                        <option value="planning">Planning</option><option value="active">Active</option><option value="closed">Closed</option>
                    </select></div>
                <div class="col-12"><label class="form-label small">Description</label><textarea class="form-control" name="description" id="ev_desc" rows="2"></textarea></div>
            </div>
        </div>
        <div class="modal-footer"><button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
            <button class="btn btn-success" type="submit">Save</button></div>
    </form>
</div></div></div>

<!-- Event detail modal -->
<div class="modal fade" id="evDetailModal" tabindex="-1"><div class="modal-dialog modal-xl"><div class="modal-content">
    <div class="modal-header"><h5 class="modal-title" id="evDetailTitle">Event</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal"></button></div>
    <div class="modal-body" id="evDetailBody">Loading…</div>
</div></div></div>

<script>
function esc(s){const d=document.createElement('div');d.textContent=s==null?'':s;return d.innerHTML;}
function money(n){return 'GHS '+Number(n||0).toLocaleString(undefined,{minimumFractionDigits:2});}
function stpill(s){const m={planning:'st-planning',active:'st-active',closed:'st-closed'};return `<span class="status-pill ${m[s]||''}">${s}</span>`;}
let CUR_EVENT=null;

function loadEvents(){
  fetch('ajax/events.php?action=list').then(r=>r.json()).then(d=>{
    const g=document.getElementById('eventGrid');
    if(!d.data.length){g.innerHTML='<div class="col-12 text-center text-muted py-4">No events yet.</div>';return;}
    g.innerHTML=d.data.map(e=>{
      const outstanding=Number(e.charged)-Number(e.paid);
      return `<div class="col-md-6 col-lg-4"><div class="fin-card p-3 h-100">
        <div class="d-flex justify-content-between"><h6 class="mb-1">${esc(e.name)}</h6>${stpill(e.status)}</div>
        <div class="small text-muted mb-2">${esc(e.event_date||'')} ${e.location?('· '+esc(e.location)):''}</div>
        <div class="d-flex justify-content-between small"><span>Spend</span><b>${money(e.spend)}</b></div>
        <div class="d-flex justify-content-between small"><span>Budget</span><span>${money(e.budget)}</span></div>
        <div class="d-flex justify-content-between small"><span>Participants</span><span>${e.participants}</span></div>
        <div class="d-flex justify-content-between small"><span>Owed by students</span><b class="${outstanding>0?'text-danger':'text-success'}">${money(outstanding)}</b></div>
        <div class="mt-2 d-flex gap-2">
          <button class="btn btn-sm btn-success flex-grow-1" onclick="openDetail(${e.id})">Open</button>
          <button class="btn btn-sm btn-outline-secondary" onclick='openEvent(${JSON.stringify(e)})'><i class="fas fa-pen"></i></button>
        </div></div></div>`;
    }).join('');
  });
}

function openEvent(e){
  document.getElementById('eventForm').reset();
  document.getElementById('ev_id').value=e?e.id:0;
  document.getElementById('eventModalTitle').textContent=e?'Edit Event':'New Event';
  if(e){ev_name.value=e.name;ev_date.value=e.event_date||'';ev_budget.value=e.budget;ev_loc.value=e.location||'';ev_status.value=e.status;ev_desc.value=e.description||'';}
  new bootstrap.Modal(document.getElementById('eventModal')).show();
}

document.getElementById('eventForm').addEventListener('submit',function(e){
  e.preventDefault();
  fetch('ajax/events.php',{method:'POST',body:new FormData(this)}).then(r=>r.json()).then(d=>{
    if(d.success){bootstrap.Modal.getInstance(document.getElementById('eventModal')).hide();loadEvents();}else alert(d.message);
  });
});

function openDetail(id){
  CUR_EVENT=id;
  new bootstrap.Modal(document.getElementById('evDetailModal')).show();
  renderDetail();
}
function renderDetail(){
  document.getElementById('evDetailBody').innerHTML='Loading…';
  fetch(`ajax/events.php?action=get&id=${CUR_EVENT}`).then(r=>r.json()).then(d=>{
    if(!d.success){document.getElementById('evDetailBody').innerHTML='<div class="text-danger">'+esc(d.message)+'</div>';return;}
    const e=d.event,s=d.summary,outstanding=Number(s.charged)-Number(s.paid);
    document.getElementById('evDetailTitle').textContent=e.name;
    const costs=d.expenses.length?d.expenses.map(x=>`<tr><td>${esc(x.expense_date)}</td><td>${esc(x.category)}</td><td>${esc(x.description)}</td><td>${money(x.amount)}</td></tr>`).join(''):'<tr><td colspan="4" class="text-muted text-center">No costs logged.</td></tr>';
    const parts=d.participants.length?d.participants.map(p=>{
      const bal=Number(p.amount_charged)-Number(p.amount_paid);
      return `<tr><td>${esc(p.student_name)}</td><td>${esc(p.class_name)}</td><td>${money(p.amount_charged)}</td><td>${money(p.amount_paid)}</td>
        <td class="${bal>0?'text-danger':'text-success'}">${money(bal)}</td>
        <td><button class="btn btn-xs btn-outline-primary btn-sm py-0" onclick="payPart(${p.id})">Pay</button>
            <button class="btn btn-xs btn-outline-danger btn-sm py-0" onclick="rmPart(${p.id})"><i class="fas fa-times"></i></button></td></tr>`;
    }).join(''):'<tr><td colspan="6" class="text-muted text-center">No participants billed.</td></tr>';
    document.getElementById('evDetailBody').innerHTML=`
      <div class="row g-2 mb-3">
        <div class="col-3"><div class="fin-stat"><div class="lbl">Spend</div><div class="val">${money(s.spend)}</div></div></div>
        <div class="col-3"><div class="fin-stat"><div class="lbl">Budget</div><div class="val">${money(e.budget)}</div></div></div>
        <div class="col-3"><div class="fin-stat"><div class="lbl">Billed</div><div class="val">${money(s.charged)}</div></div></div>
        <div class="col-3"><div class="fin-stat"><div class="lbl">Owed</div><div class="val ${outstanding>0?'text-danger':''}">${money(outstanding)}</div></div></div>
      </div>
      <div class="row">
        <div class="col-lg-6">
          <div class="d-flex justify-content-between align-items-center"><h6>Costs</h6>
            <button class="btn btn-sm btn-outline-success" onclick="addCostRow()"><i class="fas fa-plus"></i> Add cost</button></div>
          <div id="costForm"></div>
          <table class="table table-sm"><thead><tr><th>Date</th><th>Cat</th><th>Desc</th><th>Amt</th></tr></thead><tbody>${costs}</tbody></table>
        </div>
        <div class="col-lg-6">
          <div class="d-flex justify-content-between align-items-center"><h6>Participants</h6>
            <button class="btn btn-sm btn-outline-success" onclick="addPartRow()"><i class="fas fa-user-plus"></i> Bill students</button></div>
          <div id="partForm"></div>
          <table class="table table-sm"><thead><tr><th>Student</th><th>Class</th><th>Charged</th><th>Paid</th><th>Bal</th><th></th></tr></thead><tbody>${parts}</tbody></table>
        </div>
      </div>`;
  });
}

function addCostRow(){
  document.getElementById('costForm').innerHTML=`<div class="border rounded p-2 mb-2">
    <div class="row g-1">
      <div class="col-4"><input type="date" id="c_date" class="form-control form-control-sm" value="${new Date().toISOString().slice(0,10)}"></div>
      <div class="col-4"><input id="c_cat" class="form-control form-control-sm" placeholder="Category"></div>
      <div class="col-4"><input id="c_amt" type="number" step="0.01" class="form-control form-control-sm" placeholder="Amount"></div>
      <div class="col-8"><input id="c_desc" class="form-control form-control-sm" placeholder="Description"></div>
      <div class="col-4"><button class="btn btn-sm btn-success w-100" onclick="saveCost()">Save</button></div>
    </div></div>`;
}
function saveCost(){
  const fd=new FormData();fd.append('action','add_expense');fd.append('event_id',CUR_EVENT);
  fd.append('expense_date',c_date.value);fd.append('category',c_cat.value);fd.append('description',c_desc.value);fd.append('amount',c_amt.value);
  fetch('ajax/events.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{if(d.success){renderDetail();loadEvents();}else alert(d.message);});
}

function addPartRow(){
  document.getElementById('partForm').innerHTML=`<div class="border rounded p-2 mb-2">
    <div class="input-group input-group-sm mb-1">
      <input id="p_search" class="form-control" placeholder="Search student by name / ID / class">
      <button class="btn btn-outline-secondary" onclick="doSearch()">Search</button></div>
    <select id="p_results" class="form-select form-select-sm mb-1" multiple size="4"></select>
    <div class="input-group input-group-sm">
      <span class="input-group-text">Charge each</span>
      <input id="p_amt" type="number" step="0.01" class="form-control" placeholder="Amount">
      <button class="btn btn-success" onclick="savePart()">Bill</button></div></div>`;
}
function doSearch(){
  fetch(`ajax/events.php?action=search_students&q=${encodeURIComponent(p_search.value)}`).then(r=>r.json()).then(d=>{
    p_results.innerHTML=d.data.map(s=>`<option value="${s.id}">${esc(s.label)}</option>`).join('');
  });
}
function savePart(){
  const ids=Array.from(p_results.selectedOptions).map(o=>o.value);
  if(!ids.length){alert('Select student(s).');return;}
  const fd=new FormData();fd.append('action','add_participants');fd.append('event_id',CUR_EVENT);
  fd.append('student_ids',ids.join(','));fd.append('amount_charged',p_amt.value||0);
  fetch('ajax/events.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{if(d.success){renderDetail();loadEvents();}else alert(d.message);});
}
function payPart(pid){
  const amt=prompt('Payment amount (GHS):');if(!amt)return;
  const fd=new FormData();fd.append('action','record_payment');fd.append('participant_id',pid);fd.append('amount',amt);
  fetch('ajax/events.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{if(d.success){renderDetail();loadEvents();}else alert(d.message);});
}
function rmPart(pid){
  if(!confirm('Remove this participant?'))return;
  const fd=new FormData();fd.append('action','remove_participant');fd.append('participant_id',pid);
  fetch('ajax/events.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{if(d.success){renderDetail();loadEvents();}});
}
loadEvents();
</script>
<?php finance_page_footer(); ?>
