<?php
/** Student Health & Medical Records (health_records add-on). Access: admin/headteacher/nurse. */
if (session_status() === PHP_SESSION_NONE) session_start();
if (!isset($_SESSION['user_id'])) { header('Location: ../index.php'); exit; }

require_once '../config.php';
requireModule('health_records');
require_once __DIR__ . '/../includes/health_lib.php';

$role = $_SESSION['role'] ?? '';
if (!health_can_access($role)) { header('Location: ../dashboard.php?error=no_access'); exit; }

$conn = getDBConnection();
health_ensure_tables($conn);
$base = defined('BASE_URL') ? rtrim(BASE_URL, '/') : '';
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Health Records — 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('health/index.php'); ?></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,#e11d48,#9f1239);border-radius:12px;width:44px;height:44px;display:flex;align-items:center;justify-content:center;">
                    <i class="fas fa-heart-pulse text-white fa-lg"></i>
                </div>
                <div>
                    <h2 class="mb-0">Health &amp; Medical Records</h2>
                    <p class="text-muted mb-0 small">Confidential — allergies, conditions, emergency contacts &amp; infirmary log.</p>
                </div>
            </div>

            <div class="alert alert-warning small"><i class="fas fa-lock me-1"></i>
                This information is confidential and visible only to the school nurse and administration.</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="area" 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">
                    <!-- Medical profile -->
                    <div class="col-lg-6"><div class="card h-100"><div class="card-body">
                        <h5 class="mb-3"><i class="fas fa-notes-medical text-danger me-2"></i>Medical Profile</h5>
                        <form id="profileForm">
                            <div class="row g-2">
                                <div class="col-6"><label class="form-label small">Blood group</label><input class="form-control form-control-sm" name="blood_group"></div>
                                <div class="col-6"><label class="form-label small">Genotype</label><input class="form-control form-control-sm" name="genotype"></div>
                                <div class="col-12"><label class="form-label small">Allergies</label><textarea class="form-control form-control-sm" name="allergies" rows="2"></textarea></div>
                                <div class="col-12"><label class="form-label small">Chronic conditions</label><textarea class="form-control form-control-sm" name="conditions" rows="2"></textarea></div>
                                <div class="col-12"><label class="form-label small">Regular medications</label><textarea class="form-control form-control-sm" name="medications" rows="2"></textarea></div>
                                <div class="col-12"><label class="form-label small">Disabilities / special needs</label><input class="form-control form-control-sm" name="disabilities"></div>
                                <div class="col-6"><label class="form-label small">Emergency contact</label><input class="form-control form-control-sm" name="emergency_name"></div>
                                <div class="col-6"><label class="form-label small">Emergency phone</label><input class="form-control form-control-sm" name="emergency_phone"></div>
                                <div class="col-6"><label class="form-label small">Relationship</label><input class="form-control form-control-sm" name="emergency_relation"></div>
                                <div class="col-6"><label class="form-label small">NHIS / insurance no.</label><input class="form-control form-control-sm" name="insurance_no"></div>
                                <div class="col-6"><label class="form-label small">Family doctor</label><input class="form-control form-control-sm" name="doctor_name"></div>
                                <div class="col-6"><label class="form-label small">Doctor phone</label><input class="form-control form-control-sm" name="doctor_phone"></div>
                                <div class="col-12"><label class="form-label small">Other notes</label><textarea class="form-control form-control-sm" name="notes" rows="2"></textarea></div>
                            </div>
                            <button type="submit" class="btn btn-danger btn-sm mt-2"><i class="fas fa-save me-1"></i>Save Profile</button>
                            <span id="profMsg" class="small ms-2"></span>
                        </form>
                    </div></div></div>

                    <!-- Infirmary log -->
                    <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-briefcase-medical text-danger me-2"></i>Infirmary Visits</h5>
                            <button class="btn btn-sm btn-outline-danger" id="addVisitBtn"><i class="fas fa-plus"></i> Log visit</button>
                        </div>
                        <div id="visitForm"></div>
                        <div id="visitList"></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 CAN_DELETE = <?php echo in_array($role, ['admin','headteacher'], true) ? 'true' : 'false'; ?>;
