<?php
/** Student Leadership & Activities (student_activities add-on). */
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id'])) { header('Location: index.php'); exit; }

require_once 'config.php';
requireModule('student_activities');
require_once __DIR__ . '/includes/student_activities_lib.php';

$conn = getDBConnection();
sa_ensure_tables($conn);
$defaultYear = getSettingValue('academic_year') ?: date('Y');
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Leadership &amp; Activities — EduTrack</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
<div class="wrapper">
    <nav id="sidebar" class="sidebar"><?php echo buildSidebar(basename($_SERVER['PHP_SELF'])); ?></nav>
    <div class="main-content">
        <header class="header">
            <button class="btn-toggle" id="sidebarToggle"><i class="fas fa-bars"></i></button>
            <div class="header-right"><span class="text-muted"><i class="fas fa-user-circle me-2"></i><?php echo htmlspecialchars((string)($_SESSION['full_name'] ?? '')); ?></span></div>
        </header>
        <main class="content">
            <div class="content-header d-flex align-items-center gap-3">
                <div style="background:linear-gradient(135deg,#7c3aed,#5b21b6);border-radius:12px;width:44px;height:44px;display:flex;align-items:center;justify-content:center;">
                    <i class="fas fa-medal text-white fa-lg"></i>
                </div>
                <div>
                    <h2 class="mb-0">Leadership &amp; Activities</h2>
                    <p class="text-muted mb-0 small">Prefect roles and extracurricular history — kept on the permanent record.</p>
                </div>
            </div>

            <div class="card mb-3"><div class="card-body">
                <label class="form-label small">Find a student</label>
                <div class="input-group">
                    <input id="stuSearch" class="form-control" placeholder="Search by name, ID or class">
                    <button class="btn btn-outline-secondary" id="stuSearchBtn"><i class="fas fa-search"></i></button>
                </div>
                <select id="stuResults" class="form-select mt-2" size="4" style="display:none"></select>
            </div></div>

            <div id="profileArea" style="display:none">
                <div class="card mb-3"><div class="card-body d-flex align-items-center gap-3">
                    <i class="fas fa-user-graduate fa-2x text-secondary"></i>
                    <div><h5 class="mb-0" id="pName"></h5><span class="text-muted small" id="pMeta"></span></div>
                </div></div>

                <div class="row g-3">
                    <!-- Leadership -->
                    <div class="col-lg-6"><div class="card h-100"><div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <h5 class="mb-0"><i class="fas fa-crown text-warning me-2"></i>Leadership Roles</h5>
                            <button class="btn btn-sm btn-outline-primary" id="addLeadBtn" style="display:none"><i class="fas fa-plus"></i></button>
                        </div>
                        <div id="leadForm"></div>
                        <div id="leadList" class="mt-2"></div>
                    </div></div></div>

                    <!-- Activities -->
                    <div class="col-lg-6"><div class="card h-100"><div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <h5 class="mb-0"><i class="fas fa-futbol text-success me-2"></i>Extracurricular Activities</h5>
                            <button class="btn btn-sm btn-outline-primary" id="addActBtn" style="display:none"><i class="fas fa-plus"></i></button>
                        </div>
                        <div id="actForm"></div>
                        <div id="actList" class="mt-2"></div>
                    </div></div></div>
                </div>
            </div>
        </main>
    </div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="js/main.js"></script>
<script>
const DEF_YEAR = "<?php echo htmlspecialchars($defaultYear); ?>";
let CUR = null, CAN_EDIT = false;
function esc(s){const d=document.createElement('div');d.textContent=s==null?'':s;return d.innerHTML;}

document.getElementById('stuSearchBtn').addEventListener('click', doSearch);
document.getElementById('stuSearch').addEventListener('keyup', e=>{ if(e.key==='Enter') doSearch(); });
function doSearch(){
  const q=document.getElementById('stuSearch').value;
  fetch(`ajax/student_activities.php?action=search_students&q=${encodeURIComponent(q)}`).then(r=>r.json()).then(d=>{
    const sel=document.getElementById('stuResults');
    sel.style.display='';
    sel.innerHTML=d.data.map(s=>`<option value="${s.id}">${esc(s.label)}</option>`).join('') || '<option disabled>No matches</option>';
  });
}
document.getElementById('stuResults').addEventListener('change', function(){ if(this.value) loadStudent(this.value); });

function loadStudent(id){
  fetch(`ajax/student_activities.php?action=get&student_id=${id}`).then(r=>r.json()).then(d=>{
    if(!d.success){alert(d.message);return;}
    CUR=d.student.id; CAN_EDIT=d.can_edit;
    document.getElementById('profileArea').style.display='';
    document.getElementById('pName').textContent=d.student.first_name+' '+d.student.last_name;
    document.getElementById('pMeta').textContent=d.student.class+' · '+d.student.student_id;
    document.getElementById('addLeadBtn').style.display=CAN_EDIT?'':'none';
    document.getElementById('addActBtn').style.display=CAN_EDIT?'':'none';
    renderLead(d.leadership); renderAct(d.activities);
  });
}

