<?php
header('Content-Type: application/json');
session_start();
ob_start();

include '../layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Not authenticated']);
    exit();
}

$user_id   = $_SESSION['user_id'];
$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' => 'Unauthorized access']);
    exit();
}

// ── Inputs ────────────────────────────────────────────────────────────────────
$patient_id    = isset($_POST['patient_id'])    ? (int)$_POST['patient_id']    : 0;
$visit_id      = isset($_POST['visit_id'])      ? (int)$_POST['visit_id']      : 0;
$queue_id      = isset($_POST['queue_id'])      ? (int)$_POST['queue_id']      : 0;
$vital_sign_id = isset($_POST['vital_sign_id']) ? (int)$_POST['vital_sign_id'] : 0;

// Vital signs
$blood_pressure      = trim($_POST['blood_pressure']      ?? '');
$pulse_rate          = ($_POST['pulse_rate']      ?? '') !== '' ? (int)$_POST['pulse_rate']           : null;
$temperature         = ($_POST['temperature']     ?? '') !== '' ? (float)$_POST['temperature']        : null;
$temperature_route   = trim($_POST['temperature_route']   ?? 'ORAL');
$respiratory_rate    = ($_POST['respiratory_rate']?? '') !== '' ? (int)$_POST['respiratory_rate']     : null;
$oxygen_saturation   = ($_POST['oxygen_saturation']??'')!== '' ? (float)$_POST['oxygen_saturation']  : null;
$weight              = ($_POST['weight']          ?? '') !== '' ? (float)$_POST['weight']             : null;
$height              = ($_POST['height']          ?? '') !== '' ? (float)$_POST['height']             : null;
$pain_scale          = isset($_POST['pain_scale'])        ? (int)$_POST['pain_scale']                 : 0;
$consciousness_level = trim($_POST['consciousness_level'] ?? 'ALERT');
$notes               = trim($_POST['notes']               ?? '');
$abnormal_findings   = trim($_POST['abnormal_findings']   ?? '');
$abnormal_detected   = (($_POST['abnormal_vitals_detected'] ?? '0') === '1');

// Triage / routing
$triage_priority = trim($_POST['triage_priority'] ?? 'NORMAL');
$triage_notes    = trim($_POST['triage_notes']    ?? '');

if (!$patient_id) {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Patient ID is required']);
    exit();
}

if (!$blood_pressure && $pulse_rate === null && $temperature === null) {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Enter at least blood pressure, pulse rate, or temperature']);
    exit();
}

if ($abnormal_detected && $abnormal_findings === '') {
    ob_end_clean();
    echo json_encode(['success' => false, 'message' => 'Abnormal vitals detected — please document findings in "Abnormal Findings / Notes for Doctor"']);
    exit();
}

// ── Validate visit_id exists ──────────────────────────────────────────────────
$valid_visit_id = null;
if ($visit_id > 0) {
    $chk = $conn->prepare("SELECT visit_id FROM patient_visits WHERE visit_id = ? LIMIT 1");
    $chk->bind_param("i", $visit_id);
    $chk->execute();
    if ($chk->get_result()->num_rows > 0) {
        $valid_visit_id = $visit_id;
    }
    $chk->close();
}

// ── Valid triage priority? ────────────────────────────────────────────────────
$valid_priorities = ['NORMAL', 'URGENT', 'EMERGENCY'];
$triage_priority  = in_array($triage_priority, $valid_priorities) ? $triage_priority : 'NORMAL';

