<?php
session_start();
if (!isset($_SESSION['nurse_id'])) {
    header("Location: login.php");
    exit();
}
include '../include/config.php';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $patient_id = $_POST['patient_id'];
    $nurse_id = $_SESSION['nurse_id'];
    
    // Get doctor_id from nurse_patient_assignments
    $doc_query = $conn->query("SELECT doctor_id FROM nurse_patient_assignments WHERE patient_id = $patient_id AND nurse_id = $nurse_id LIMIT 1");
    $doc_data = $doc_query->fetch_assoc();
    $doctor_id = $doc_data['doctor_id'] ?? null;
    
    $blood_pressure = $_POST['blood_pressure'] ?? null;
    $heart_rate = $_POST['heart_rate'] ?? null;
    $temperature = $_POST['temperature'] ?? null;
    $oxygen_saturation = $_POST['oxygen_saturation'] ?? null;
    $weight = $_POST['weight'] ?? null;
    $height = $_POST['height'] ?? null;
    $notes = $_POST['notes'] ?? null;
    
    // Calculate BMI if weight and height provided
    $bmi = null;
    if ($weight && $height && $height > 0) {
        $height_m = $height / 100;
        $bmi = $weight / ($height_m * $height_m);
        $bmi = round($bmi, 2);
    }
    
    $query = "INSERT INTO vitals (patient_id, doctor_id, recorded_by_nurse_id, blood_pressure, heart_rate, temperature, oxygen_saturation, weight, height, bmi, notes, recorded_date) 
              VALUES ('$patient_id', '$doctor_id', '$nurse_id', '$blood_pressure', '$heart_rate', '$temperature', '$oxygen_saturation', '$weight', '$height', '$bmi', '$notes', NOW())";
    
    if ($conn->query($query)) {
        $_SESSION['success'] = "Vital signs recorded successfully!";
    } else {
        $_SESSION['error'] = "Error: " . $conn->error;
    }
    
    header("Location: dashboard.php");
    exit();
}
?>