function renderLead(rows){
  const el=document.getElementById('leadList');
  if(!rows.length){el.innerHTML='<p class="text-muted small">No leadership roles recorded.</p>';return;}
  el.innerHTML=rows.map(r=>`<div class="border rounded p-2 mb-2 d-flex justify-content-between">
    <div><b>${esc(r.role)}</b> <span class="badge bg-light text-dark">${esc(r.academic_year)}</span>
      ${r.term?('<span class="small text-muted">'+esc(r.term)+'</span>'):''}
      ${r.note?('<div class="small text-muted">'+esc(r.note)+'</div>'):''}</div>
    ${CAN_EDIT?`<button class="btn btn-sm btn-outline-danger py-0" onclick="delLead(${r.id})"><i class="fas fa-times"></i></button>`:''}
  </div>`).join('');
}
function renderAct(rows){
  const el=document.getElementById('actList');
  const icon={sport:'fa-futbol',club:'fa-users',society:'fa-people-group',other:'fa-star'};
  if(!rows.length){el.innerHTML='<p class="text-muted small">No activities recorded.</p>';return;}
  el.innerHTML=rows.map(r=>`<div class="border rounded p-2 mb-2 d-flex justify-content-between">
    <div><i class="fas ${icon[r.activity_type]||'fa-star'} me-1 text-muted"></i><b>${esc(r.activity_name)}</b>
      <span class="badge bg-light text-dark">${esc(r.academic_year)}</span>
      ${r.position?('<span class="small text-muted"> · '+esc(r.position)+'</span>'):''}
      ${r.achievement?('<div class="small text-success">🏆 '+esc(r.achievement)+'</div>'):''}</div>
    ${CAN_EDIT?`<button class="btn btn-sm btn-outline-danger py-0" onclick="delAct(${r.id})"><i class="fas fa-times"></i></button>`:''}
  </div>`).join('');
}

document.getElementById('addLeadBtn').addEventListener('click', ()=>{
  document.getElementById('leadForm').innerHTML=`<div class="border rounded p-2 mb-2"><div class="row g-1">
    <div class="col-7"><input id="l_role" class="form-control form-control-sm" placeholder="Role e.g. School Prefect"></div>
    <div class="col-5"><input id="l_year" class="form-control form-control-sm" value="${esc(DEF_YEAR)}" placeholder="Year"></div>
    <div class="col-6"><input id="l_term" class="form-control form-control-sm" placeholder="Term (optional)"></div>
    <div class="col-6"><input id="l_note" class="form-control form-control-sm" placeholder="Note (optional)"></div>
    <div class="col-12"><button class="btn btn-sm btn-primary w-100" onclick="saveLead()">Save role</button></div>
  </div></div>`;
});
function saveLead(){
  const fd=new FormData();fd.append('action','add_leadership');fd.append('student_id',CUR);
  fd.append('role',l_role.value);fd.append('academic_year',l_year.value);fd.append('term',l_term.value);fd.append('note',l_note.value);
  fetch('ajax/student_activities.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{if(d.success){document.getElementById('leadForm').innerHTML='';loadStudent(CUR);}else alert(d.message);});
}
function delLead(id){ if(!confirm('Remove this role?'))return;
  const fd=new FormData();fd.append('action','delete_leadership');fd.append('id',id);
  fetch('ajax/student_activities.php',{method:'POST',body:fd}).then(r=>r.json()).then(()=>loadStudent(CUR)); }

document.getElementById('addActBtn').addEventListener('click', ()=>{
  document.getElementById('actForm').innerHTML=`<div class="border rounded p-2 mb-2"><div class="row g-1">
    <div class="col-7"><input id="a_name" class="form-control form-control-sm" placeholder="Activity e.g. Football"></div>
    <div class="col-5"><select id="a_type" class="form-select form-select-sm">
      <option value="sport">Sport</option><option value="club">Club</option><option value="society">Society</option><option value="other">Other</option></select></div>
    <div class="col-5"><input id="a_year" class="form-control form-control-sm" value="${esc(DEF_YEAR)}" placeholder="Year"></div>
    <div class="col-7"><input id="a_pos" class="form-control form-control-sm" placeholder="Position (optional)"></div>
    <div class="col-12"><input id="a_ach" class="form-control form-control-sm" placeholder="Achievement (optional)"></div>
    <div class="col-12"><button class="btn btn-sm btn-primary w-100" onclick="saveAct()">Save activity</button></div>
  </div></div>`;
});
function saveAct(){
  const fd=new FormData();fd.append('action','add_activity');fd.append('student_id',CUR);
  fd.append('activity_name',a_name.value);fd.append('activity_type',a_type.value);fd.append('academic_year',a_year.value);
  fd.append('position',a_pos.value);fd.append('achievement',a_ach.value);
  fetch('ajax/student_activities.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{if(d.success){document.getElementById('actForm').innerHTML='';loadStudent(CUR);}else alert(d.message);});
}
function delAct(id){ if(!confirm('Remove this activity?'))return;
  const fd=new FormData();fd.append('action','delete_activity');fd.append('id',id);
  fetch('ajax/student_activities.php',{method:'POST',body:fd}).then(r=>r.json()).then(()=>loadStudent(CUR)); }
</script>
</body>
</html>
