<?php
/** Student health & infirmary — AJAX. Access: admin / headteacher / nurse. */
if (session_status() === PHP_SESSION_NONE) session_start();
header('Content-Type: application/json');

require_once __DIR__ . '/../config.php';
if (!isset($_SESSION['user_id'])) { http_response_code(401); echo json_encode(['success' => false, 'message' => 'Not signed in.']); exit; }
requireModule('health_records', true);
require_once __DIR__ . '/../includes/health_lib.php';

$role = $_SESSION['role'] ?? '';
if (!health_can_access($role)) {
    http_response_code(403);
    echo json_encode(['success' => false, 'message' => 'Health records are restricted to the school nurse and administration.']);
    exit;
}

$conn = getDBConnection();
health_ensure_tables($conn);
$uid = (int) $_SESSION['user_id'];
$actorName = (string) ($_SESSION['full_name'] ?? 'Staff');
$action = $_POST['action'] ?? $_GET['action'] ?? '';
function h_out($p){ echo json_encode($p); exit; }

switch ($action) {

    case 'search_students': {
        $q = trim($_GET['q'] ?? $_POST['q'] ?? '');
        $like = '%' . $q . '%';
        $stmt = $conn->prepare("SELECT id, student_id, first_name, last_name, class
            FROM students WHERE status='active' AND (CONCAT(first_name,' ',last_name) LIKE ? OR student_id LIKE ? OR class LIKE ?)
            ORDER BY first_name, last_name LIMIT 25");
        $stmt->bind_param('sss', $like, $like, $like); $stmt->execute();
        $res = $stmt->get_result(); $rows = [];
        while ($r = $res->fetch_assoc()) $rows[] = ['id' => $r['id'], 'label' => $r['first_name'] . ' ' . $r['last_name'] . ' — ' . $r['class'] . ' (' . $r['student_id'] . ')'];
        $stmt->close();
        h_out(['success' => true, 'data' => $rows]);
    }

    case 'get': {
        $sid = (int) ($_GET['student_id'] ?? $_POST['student_id'] ?? 0);
        if (!$sid) h_out(['success' => false, 'message' => 'No student selected.']);
        $s = $conn->prepare("SELECT id, student_id, first_name, last_name, class FROM students WHERE id=?");
        $s->bind_param('i', $sid); $s->execute();
        $stu = $s->get_result()->fetch_assoc(); $s->close();
        if (!$stu) h_out(['success' => false, 'message' => 'Student not found.']);
        h_out([
            'success' => true, 'student' => $stu,
            'profile' => health_profile($conn, $sid) ?: new stdClass(),
            'visits'  => health_visits($conn, $sid),
        ]);
    }

    case 'save_profile': {
        $sid = (int) ($_POST['student_id'] ?? 0);
        if (!$sid) h_out(['success' => false, 'message' => 'No student selected.']);
        $f = fn($k) => trim((string) ($_POST[$k] ?? '')) ?: null;
        $blood=$f('blood_group'); $geno=$f('genotype'); $allerg=$f('allergies'); $cond=$f('conditions');
        $meds=$f('medications'); $disab=$f('disabilities'); $en=$f('emergency_name'); $ep=$f('emergency_phone');
        $er=$f('emergency_relation'); $dn=$f('doctor_name'); $dp=$f('doctor_phone'); $ins=$f('insurance_no'); $notes=$f('notes');
        $stmt = $conn->prepare("INSERT INTO student_health
            (student_id, blood_group, genotype, allergies, conditions, medications, disabilities,
             emergency_name, emergency_phone, emergency_relation, doctor_name, doctor_phone, insurance_no, notes, updated_by)
            VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)
            ON DUPLICATE KEY UPDATE blood_group=VALUES(blood_group), genotype=VALUES(genotype),
             allergies=VALUES(allergies), conditions=VALUES(conditions), medications=VALUES(medications),
             disabilities=VALUES(disabilities), emergency_name=VALUES(emergency_name), emergency_phone=VALUES(emergency_phone),
             emergency_relation=VALUES(emergency_relation), doctor_name=VALUES(doctor_name), doctor_phone=VALUES(doctor_phone),
             insurance_no=VALUES(insurance_no), notes=VALUES(notes), updated_by=VALUES(updated_by)");
        $stmt->bind_param('isssssssssssssi', $sid, $blood, $geno, $allerg, $cond, $meds, $disab,
            $en, $ep, $er, $dn, $dp, $ins, $notes, $uid);
        $ok = $stmt->execute(); $err = $stmt->error; $stmt->close();
        h_out(['success' => (bool) $ok, 'message' => $ok ? 'Health profile saved.' : ('Error: ' . $err)]);
    }

    case 'add_visit': {
        $sid   = (int) ($_POST['student_id'] ?? 0);
        $comp  = trim($_POST['complaint'] ?? '');
        $temp  = trim($_POST['temperature'] ?? '') ?: null;
        $treat = trim($_POST['treatment'] ?? '') ?: null;
        $medg  = trim($_POST['medication_given'] ?? '') ?: null;
        $out   = $_POST['outcome'] ?? 'resolved';
        $vdate = trim($_POST['visit_date'] ?? '') ?: date('Y-m-d H:i:s');
        if (!in_array($out, ['resolved', 'sent_home', 'referred', 'observation'], true)) $out = 'resolved';
        if (!$sid || $comp === '') h_out(['success' => false, 'message' => 'Student and complaint are required.']);
        $stmt = $conn->prepare("INSERT INTO infirmary_visits
            (student_id, visit_date, complaint, temperature, treatment, medication_given, outcome, attended_by, recorded_by)
            VALUES (?,?,?,?,?,?,?,?,?)");
        $stmt->bind_param('isssssssi', $sid, $vdate, $comp, $temp, $treat, $medg, $out, $actorName, $uid);
        $stmt->execute(); $stmt->close();
        h_out(['success' => true, 'message' => 'Infirmary visit logged.']);
    }

    case 'delete_visit': {
        if (!in_array($role, ['admin', 'headteacher'], true)) h_out(['success' => false, 'message' => 'Only administration can delete visit records.']);
        $id = (int) ($_POST['id'] ?? 0);
        $conn->query("DELETE FROM infirmary_visits WHERE id=" . $id);
        h_out(['success' => true, 'message' => 'Visit removed.']);
    }

    default:
        h_out(['success' => false, 'message' => 'Unknown action.']);
}
