<?php
// File: /dripend/includes/vitalsHistory/getVitalsHistory.php
session_start();

// FIX: Just go up one level to reach includes/db.php
require_once '../db.php';

if (!isset($_GET['patient_no'])) {
    die("<tr><td colspan='10' style='text-align:center; color:red;'>No patient ID provided.</td></tr>");
}

$patient_no = $_GET['patient_no'];

$stmt = $conn->prepare("SELECT * FROM patient_vitals WHERE patient_no = ? ORDER BY recorded_at DESC");
$stmt->bind_param("s", $patient_no);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows === 0) {
    echo "<tr><td colspan='10' style='text-align:center; padding:30px; color:#64748b; font-weight:600;'>No historical vitals found for this patient.</td></tr>";
} else {
    while ($row = $result->fetch_assoc()) {
        $date = date('d M Y, h:i A', strtotime($row['recorded_at']));
        $context = htmlspecialchars($row['context'] ?? 'OPD');
        
        // Format BP safely
        $bp = ($row['bp_systolic'] && $row['bp_diastolic']) ? $row['bp_systolic'] . '/' . $row['bp_diastolic'] : '--';
        $pulse = $row['pulse_rate'] ?? '--';
        $temp = $row['temperature'] ?? '--';
        $spo2 = $row['spo2'] ? $row['spo2'].'%' : '--';
        $weight = $row['weight_kg'] ?? '--';
        
        // Combine Sugars
        $sugars = [];
        if (!empty($row['fasting_blood_sugar'])) $sugars[] = "FBS: " . $row['fasting_blood_sugar'];
        if (!empty($row['random_blood_sugar'])) $sugars[] = "RBS: " . $row['random_blood_sugar'];
        $sugar_display = !empty($sugars) ? implode("<br>", $sugars) : '--';

        $upt = $row['urine_pregnancy_test'] ?? '--';
        $rdt = $row['rapid_diagnostic_test'] ?? '--';

        echo "<tr>";
        echo "<td><strong>{$date}</strong><br><span style='font-size:11px; color:#64748b; background:#e2e8f0; padding:2px 6px; border-radius:4px;'>{$context}</span></td>";
        echo "<td>{$bp}</td>";
        echo "<td>{$pulse}</td>";
        echo "<td>{$temp}</td>";
        echo "<td>{$spo2}</td>";
        echo "<td>{$weight}</td>";
        echo "<td>{$sugar_display}</td>";
        echo "<td>{$upt}</td>";
        echo "<td>{$rdt}</td>";
        echo "</tr>";
    }
}
$stmt->close();
?>