<?php
/** Student health & infirmary — shared helpers + table self-heal. Sensitive data. */

if (!function_exists('health_ensure_tables')) {

    function health_ensure_tables(mysqli $conn): void
    {
        static $done = false;
        if ($done) return;
        $done = true;
        $conn->query("CREATE TABLE IF NOT EXISTS student_health (
            student_id INT PRIMARY KEY,
            blood_group VARCHAR(6) NULL,
            genotype VARCHAR(6) NULL,
            allergies TEXT NULL,
            conditions TEXT NULL,
            medications TEXT NULL,
            disabilities TEXT NULL,
            emergency_name VARCHAR(120) NULL,
            emergency_phone VARCHAR(30) NULL,
            emergency_relation VARCHAR(60) NULL,
            doctor_name VARCHAR(120) NULL,
            doctor_phone VARCHAR(30) NULL,
            insurance_no VARCHAR(60) NULL,
            notes TEXT NULL,
            updated_by INT NULL,
            updated_at DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci");
        $conn->query("CREATE TABLE IF NOT EXISTS infirmary_visits (
            id INT AUTO_INCREMENT PRIMARY KEY,
            student_id INT NOT NULL,
            visit_date DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
            complaint VARCHAR(255) NOT NULL,
            temperature VARCHAR(10) NULL,
            treatment TEXT NULL,
            medication_given VARCHAR(255) NULL,
            outcome ENUM('resolved','sent_home','referred','observation') NOT NULL DEFAULT 'resolved',
            attended_by VARCHAR(120) NULL,
            recorded_by INT NULL,
            created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
            KEY idx_student (student_id), KEY idx_date (visit_date)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci");
    }

    /** Roles allowed to view/edit health records. */
    function health_can_access(string $role): bool
    {
        return in_array($role, ['admin', 'headteacher', 'nurse'], true);
    }

    function health_profile(mysqli $conn, int $studentId): ?array
    {
        health_ensure_tables($conn);
        $stmt = $conn->prepare("SELECT * FROM student_health WHERE student_id=?");
        $stmt->bind_param('i', $studentId); $stmt->execute();
        $row = $stmt->get_result()->fetch_assoc(); $stmt->close();
        return $row ?: null;
    }

    function health_visits(mysqli $conn, int $studentId, int $limit = 100): array
    {
        health_ensure_tables($conn);
        $stmt = $conn->prepare("SELECT * FROM infirmary_visits WHERE student_id=? ORDER BY visit_date DESC, id DESC LIMIT ?");
        $stmt->bind_param('ii', $studentId, $limit); $stmt->execute();
        $rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC); $stmt->close();
        return $rows;
    }
}