try {
    $conn->begin_transaction();

    // ════════════════════════════════════════════════════════════
    //  EDIT MODE — update existing vital signs record
    // ════════════════════════════════════════════════════════════
    if ($vital_sign_id > 0) {

        // Fetch existing for audit
        $stmt_get = $conn->prepare(
            "SELECT blood_pressure, pulse_rate, temperature, temperature_route,
                    respiratory_rate, oxygen_saturation, weight, height,
                    pain_scale, consciousness_level, notes, abnormal_findings
             FROM vital_signs WHERE vital_id = ? LIMIT 1"
        );
        $stmt_get->bind_param("i", $vital_sign_id);
        $stmt_get->execute();
        $existing = $stmt_get->get_result()->fetch_assoc();
        $stmt_get->close();

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

        // UPDATE
        $stmt_up = $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         = ?,
                 recorded_date       = NOW()
             WHERE vital_id = ?"
        );
        // 14 params: s i d s i d d d i s s s i i
        $stmt_up->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_sign_id
        );

        if (!$stmt_up->execute()) {
            throw new Exception("Failed to update vitals: " . $stmt_up->error);
        }
        $stmt_up->close();

        // Update triage priority on queue — also set updated_by so the
        // after_queue_update trigger can correctly resolve performed_by_name
        if ($queue_id > 0) {
            $stmt_q = $conn->prepare(
                "UPDATE patient_queue
                 SET triage_priority    = ?,
                     priority           = ?,
                     triage_notes       = ?,
                     triage_assessed_by = ?,
                     triage_assessed_at = NOW(),
                     updated_by         = ?
                 WHERE queue_id = ?"
            );
            $stmt_q->bind_param("sssiii", $triage_priority, $triage_priority, $triage_notes, $user_id, $user_id, $queue_id);
            $stmt_q->execute();
            $stmt_q->close();
        }

        // Update visit vital_signs JSON snapshot
        if ($valid_visit_id) {
            $vitals_json = json_encode([
                'blood_pressure'    => $blood_pressure,
                'pulse_rate'        => $pulse_rate,
                'temperature'       => $temperature,
                'oxygen_saturation' => $oxygen_saturation,
                'weight'            => $weight,
                'height'            => $height,
                'recorded_at'       => date('Y-m-d H:i:s'),
            ]);
            $stmt_v = $conn->prepare("UPDATE patient_visits SET vital_signs = ? WHERE visit_id = ?");
            $stmt_v->bind_param("si", $vitals_json, $valid_visit_id);
            $stmt_v->execute();
            $stmt_v->close();
        }

        // Activity log (non-fatal)
        try {
            $stmt_log = $conn->prepare(
                "INSERT INTO activity_log (user_id, action, module, record_id, record_type, old_values, new_values, ip_address, user_agent, session_id)
                 VALUES (?, 'UPDATE', 'NURSING', ?, 'VITAL_SIGNS', ?, ?, ?, ?, ?)"
            );
            if ($stmt_log) {
                $old_j = json_encode($existing);
                $new_j = json_encode([
                    'blood_pressure'    => $blood_pressure,
                    'pulse_rate'        => $pulse_rate,
                    'temperature'       => $temperature,
                    'temperature_route' => $temperature_route,
                    'oxygen_saturation' => $oxygen_saturation,
                    'weight'            => $weight,
                ]);
                $ip  = $_SERVER['REMOTE_ADDR']     ?? 'UNKNOWN';
                $ua  = $_SERVER['HTTP_USER_AGENT'] ?? '';
                $sid = session_id();
                $stmt_log->bind_param("iiisssss", $user_id, $vital_sign_id, $old_j, $new_j, $ip, $ua, $sid);
                $stmt_log->execute();
                $stmt_log->close();
            }
        } catch (Exception $e) {
            error_log("Vitals edit activity_log error: " . $e->getMessage());
        }

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

    // ════════════════════════════════════════════════════════════
    //  NEW MODE — insert fresh vital signs record
    // ════════════════════════════════════════════════════════════

    $stmt = $conn->prepare(
        "INSERT INTO vital_signs (
            patient_id, visit_id,
            blood_pressure, pulse_rate, temperature, temperature_route,
            respiratory_rate, oxygen_saturation,
            weight, height,
            pain_scale, consciousness_level,
            notes, abnormal_findings,
            recorded_by, location, created_at
         ) VALUES (
            ?, ?,
            ?, ?, ?, ?,
            ?, ?,
            ?, ?,
            ?, ?,
            ?, ?,
            ?, 'Triage Station', NOW()
         )"
    );

    // 15 params: i i s i d s i d d d i s s s i
    $stmt->bind_param(
        "iisidsidddisssi",
        $patient_id,          // 1  i
        $valid_visit_id,      // 2  i
        $blood_pressure,      // 3  s
        $pulse_rate,          // 4  i
        $temperature,         // 5  d
        $temperature_route,   // 6  s
        $respiratory_rate,    // 7  i
        $oxygen_saturation,   // 8  d
        $weight,              // 9  d
        $height,              // 10 d
        $pain_scale,          // 11 i
        $consciousness_level, // 12 s
        $notes,               // 13 s
        $abnormal_findings,   // 14 s
        $user_id              // 15 i
    );

    if (!$stmt->execute()) {
        throw new Exception("Failed to record vitals: " . $stmt->error);
    }
    $vital_id = $conn->insert_id;
    $stmt->close();

    // ── Update queue: mark vitals taken + store vital_signs_id + triage priority
    // updated_by is set so the after_queue_update trigger resolves the nurse name
    if ($queue_id > 0) {
        $stmt_q = $conn->prepare(
            "UPDATE patient_queue
             SET vitals_taken       = 1,
                 vital_signs_id     = ?,
                 triage_priority    = ?,
                 priority           = ?,
                 triage_notes       = ?,
                 triage_assessed_by = ?,
                 triage_assessed_at = NOW(),
                 updated_by         = ?
             WHERE queue_id = ?"
        );
        // i s s s i i i
        $stmt_q->bind_param("isssiii", $vital_id, $triage_priority, $triage_priority, $triage_notes, $user_id, $user_id, $queue_id);
        $stmt_q->execute();
        $stmt_q->close();
    }

    // ── Update visit vital_signs JSON snapshot ────────────────────────────────
    if ($valid_visit_id) {
        $vitals_json = json_encode([
            'blood_pressure'    => $blood_pressure,
            'pulse_rate'        => $pulse_rate,
            'temperature'       => $temperature,
            'oxygen_saturation' => $oxygen_saturation,
            'weight'            => $weight,
            'height'            => $height,
            'recorded_at'       => date('Y-m-d H:i:s'),
        ]);
        $stmt_v = $conn->prepare("UPDATE patient_visits SET vital_signs = ? WHERE visit_id = ?");
        $stmt_v->bind_param("si", $vitals_json, $valid_visit_id);
        $stmt_v->execute();
        $stmt_v->close();
    }

    // ── Activity log (non-fatal) ──────────────────────────────────────────────
    try {
        $stmt_log = $conn->prepare(
            "INSERT INTO activity_log (user_id, action, module, record_id, record_type, old_values, new_values, ip_address, user_agent, session_id)
             VALUES (?, 'CREATE', 'NURSING', ?, 'VITAL_SIGNS', NULL, ?, ?, ?, ?)"
        );
        if ($stmt_log) {
            $new_j = json_encode([
                'patient_id'    => $patient_id,
                'visit_id'      => $valid_visit_id,
                'blood_pressure'=> $blood_pressure,
                'pulse_rate'    => $pulse_rate,
                'temperature'   => $temperature,
                'oxygen_saturation' => $oxygen_saturation,
                'weight'        => $weight,
            ]);
            $ip  = $_SERVER['REMOTE_ADDR']     ?? 'UNKNOWN';
            $ua  = $_SERVER['HTTP_USER_AGENT'] ?? '';
            $sid = session_id();
            $stmt_log->bind_param("iissss", $user_id, $vital_id, $new_j, $ip, $ua, $sid);
            $stmt_log->execute();
            $stmt_log->close();
        }
    } catch (Exception $e) {
        error_log("Vitals create activity_log error: " . $e->getMessage());
    }

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

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