<?php
ob_start();
session_start();
include '../layouts/dbconn.php';

header('Content-Type: application/json');

// Auth check
if (!isset($_SESSION['user_id'])) {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Unauthorised.']);
    exit();
}

$role_code = $_SESSION['role_code'] ?? '';
if (!in_array($role_code, ['HEAD_NURSE','ENT_NURSE','SUPER_ADMIN','HOSPITAL_ADMIN'])) {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Access denied.']);
    exit();
}

$user_id = (int)$_SESSION['user_id'];

// ── Required fields ───────────────────────────────────────────
$vital_id   = (int)($_POST['vital_id']        ?? 0);
$patient_id = (int)($_POST['patient_id']      ?? 0);
$queue_id   = (int)($_POST['queue_id']        ?? 0);
$visit_id   = (int)($_POST['visit_id']        ?? 0) ?: null;
$priority   = trim($_POST['triage_priority']  ?? '');
$edit_reason= trim($_POST['edit_reason']      ?? '');
$triage_notes = trim($_POST['triage_notes']   ?? '');

if (!$vital_id || !$patient_id) {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Missing vital_id or patient_id.']);
    exit();
}

// ── Sanitise vitals ───────────────────────────────────────────
$blood_pressure     = trim($_POST['blood_pressure']      ?? '') ?: null;
$pulse_rate         = is_numeric($_POST['pulse_rate']    ?? '') ? (int)$_POST['pulse_rate']         : null;
$temperature        = is_numeric($_POST['temperature']   ?? '') ? (float)$_POST['temperature']      : null;
$temperature_route  = trim($_POST['temperature_route']   ?? '') ?: 'ORAL';
$respiratory_rate   = is_numeric($_POST['respiratory_rate'] ?? '') ? (int)$_POST['respiratory_rate']: null;
$oxygen_saturation  = is_numeric($_POST['oxygen_saturation'] ?? '') ? (float)$_POST['oxygen_saturation'] : null;
$weight             = is_numeric($_POST['weight']        ?? '') ? (float)$_POST['weight']           : null;
$height             = is_numeric($_POST['height']        ?? '') ? (float)$_POST['height']           : null;
$pain_scale         = isset($_POST['pain_scale'])        ? (int)$_POST['pain_scale']                : null;
$consciousness_level= trim($_POST['consciousness_level'] ?? 'ALERT');
$notes              = trim($_POST['notes']               ?? '') ?: null;
$abnormal_findings  = trim($_POST['abnormal_findings']   ?? '') ?: null;

// Validate consciousness ENUM
$valid_cons = ['ALERT','VERBAL','PAIN','UNRESPONSIVE'];
if (!in_array($consciousness_level, $valid_cons)) $consciousness_level = 'ALERT';

// Validate priority ENUM
$valid_prio = ['NORMAL','URGENT','EMERGENCY'];
if (!in_array($priority, $valid_prio)) {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Invalid priority value.']);
    exit();
}

try {
    $conn->begin_transaction();

    // ── 1. Fetch old values for the activity log ──────────────
    $st = $conn->prepare("SELECT * FROM vital_signs WHERE vital_id = ?");
    $st->bind_param("i", $vital_id);
    $st->execute();
    $old = $st->get_result()->fetch_assoc();
    $st->close();

    if (!$old) {
        $conn->rollback();
        ob_end_clean();
        echo json_encode(['success' => false, 'message' => 'Vital signs record not found.']);
        exit();
    }

    // ── 2. UPDATE vital_signs ─────────────────────────────────
    // BMI and systolic/diastolic are handled by DB triggers on UPDATE
    $st = $conn->prepare("
        UPDATE vital_signs SET
            blood_pressure      = ?,
            pulse_rate          = ?,
            temperature         = ?,
            temperature_route   = ?,
            respiratory_rate    = ?,
            oxygen_saturation   = ?,
            weight              = ?,
            height              = ?,
            pain_scale          = ?,
            consciousness_level = ?,
            notes               = ?,
            abnormal_findings   = ?,
            recorded_by         = ?
        WHERE vital_id = ?");
    // Type string breakdown (14 params):
    // s  blood_pressure      (varchar)
    // i  pulse_rate          (int)
    // d  temperature         (decimal)
    // s  temperature_route   (varchar)
    // i  respiratory_rate    (int)
    // d  oxygen_saturation   (decimal)
    // d  weight              (decimal)
    // d  height              (decimal)
    // i  pain_scale          (int)
    // s  consciousness_level (enum — must be s, not i)
    // s  notes               (text)
    // s  abnormal_findings   (text)
    // i  user_id             (int)
    // i  vital_id            (int)
    $st->bind_param(
        "sidsidddisssii",
        $blood_pressure,
        $pulse_rate,
        $temperature,
        $temperature_route,
        $respiratory_rate,
        $oxygen_saturation,
        $weight,
        $height,
        $pain_scale,
        $consciousness_level,
        $notes,
        $abnormal_findings,
        $user_id,
        $vital_id
    );
    $st->execute();
    $st->close();

    // ── 3. UPDATE patient_queue priority if queue_id given ────
    if ($queue_id) {
        $now = date('Y-m-d H:i:s');
        $st  = $conn->prepare("
            UPDATE patient_queue SET
                triage_priority     = ?,
                triage_notes        = ?,
                triage_assessed_by  = ?,
                triage_assessed_at  = ?,
                updated_by          = ?
            WHERE queue_id = ?");
        $st->bind_param("ssssii",
            $priority,
            $triage_notes,
            $user_id,
            $now,
            $user_id,
            $queue_id
        );
        $st->execute();
        $st->close();
    }

    // ── 4. Log to activity_log ────────────────────────────────
    $old_json = json_encode([
        'blood_pressure'    => $old['blood_pressure'],
        'pulse_rate'        => $old['pulse_rate'],
        'temperature'       => $old['temperature'],
        'respiratory_rate'  => $old['respiratory_rate'],
        'oxygen_saturation' => $old['oxygen_saturation'],
        'weight'            => $old['weight'],
        'height'            => $old['height'],
        'pain_scale'        => $old['pain_scale'],
        'consciousness_level'=> $old['consciousness_level'],
        'notes'             => $old['notes'],
        'abnormal_findings' => $old['abnormal_findings'],
    ]);
    $new_json = json_encode([
        'blood_pressure'    => $blood_pressure,
        'pulse_rate'        => $pulse_rate,
        'temperature'       => $temperature,
        'respiratory_rate'  => $respiratory_rate,
        'oxygen_saturation' => $oxygen_saturation,
        'weight'            => $weight,
        'height'            => $height,
        'pain_scale'        => $pain_scale,
        'consciousness_level'=> $consciousness_level,
        'notes'             => $notes,
        'abnormal_findings' => $abnormal_findings,
        'edit_reason'       => $edit_reason,
    ]);

    $action = 'UPDATE';
    $module = 'VITALS';
    $rec_type = 'vital_signs';
    $st = $conn->prepare("
        INSERT INTO activity_log
            (user_id, action, module, record_id, record_type, old_values, new_values, ip_address)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
    $ip = $_SERVER['REMOTE_ADDR'] ?? '';
    $st->bind_param("isisssss",
        $user_id, $action, $module,
        $vital_id, $rec_type,
        $old_json, $new_json, $ip
    );
    $st->execute();
    $st->close();

    $conn->commit();
    ob_end_clean();
    echo json_encode(['success' => true, 'message' => 'Vital signs updated successfully.']);

} catch (Exception $e) {
    $conn->rollback();
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
}