let CUR=null;
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(){
  fetch(`../ajax/health_records.php?action=search_students&q=${encodeURIComponent(document.getElementById('stuSearch').value)}`)
    .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/health_records.php?action=get&student_id=${id}`).then(r=>r.json()).then(d=>{
    if(!d.success){alert(d.message);return;}
    CUR=d.student.id;
    document.getElementById('area').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;
    const p=d.profile||{};
    const form=document.getElementById('profileForm');
    ['blood_group','genotype','allergies','conditions','medications','disabilities','emergency_name','emergency_phone','emergency_relation','insurance_no','doctor_name','doctor_phone','notes'].forEach(k=>{ if(form[k]) form[k].value=p[k]||''; });
    renderVisits(d.visits);
  });
}
function renderVisits(rows){
  const el=document.getElementById('visitList');
  const oc={resolved:'success',sent_home:'warning',referred:'danger',observation:'info'};
  if(!rows.length){el.innerHTML='<p class="text-muted small">No infirmary visits recorded.</p>';return;}
  el.innerHTML=rows.map(v=>`<div class="border rounded p-2 mb-2">
    <div class="d-flex justify-content-between"><b>${esc(v.complaint)}</b>
      <span class="badge bg-${oc[v.outcome]||'secondary'}">${esc(v.outcome.replace('_',' '))}</span></div>
    <div class="small text-muted">${esc(v.visit_date)} ${v.temperature?('· '+esc(v.temperature)+'°'):''} ${v.attended_by?('· '+esc(v.attended_by)):''}</div>
    ${v.treatment?('<div class="small">Treatment: '+esc(v.treatment)+'</div>'):''}
    ${v.medication_given?('<div class="small">Meds: '+esc(v.medication_given)+'</div>'):''}
    ${CAN_DELETE?`<button class="btn btn-sm btn-outline-danger py-0 mt-1" onclick="delVisit(${v.id})"><i class="fas fa-times"></i></button>`:''}
  </div>`).join('');
}

document.getElementById('profileForm').addEventListener('submit',function(e){
  e.preventDefault();
  const fd=new FormData(this);fd.append('action','save_profile');fd.append('student_id',CUR);
  fetch('../ajax/health_records.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{
    document.getElementById('profMsg').innerHTML=d.success?'<span class="text-success">Saved.</span>':'<span class="text-danger">'+esc(d.message)+'</span>';
  });
});

document.getElementById('addVisitBtn').addEventListener('click',()=>{
  document.getElementById('visitForm').innerHTML=`<div class="border rounded p-2 mb-2"><div class="row g-1">
    <div class="col-8"><input id="v_comp" class="form-control form-control-sm" placeholder="Complaint / symptoms"></div>
    <div class="col-4"><input id="v_temp" class="form-control form-control-sm" placeholder="Temp °C"></div>
    <div class="col-12"><input id="v_treat" class="form-control form-control-sm" placeholder="Treatment given"></div>
    <div class="col-7"><input id="v_med" class="form-control form-control-sm" placeholder="Medication given"></div>
    <div class="col-5"><select id="v_out" class="form-select form-select-sm">
      <option value="resolved">Resolved</option><option value="observation">Observation</option>
      <option value="sent_home">Sent home</option><option value="referred">Referred</option></select></div>
    <div class="col-12"><button class="btn btn-sm btn-danger w-100" onclick="saveVisit()">Save visit</button></div>
  </div></div>`;
});
function saveVisit(){
  const fd=new FormData();fd.append('action','add_visit');fd.append('student_id',CUR);
  fd.append('complaint',v_comp.value);fd.append('temperature',v_temp.value);fd.append('treatment',v_treat.value);
  fd.append('medication_given',v_med.value);fd.append('outcome',v_out.value);
  fetch('../ajax/health_records.php',{method:'POST',body:fd}).then(r=>r.json()).then(d=>{if(d.success){document.getElementById('visitForm').innerHTML='';loadStudent(CUR);}else alert(d.message);});
}
function delVisit(id){ if(!confirm('Delete this visit record?'))return;
  const fd=new FormData();fd.append('action','delete_visit');fd.append('id',id);
  fetch('../ajax/health_records.php',{method:'POST',body:fd}).then(r=>r.json()).then(()=>loadStudent(CUR)); }
</script>
</body>
</html>
