<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
include 'layouts/dbconn.php';

// Check if user is logged in
if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

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

// Verify Role Access
if ($role_code !== 'HEAD_NURSE' && $role_code !== 'ENT_NURSE') {
    $redirect_url = match ($role_code) {
        'SUPER_ADMIN', 'HOSPITAL_ADMIN' => 'admin_dashboard.php',
        'ENT_CONSULTANT', 'ENT_DOCTOR' => 'doctor_dashboard.php',
        'RESIDENT_DOCTOR' => 'resident_dashboard.php',
        'AUDIOLOGIST' => 'audiologist_dashboard.php',
        'LAB_TECHNICIAN' => 'lab_dashboard.php',
        'RECEPTIONIST' => 'reception_dashboard.php',
        'BILLING_CLERK' => 'billing_dashboard.php',
        'MEDICAL_RECORDS' => 'records_dashboard.php',
        'PATIENT' => 'patient_portal.php',
        default => 'index.php'
    };
    header("Location: $redirect_url");
    exit();
}

// Fetch user details
$sql_user_details = "SELECT full_name FROM users WHERE user_id = ?";
$stmt_user = $conn->prepare($sql_user_details);
$stmt_user->bind_param("i", $user_id);
$stmt_user->execute();
$val = $stmt_user->get_result()->fetch_assoc();
$full_name = $val['full_name'];

// Get patients awaiting vitals from triage queue
$patients_sql = "SELECT 
    q.queue_id,
    q.patient_id,
    q.patient_name,
    q.patient_number,
    q.age,
    q.gender,
    q.phone_number,
    q.visit_id,
    q.chief_complaint,
    q.triage_category,
    q.priority,
    q.queue_entry_time,
    q.vitals_taken,
    q.vital_signs_id,
    pv.registration_type,
    pv.insurance_details,
    TIMESTAMPDIFF(MINUTE, q.queue_entry_time, NOW()) as wait_minutes
FROM patient_queue q
LEFT JOIN patient_visits pv ON q.visit_id = pv.visit_id
WHERE DATE(q.queue_entry_time) = CURDATE()
AND q.queue_status IN ('WAITING', 'IN_SERVICE')
AND q.department_id = 2
ORDER BY 
    CASE q.priority
        WHEN 'EMERGENCY' THEN 1
        WHEN 'URGENT' THEN 2
        WHEN 'NORMAL' THEN 3
    END,
    q.queue_entry_time";

$patients_result = $conn->query($patients_sql);

// Get recent vitals records
$recent_vitals_sql = "SELECT 
    v.vital_id,
    v.patient_id,
    p.patient_number,
    u_patient.full_name as patient_name,
    v.recorded_date,
    v.blood_pressure,
    v.pulse_rate,
    v.temperature,
    v.oxygen_saturation,
    v.weight,
    u_nurse.full_name as recorded_by_name
FROM vital_signs v
INNER JOIN patients p ON v.patient_id = p.patient_id
INNER JOIN users u_patient ON p.user_id = u_patient.user_id
INNER JOIN users u_nurse ON v.recorded_by = u_nurse.user_id
WHERE DATE(v.recorded_date) = CURDATE()
ORDER BY v.recorded_date DESC
LIMIT 10";

$recent_vitals_result = $conn->query($recent_vitals_sql);
?>

