<?php
/**
 * File 2: ajax/save_vital_signs.php
 * Save patient vital signs
 */
session_start();
include '../layouts/dbconn.php';

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

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

$user_id = $_SESSION['user_id'];
$patient_id = $_POST['patient_id'] ?? 0;
$visit_id = $_POST['visit_id'] ?? null;

// Get vital signs data
$blood_pressure = $_POST['blood_pressure'] ?? null;
$systolic_bp = null;
$diastolic_bp = null;

// Parse blood pressure
if ($blood_pressure && preg_match('/^(\d+)\/(\d+)$/', $blood_pressure, $matches)) {
    $systolic_bp = intval($matches[1]);
    $diastolic_bp = intval($matches[2]);
}

$pulse_rate = $_POST['pulse_rate'] ?? null;
$temperature = $_POST['temperature'] ?? null;
$temperature_route = $_POST['temperature_route'] ?? 'ORAL';
$respiratory_rate = $_POST['respiratory_rate'] ?? null;
$oxygen_saturation = $_POST['oxygen_saturation'] ?? null;
$weight = $_POST['weight'] ?? null;
$height = $_POST['height'] ?? null;
$pain_scale = $_POST['pain_scale'] ?? null;
$consciousness_level = $_POST['consciousness_level'] ?? 'ALERT';
$notes = trim($_POST['notes'] ?? '');
$abnormal_findings = trim($_POST['abnormal_findings'] ?? '');

// Calculate BMI if weight and height provided
$bmi = null;
if ($weight && $height) {
    $height_m = $height / 100;
    $bmi = round($weight / ($height_m * $height_m), 2);
}

try {
    $conn->begin_transaction();
    
    $insert_sql = "INSERT INTO vital_signs (
        patient_id, visit_id, blood_pressure, systolic_bp, diastolic_bp,
        pulse_rate, temperature, temperature_route, respiratory_rate,
        oxygen_saturation, weight, height, bmi, pain_scale,
        consciousness_level, notes, abnormal_findings, recorded_by, recorded_date
    ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())";
    
    $stmt = $conn->prepare($insert_sql);
    $stmt->bind_param("iisiiddsiiddissssi",
        $patient_id, $visit_id, $blood_pressure, $systolic_bp, $diastolic_bp,
        $pulse_rate, $temperature, $temperature_route, $respiratory_rate,
        $oxygen_saturation, $weight, $height, $bmi, $pain_scale,
        $consciousness_level, $notes, $abnormal_findings, $user_id
    );
    
    if (!$stmt->execute()) {
        throw new Exception("Failed to save vital signs");
    }
    
    $vital_id = $conn->insert_id();
    
    // Update queue if patient has vitals_taken flag
    $update_queue = "UPDATE patient_queue 
                    SET vitals_taken = 1, vital_signs_id = ?
                    WHERE patient_id = ? AND queue_status IN ('WAITING', 'IN_SERVICE')
                    AND DATE(queue_entry_time) = CURDATE()";
    $stmt = $conn->prepare($update_queue);
    $stmt->bind_param("ii", $vital_id, $patient_id);
    $stmt->execute();
    
    // Log activity
    $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, ip_address, logged_at)
                    VALUES (?, 'CREATE', 'VITAL_SIGNS', ?, 'VITAL_SIGNS', ?, NOW())";
    $ip_address = $_SERVER['REMOTE_ADDR'];
    $stmt = $conn->prepare($activity_sql);
    $stmt->bind_param("iis", $user_id, $vital_id, $ip_address);
    $stmt->execute();
    
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Vital signs recorded successfully',
        'vital_id' => $vital_id
    ]);
    
} catch (Exception $e) {
    $conn->rollback();
    echo json_encode([
        'success' => false,
        'message' => 'Failed to save vital signs: ' . $e->getMessage()
    ]);
}
?>