<?php
header('Content-Type: application/json');
session_start();
include 'layouts/dbconn.php';

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

$user_id = $_SESSION['user_id'];
$role_code = $_SESSION['role_code'];

// Verify nurse access
if ($role_code !== 'HEAD_NURSE' && $role_code !== 'ENT_NURSE') {
    echo json_encode(['success' => false, 'message' => 'Unauthorized access']);
    exit();
}

// Get form data
$patient_id = $_POST['patient_id'] ?? null;
$visit_id = $_POST['visit_id'] ?? null;
$queue_id = $_POST['queue_id'] ?? null;

// Vital signs
$blood_pressure = $_POST['blood_pressure'] ?? null;
$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 = $_POST['notes'] ?? null;
$abnormal_findings = $_POST['abnormal_findings'] ?? null;

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

try {
    $conn->begin_transaction();
    
    // Validate visit_id if provided - check if it exists in patient_visits
    $valid_visit_id = null;
    if ($visit_id && $visit_id != '') {
        $visit_id_int = intval($visit_id);
        if ($visit_id_int > 0) {
            $check_visit_sql = "SELECT visit_id FROM patient_visits WHERE visit_id = ?";
            $stmt_check = $conn->prepare($check_visit_sql);
            $stmt_check->bind_param("i", $visit_id_int);
            $stmt_check->execute();
            $visit_result = $stmt_check->get_result();
            
            if ($visit_result->num_rows > 0) {
                // Visit ID exists, use it
                $valid_visit_id = $visit_id_int;
            }
            $stmt_check->close();
        }
    }
    
    // Insert vital signs - handle NULL visit_id properly
    $insert_sql = "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())";
    
    $stmt = $conn->prepare($insert_sql);
    
    // Bind parameters - visit_id can be NULL
    // For NULL values in bind_param with 'i', we need to pass the actual NULL
    $stmt->bind_param(
        "iisdsiiddissssi",
        $patient_id,
        $valid_visit_id,  // Will be NULL if visit doesn't exist or not provided
        $blood_pressure,
        $pulse_rate,
        $temperature,
        $temperature_route,
        $respiratory_rate,
        $oxygen_saturation,
        $weight,
        $height,
        $pain_scale,
        $consciousness_level,
        $notes,
        $abnormal_findings,
        $user_id
    );
    
    if (!$stmt->execute()) {
        throw new Exception("Failed to record vitals: " . $stmt->error);
    }
    
    $vital_id = $conn->insert_id;
    $stmt->close();
    
    // Update queue to mark vitals as taken
    if ($queue_id) {
        $update_queue_sql = "UPDATE patient_queue 
                            SET vitals_taken = 1, 
                                vital_signs_id = ?,
                                updated_by = ?
                            WHERE queue_id = ?";
        $stmt_queue = $conn->prepare($update_queue_sql);
        $stmt_queue->bind_param("iii", $vital_id, $user_id, $queue_id);
        $stmt_queue->execute();
        $stmt_queue->close();
    }
    
    // Update visit with vital signs JSON only if visit_id exists
    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')
        ]);
        
        $update_visit_sql = "UPDATE patient_visits 
                            SET vital_signs = ?
                            WHERE visit_id = ?";
        $stmt_visit = $conn->prepare($update_visit_sql);
        $stmt_visit->bind_param("si", $vitals_json, $valid_visit_id);
        $stmt_visit->execute();
        $stmt_visit->close();
    }
    
    // Log activity
    $activity_sql = "INSERT INTO activity_log (user_id, action, module, record_id, record_type, old_values, new_values, ip_address, user_agent, session_id) 
                     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    $stmt_log = $conn->prepare($activity_sql);
    if (!$stmt_log) {
        throw new Exception("Prepare failed: " . $conn->error);
    }
    
    $action = 'CREATE';
    $module = 'NURSING';
    $record_type = 'VITAL_SIGNS';
    $old_values = null; // No old values for new record
    $new_values = json_encode([
        'patient_id' => $patient_id,
        'visit_id' => $valid_visit_id,
        'queue_id' => $queue_id,
        'blood_pressure' => $blood_pressure,
        'pulse_rate' => $pulse_rate,
        'temperature' => $temperature,
        'oxygen_saturation' => $oxygen_saturation,
        'weight' => $weight,
        'height' => $height
    ]);
    $ip_address = $_SERVER['REMOTE_ADDR'] ?? 'UNKNOWN';
    $user_agent = $_SERVER['HTTP_USER_AGENT'] ?? '';
    $session_id = session_id();
    
    $stmt_log->bind_param("ississssss", 
        $user_id, 
        $action, 
        $module, 
        $vital_id, 
        $record_type,
        $old_values,
        $new_values,
        $ip_address,
        $user_agent,
        $session_id
    );
    $stmt_log->execute();
    $stmt_log->close();
    
    $conn->commit();
    
    echo json_encode([
        'success' => true,
        'message' => 'Vital signs recorded successfully',
        'vital_id' => $vital_id,
        'queue_id' => $queue_id,
        'patient_id' => $patient_id,
        'requires_routing' => true // Flag to show routing modal
    ]);
    
} catch (Exception $e) {
    $conn->rollback();
    error_log("Vital signs error: " . $e->getMessage());
    echo json_encode([
        'success' => false,
        'message' => $e->getMessage()
    ]);
}

if (isset($conn)) {
    $conn->close();
}
?>