<?php include 'layouts/main.php'; ?>

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Record Vital Signs')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .page-header {
            background: linear-gradient(135deg, #66CDAA 0%, #20B2AA 100%);
            color: white;
            border-radius: 12px;
            padding: 2rem;
            margin-bottom: 2rem;
            box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
        }
        
        .patient-card {
            background: white;
            border-radius: 10px;
            padding: 1.5rem;
            margin-bottom: 1rem;
            border: 1px solid #e2e8f0;
            transition: all 0.3s;
            cursor: pointer;
        }
        
        .patient-card:hover {
            border-color: #66CDAA;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
            transform: translateY(-2px);
        }
        
        .patient-card.selected {
            border-color: #66CDAA;
            background: #f0fdf4;
        }
        
        .patient-info {
            display: flex;
            align-items: center;
            gap: 1rem;
        }
        
        .patient-avatar {
            width: 50px;
            height: 50px;
            border-radius: 50%;
            background: linear-gradient(135deg, #66CDAA 0%, #20B2AA 100%);
            display: flex;
            align-items: center;
            justify-content: center;
            color: white;
            font-weight: 600;
            font-size: 1.25rem;
        }
        
        .patient-details {
            flex: 1;
        }
        
        .patient-name {
            font-weight: 600;
            color: #1e293b;
            font-size: 1.1rem;
            margin-bottom: 0.25rem;
        }
        
        .patient-meta {
            font-size: 0.875rem;
            color: #64748b;
        }
        
        .priority-badge {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 20px;
            font-size: 0.75rem;
            font-weight: 600;
            text-transform: uppercase;
        }
        
        .priority-normal {
            background: #dcfce7;
            color: #166534;
        }
        
        .priority-urgent {
            background: #fef3c7;
            color: #92400e;
        }
        
        .priority-emergency {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .vitals-form {
            background: white;
            border-radius: 12px;
            padding: 2rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
        }
        
        .form-group {
            margin-bottom: 1.5rem;
        }
        
        .form-label {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 0.5rem;
            display: block;
        }
        
        .form-control {
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.75rem;
            font-size: 0.875rem;
        }
        
        .form-control:focus {
            border-color: #66CDAA;
            box-shadow: 0 0 0 3px rgba(102, 205, 170, 0.1);
            outline: none;
        }
        
        .vitals-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 1.5rem;
        }
        
        .btn-record {
            background: linear-gradient(135deg, #66CDAA 0%, #20B2AA 100%);
            border: none;
            color: white;
            padding: 0.75rem 2rem;
            border-radius: 8px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s;
        }
        
        .btn-record:hover {
            transform: translateY(-2px);
            box-shadow: 0 4px 6px rgba(0,0,0,0.2);
        }
        
        .recent-vitals-table {
            background: white;
            border-radius: 12px;
            overflow: hidden;
        }
        
        .recent-vitals-table table {
            width: 100%;
        }
        
        .recent-vitals-table thead {
            background: linear-gradient(135deg, #66CDAA 0%, #20B2AA 100%);
            color: white;
        }
        
        .recent-vitals-table th,
        .recent-vitals-table td {
            padding: 1rem;
            text-align: left;
        }
        
        .recent-vitals-table tbody tr {
            border-bottom: 1px solid #f1f5f9;
        }
        
        .recent-vitals-table tbody tr:hover {
            background: #f8fafc;
        }
        
        .vital-indicator {
            display: inline-block;
            padding: 0.25rem 0.75rem;
            border-radius: 6px;
            font-size: 0.875rem;
            font-weight: 600;
        }
        
        .vital-normal {
            background: #dcfce7;
            color: #166534;
        }
        
        .vital-warning {
            background: #fef3c7;
            color: #92400e;
        }
        
        .vital-critical {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .no-patient-selected {
            text-align: center;
            padding: 3rem;
            color: #64748b;
            background: white;
            border-radius: 12px;
        }
        
        .no-patient-selected i {
            font-size: 4rem;
            margin-bottom: 1rem;
            opacity: 0.3;
        }
        
        .input-group {
            display: flex;
            gap: 0.5rem;
        }
        
        .input-addon {
            background: #f1f5f9;
            border: 1px solid #e2e8f0;
            border-radius: 8px;
            padding: 0.75rem;
            display: flex;
            align-items: center;
            font-size: 0.875rem;
            color: #64748b;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <!-- Page Header -->
                    <div class="page-header">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <h3 class="mb-1">
                                    <i class="ri-heart-pulse-line me-2"></i>Record Vital Signs
                                </h3>
                                <p class="mb-0 opacity-75">Take patient vital measurements and assessments</p>
                            </div>
                            <div>
                                <button class="btn btn-light" onclick="location.reload()">
                                    <i class="ri-refresh-line me-1"></i>Refresh
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <div class="row">
                        <!-- Patient Queue List -->
                        <div class="col-xl-4">
                            <div class="card">
                                <div class="card-header" style="background: linear-gradient(135deg, #66CDAA 0%, #20B2AA 100%); color: white;">
                                    <h5 class="mb-0">
                                        <i class="ri-user-heart-line me-2"></i>Patients Awaiting Vitals
                                        <span class="badge bg-light text-dark ms-2"><?php echo $patients_result->num_rows; ?></span>
                                    </h5>
                                </div>
                                <div class="card-body" style="max-height: 600px; overflow-y: auto;">
                                    <?php if ($patients_result->num_rows > 0): ?>
                                        <?php while ($patient = $patients_result->fetch_assoc()): ?>
                                            <div class="patient-card" onclick="selectPatient(<?php echo htmlspecialchars(json_encode($patient)); ?>)">
                                                <div class="patient-info">
                                                    <div class="patient-avatar">
                                                        <?php echo strtoupper(substr($patient['patient_name'], 0, 1)); ?>
                                                    </div>
                                                    <div class="patient-details">
                                                        <div class="patient-name">
                                                            <?php echo htmlspecialchars($patient['patient_name']); ?>
                                                        </div>
                                                        <div class="patient-meta">
                                                            <?php echo $patient['patient_number']; ?> • 
                                                            <?php echo $patient['age']; ?>Y <?php echo $patient['gender']; ?>
                                                        </div>
                                                        <div class="patient-meta">
                                                            <i class="ri-time-line"></i> Waiting: <?php echo $patient['wait_minutes']; ?> min
                                                        </div>
                                                        <?php if ($patient['chief_complaint']): ?>
                                                        <div class="patient-meta mt-1">
                                                            <i class="ri-stethoscope-line"></i> <?php echo htmlspecialchars(substr($patient['chief_complaint'], 0, 30)); ?>...
                                                        </div>
                                                        <?php endif; ?>
                                                    </div>
                                                    <div>
                                                        <span class="priority-badge priority-<?php echo strtolower($patient['priority']); ?>">
                                                            <?php echo $patient['priority']; ?>
                                                        </span>
                                                        <?php if ($patient['vitals_taken']): ?>
                                                        <div class="mt-2">
                                                            <i class="ri-check-line text-success"></i>
                                                            <small class="text-success">Vitals Done</small>
                                                        </div>
                                                        <?php endif; ?>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endwhile; ?>
                                    <?php else: ?>
                                        <div class="text-center py-5">
                                            <i class="ri-inbox-line" style="font-size: 3rem; opacity: 0.3;"></i>
                                            <p class="text-muted mt-3">No patients awaiting vitals</p>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Vitals Recording Form -->
                        <div class="col-xl-8">
                            <div id="no-patient-selected" class="no-patient-selected">
                                <i class="ri-user-search-line"></i>
                                <h5>Select a Patient</h5>
                                <p>Choose a patient from the list to record their vital signs</p>
                            </div>
                            
                            <div id="vitals-form-container" style="display: none;">
                                <div class="vitals-form">
                                    <form id="vitalsForm">
                                        <input type="hidden" id="patient_id" name="patient_id">
                                        <input type="hidden" id="visit_id" name="visit_id">
                                        <input type="hidden" id="queue_id" name="queue_id">
                                        
                                        <div class="mb-4 p-3" style="background: #f0fdf4; border-radius: 8px;">
                                            <h5 class="mb-2" id="selected_patient_name"></h5>
                                            <div class="text-muted" id="selected_patient_info"></div>
                                        </div>
                                        
                                        <h5 class="mb-3">
                                            <i class="ri-heart-pulse-line me-2 text-danger"></i>Vital Signs
                                        </h5>
                                        
                                        <div class="vitals-grid">
                                            <!-- Blood Pressure -->
                                            <div class="form-group">
                                                <label class="form-label">
                                                    <i class="ri-heart-line me-1 text-danger"></i>Blood Pressure
                                                </label>
                                                <input type="text" class="form-control" id="blood_pressure" 
                                                       name="blood_pressure" placeholder="120/80" 
                                                       pattern="[0-9]{2,3}/[0-9]{2,3}">
                                                <small class="text-muted">Format: Systolic/Diastolic (e.g., 120/80)</small>
                                            </div>
                                            
                                            <!-- Pulse Rate -->
                                            <div class="form-group">
                                                <label class="form-label">
                                                    <i class="ri-pulse-line me-1 text-danger"></i>Pulse Rate
                                                </label>
                                                <div class="input-group">
                                                    <input type="number" class="form-control" id="pulse_rate" 
                                                           name="pulse_rate" placeholder="72" min="40" max="200">
                                                    <span class="input-addon">bpm</span>
                                                </div>
                                            </div>
                                            
                                            <!-- Temperature -->
                                            <div class="form-group">
                                                <label class="form-label">
                                                    <i class="ri-temp-hot-line me-1 text-warning"></i>Temperature
                                                </label>
                                                <div class="input-group">
                                                    <input type="number" step="0.1" class="form-control" id="temperature" 
                                                           name="temperature" placeholder="36.5" min="35" max="42">
                                                    <span class="input-addon">°C</span>
                                                </div>
                                            </div>
                                            
                                            <!-- Temperature Route -->
                                            <div class="form-group">
                                                <label class="form-label">Temperature Route</label>
                                                <select class="form-control" id="temperature_route" name="temperature_route">
                                                    <option value="ORAL">Oral</option>
                                                    <option value="AXILLARY">Axillary (Armpit)</option>
                                                    <option value="RECTAL">Rectal</option>
                                                    <option value="TYMPANIC">Tympanic (Ear)</option>
                                                    <option value="TEMPORAL">Temporal (Forehead)</option>
                                                </select>
                                            </div>
                                            
                                            <!-- Respiratory Rate -->
                                            <div class="form-group">
                                                <label class="form-label">
                                                    <i class="ri-lungs-line me-1 text-info"></i>Respiratory Rate
                                                </label>
                                                <div class="input-group">
                                                    <input type="number" class="form-control" id="respiratory_rate" 
                                                           name="respiratory_rate" placeholder="16" min="10" max="40">
                                                    <span class="input-addon">breaths/min</span>
                                                </div>
                                            </div>
                                            
                                            <!-- Oxygen Saturation -->
                                            <div class="form-group">
                                                <label class="form-label">
                                                    <i class="ri-heart-pulse-line me-1 text-primary"></i>Oxygen Saturation (SpO2)
                                                </label>
                                                <div class="input-group">
                                                    <input type="number" step="0.1" class="form-control" id="oxygen_saturation" 
                                                           name="oxygen_saturation" placeholder="98" min="70" max="100">
                                                    <span class="input-addon">%</span>
                                                </div>
                                            </div>
                                            
                                            <!-- Weight -->
                                            <div class="form-group">
                                                <label class="form-label">
                                                    <i class="ri-scales-3-line me-1 text-success"></i>Weight
                                                </label>
                                                <div class="input-group">
                                                    <input type="number" step="0.1" class="form-control" id="weight" 
                                                           name="weight" placeholder="70" min="1" max="300">
                                                    <span class="input-addon">kg</span>
                                                </div>
                                            </div>
                                            
                                            <!-- Height -->
                                            <div class="form-group">
                                                <label class="form-label">
                                                    <i class="ri-ruler-2-line me-1 text-success"></i>Height
                                                </label>
                                                <div class="input-group">
                                                    <input type="number" step="0.1" class="form-control" id="height" 
                                                           name="height" placeholder="170" min="50" max="250">
                                                    <span class="input-addon">cm</span>
                                                </div>
                                            </div>
                                            
                                            <!-- Pain Scale -->
                                            <div class="form-group">
                                                <label class="form-label">
                                                    <i class="ri-emotion-unhappy-line me-1 text-warning"></i>Pain Scale (0-10)
                                                </label>
                                                <input type="range" class="form-range" id="pain_scale" 
                                                       name="pain_scale" min="0" max="10" value="0" 
                                                       oninput="document.getElementById('pain_value').textContent = this.value">
                                                <div class="text-center">
                                                    <span class="badge bg-warning" id="pain_value">0</span>
                                                </div>
                                            </div>
                                            
                                            <!-- Consciousness Level -->
                                            <div class="form-group">
                                                <label class="form-label">Consciousness Level (AVPU)</label>
                                                <select class="form-control" id="consciousness_level" name="consciousness_level">
                                                    <option value="ALERT" selected>Alert</option>
                                                    <option value="VERBAL">Responds to Verbal</option>
                                                    <option value="PAIN">Responds to Pain</option>
                                                    <option value="UNRESPONSIVE">Unresponsive</option>
                                                </select>
                                            </div>
                                        </div>
                                        
                                        <div class="form-group mt-3">
                                            <label class="form-label">
                                                <i class="ri-file-text-line me-1"></i>Clinical Notes / Observations
                                            </label>
                                            <textarea class="form-control" id="notes" name="notes" rows="3" 
                                                      placeholder="Any additional observations or concerns..."></textarea>
                                        </div>
                                        
                                        <div class="form-group">
                                            <label class="form-label">
                                                <i class="ri-alert-line me-1 text-danger"></i>Abnormal Findings
                                            </label>
                                            <textarea class="form-control" id="abnormal_findings" name="abnormal_findings" rows="2" 
                                                      placeholder="Document any abnormal vital signs or observations..."></textarea>
                                        </div>
                                        
                                        <div class="text-center mt-4">
                                            <button type="button" class="btn btn-secondary me-2" onclick="clearForm()">
                                                <i class="ri-refresh-line me-1"></i>Clear Form
                                            </button>
                                            <button type="submit" class="btn-record">
                                                <i class="ri-save-line me-1"></i>Record Vitals
                                            </button>
                                        </div>
                                    </form>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Recent Vitals -->
                    <div class="row mt-4">
                        <div class="col-12">
                            <div class="card">
                                <div class="card-header" style="background: linear-gradient(135deg, #66CDAA 0%, #20B2AA 100%); color: white;">
                                    <h5 class="mb-0">
                                        <i class="ri-history-line me-2"></i>Recent Vitals Recorded Today
                                    </h5>
                                </div>
                                <div class="card-body p-0">
                                    <div class="recent-vitals-table">
                                        <?php if ($recent_vitals_result->num_rows > 0): ?>
                                        <table>
                                            <thead>
                                                <tr>
                                                    <th>Time</th>
                                                    <th>Patient</th>
                                                    <th>BP</th>
                                                    <th>Pulse</th>
                                                    <th>Temp</th>
                                                    <th>SpO2</th>
                                                    <th>Weight</th>
                                                    <th>Recorded By</th>
                                                </tr>
                                            </thead>
                                            <tbody>
                                                <?php while ($vital = $recent_vitals_result->fetch_assoc()): ?>
                                                <tr>
                                                    <td><?php echo date('H:i', strtotime($vital['recorded_date'])); ?></td>
                                                    <td>
                                                        <strong><?php echo htmlspecialchars($vital['patient_name']); ?></strong><br>
                                                        <small class="text-muted"><?php echo $vital['patient_number']; ?></small>
                                                    </td>
                                                    <td>
                                                        <?php if ($vital['blood_pressure']): ?>
                                                            <span class="vital-indicator vital-normal">
                                                                <?php echo $vital['blood_pressure']; ?>
                                                            </span>
                                                        <?php else: ?>
                                                            <span class="text-muted">-</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <?php if ($vital['pulse_rate']): ?>
                                                            <?php echo $vital['pulse_rate']; ?> bpm
                                                        <?php else: ?>
                                                            <span class="text-muted">-</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <?php if ($vital['temperature']): ?>
                                                            <?php echo $vital['temperature']; ?>°C
                                                        <?php else: ?>
                                                            <span class="text-muted">-</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <?php if ($vital['oxygen_saturation']): ?>
                                                            <?php echo $vital['oxygen_saturation']; ?>%
                                                        <?php else: ?>
                                                            <span class="text-muted">-</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td>
                                                        <?php if ($vital['weight']): ?>
                                                            <?php echo $vital['weight']; ?> kg
                                                        <?php else: ?>
                                                            <span class="text-muted">-</span>
                                                        <?php endif; ?>
                                                    </td>
                                                    <td><?php echo htmlspecialchars($vital['recorded_by_name']); ?></td>
                                                </tr>
                                                <?php endwhile; ?>
                                            </tbody>
                                        </table>
                                        <?php else: ?>
                                        <div class="text-center py-5">
                                            <i class="ri-inbox-line" style="font-size: 3rem; opacity: 0.3;"></i>
                                            <p class="text-muted mt-3">No vitals recorded today</p>
                                        </div>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>

    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    
    <script>
    let selectedPatient = null;
    
    function selectPatient(patient) {
        selectedPatient = patient;
        
        // Update UI
        $('.patient-card').removeClass('selected');
        event.currentTarget.classList.add('selected');
        
        // Show form
        document.getElementById('no-patient-selected').style.display = 'none';
        document.getElementById('vitals-form-container').style.display = 'block';
        
        // Populate patient info
        document.getElementById('patient_id').value = patient.patient_id;
        document.getElementById('visit_id').value = patient.visit_id;
        document.getElementById('queue_id').value = patient.queue_id;
        
        document.getElementById('selected_patient_name').textContent = patient.patient_name;
        document.getElementById('selected_patient_info').innerHTML = `
            <strong>${patient.patient_number}</strong> • 
            ${patient.age}Y ${patient.gender} • 
            ${patient.phone_number || 'No phone'}<br>
            ${patient.chief_complaint ? '<i class="ri-stethoscope-line"></i> ' + patient.chief_complaint : ''}
        `;
    }
    
    function clearForm() {
        document.getElementById('vitalsForm').reset();
        document.getElementById('pain_value').textContent = '0';
    }
    
    // Handle form submission
    document.getElementById('vitalsForm').addEventListener('submit', function(e) {
        e.preventDefault();
        
        if (!selectedPatient) {
            Swal.fire({
                icon: 'warning',
                title: 'No Patient Selected',
                text: 'Please select a patient first'
            });
            return;
        }
        
        // Validate at least one vital sign is entered
        const bp = document.getElementById('blood_pressure').value;
        const pulse = document.getElementById('pulse_rate').value;
        const temp = document.getElementById('temperature').value;
        
        if (!bp && !pulse && !temp) {
            Swal.fire({
                icon: 'warning',
                title: 'Incomplete Data',
                text: 'Please enter at least Blood Pressure, Pulse Rate, or Temperature'
            });
            return;
        }
        
        // Show loading
        Swal.fire({
            title: 'Recording Vitals...',
            text: 'Please wait',
            allowOutsideClick: false,
            didOpen: () => {
                Swal.showLoading();
            }
        });
        
        // Prepare form data
        const formData = new FormData(this);
        
        // Send AJAX request
        fetch('save_vitals.php', {
            method: 'POST',
            body: formData
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                Swal.fire({
                    icon: 'success',
                    title: 'Vitals Recorded!',
                    text: data.message,
                    showConfirmButton: true,
                    timer: 2000
                }).then(() => {
                    // Reload page to update lists
                    location.reload();
                });
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Error',
                    text: data.message
                });
            }
        })
        .catch(error => {
            console.error('Error:', error);
            Swal.fire({
                icon: 'error',
                title: 'Error',
                text: 'An error occurred while recording vitals'
            });
        });
    });
    </script>
    
    <script src="assets/js/app.js"></script>
</body>
</html>