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

require_once '../../dripend/includes/db.php';

if (!isset($conn) || !$conn) {
    die("<div style='padding:20px; background:#fee2e2; color:#991b1b;'>Fatal Error: Database connection failed.</div>");
}

$error_message = "";
$success_data = null; 

// ==============================================================================
// 1. IDENTIFY THE VISIT & PATIENT
// ==============================================================================
$visit_id = $_GET['visit_id'] ?? null;
if (!$visit_id) die("<div style='padding:40px; text-align:center;'><h2>Invalid Request</h2><p>No Visit ID provided.</p></div>");

// Fetch the visit details
$vStmt = $conn->prepare("SELECT patient_no, status FROM visit_master WHERE id = ?");
$vStmt->bind_param("i", $visit_id);
$vStmt->execute();
$vRes = $vStmt->get_result();
if ($vRes->num_rows === 0) die("<div style='padding:40px; text-align:center;'><h2>Visit Not Found</h2></div>");
$visit_data = $vRes->fetch_assoc();
$vStmt->close();

$_GET['patient_id'] = $visit_data['patient_no']; 
$patient_no = $visit_data['patient_no'];

// ==============================================================================
// 2. FETCH ONLY THE ABSOLUTE LAST RECORDED VITALS FOR THE TOP BANNER
// ==============================================================================
$last_vitals = null;
$last_vitals_date = "No previous records";

$lvStmt = $conn->prepare("SELECT * FROM patient_vitals WHERE patient_no = ? ORDER BY recorded_at DESC LIMIT 1");
$lvStmt->bind_param("s", $patient_no);
$lvStmt->execute();
$lvRes = $lvStmt->get_result();
if ($lvRes->num_rows > 0) {
    $last_vitals = $lvRes->fetch_assoc();
    $last_vitals_date = date('d M Y, h:i A', strtotime($last_vitals['recorded_at']));
}
$lvStmt->close();

// ==============================================================================
// 3. FORM PROCESSING LOGIC
// ==============================================================================
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $temperature      = !empty($_POST['temperature']) ? (float)$_POST['temperature'] : null;
    $pulse_rate       = !empty($_POST['pulse_rate']) ? (int)$_POST['pulse_rate'] : null;
    $bp_systolic      = !empty($_POST['bp_systolic']) ? (int)$_POST['bp_systolic'] : null;
    $bp_diastolic     = !empty($_POST['bp_diastolic']) ? (int)$_POST['bp_diastolic'] : null;
    $respiratory_rate = !empty($_POST['respiratory_rate']) ? (int)$_POST['respiratory_rate'] : null;
    $spo2             = !empty($_POST['spo2']) ? (int)$_POST['spo2'] : null;
    
    $weight_kg        = !empty($_POST['weight_kg']) ? (float)$_POST['weight_kg'] : null;
    $height_cm        = !empty($_POST['height_cm']) ? (float)$_POST['height_cm'] : null;
    $bmi              = !empty($_POST['bmi']) ? (float)$_POST['bmi'] : null;

    $fasting_blood_sugar   = !empty($_POST['fasting_blood_sugar']) ? (float)$_POST['fasting_blood_sugar'] : null;
    $random_blood_sugar    = !empty($_POST['random_blood_sugar']) ? (float)$_POST['random_blood_sugar'] : null;
    $urine_pregnancy_test  = !empty($_POST['urine_pregnancy_test']) ? trim($_POST['urine_pregnancy_test']) : null;
    $rapid_diagnostic_test = !empty($_POST['rapid_diagnostic_test']) ? trim($_POST['rapid_diagnostic_test']) : null;
    $urine_remarks         = !empty($_POST['urine_remarks']) ? trim($_POST['urine_remarks']) : null;
    
    $context = 'OPD Triage';
    $recorded_by = 1; // HARDCODED for now until Staff Login Sessions are mapped

    $conn->begin_transaction();
    try {
        $sql = "INSERT INTO patient_vitals (
            patient_no, visit_id, temperature, pulse_rate, bp_systolic, bp_diastolic, 
            respiratory_rate, spo2, weight_kg, height_cm, bmi, 
            fasting_blood_sugar, random_blood_sugar, urine_pregnancy_test, rapid_diagnostic_test, urine_remarks, 
            context, recorded_by
        ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        
        $stmt = $conn->prepare($sql);
        // Bind 18 parameters (Removed custom_vitals for perfect mapping)
        $stmt->bind_param("sidiiiiiiddddssssi", 
            $patient_no, $visit_id, $temperature, $pulse_rate, $bp_systolic, $bp_diastolic, 
            $respiratory_rate, $spo2, $weight_kg, $height_cm, $bmi,
            $fasting_blood_sugar, $random_blood_sugar, $urine_pregnancy_test, $rapid_diagnostic_test, $urine_remarks,
            $context, $recorded_by
        );
        $stmt->execute();
        $stmt->close();

        // Update Visit Status to 'In Progress'
        if (in_array($visit_data['status'], ['Scheduled', 'Pending'])) {
            $uStmt = $conn->prepare("UPDATE visit_master SET status = 'In Progress' WHERE id = ?");
            $uStmt->bind_param("i", $visit_id);
            $uStmt->execute();
            $uStmt->close();
        }

        $conn->commit();

        $success_data = [
            'redirect_url' => '../appointment/appointment_calendar.php', 
            'message'      => 'Vitals saved successfully. Patient is now ready for consultation.'
        ];

    } catch (Exception $e) {
        $conn->rollback();
        $error_message = "Failed to save vitals: " . $e->getMessage();
    }
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Record OPD Vitals | DripDental</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.0/css/all.min.css">
<style>
:root { --sidebar-width: 240px; --e-blue: #1e3a8a; --e-blue-light: #eff6ff; --e-green: #16a34a; --e-red: #dc2626; --bg-color: #f8fafc; --card-bg: #ffffff; --border-color: #e2e8f0; --text-main: #0f172a; --text-muted: #64748b; }
* { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Segoe UI', system-ui, sans-serif; }
body { background: var(--bg-color); color: var(--text-main); overflow-x: hidden; }
.page-wrapper { position: absolute; top: 0; left: var(--sidebar-width); width: calc(100% - var(--sidebar-width)); min-height: 100vh; padding: 30px; display: block !important; }
.alert { padding: 15px; border-radius: 8px; font-weight: 600; margin-bottom: 20px; border-left: 5px solid; }
.alert-error { background: #fee2e2; color: #991b1b; border-color: #ef4444; }

/* HEADER STYLING */
.triage-header-block { background: #eff6ff; border: 1px solid #bfdbfe; border-radius: 8px 8px 0 0; padding: 16px 24px; display: flex; justify-content: space-between; align-items: center; margin-bottom: -1px; }
.triage-header-title { font-size: 18px; font-weight: 900; color: #1e3a8a; margin: 0; }
.btn-history { background: #fff; border: 1px solid #3b82f6; color: #2563eb; padding: 8px 16px; border-radius: 20px; font-size: 13px; font-weight: 800; cursor: pointer; display: flex; align-items: center; gap: 6px; transition: 0.2s; }
.btn-history:hover { background: #3b82f6; color: #fff; }

.vitals-container { background: #fff; border: 1px solid var(--border-color); border-radius: 0 0 8px 8px; padding: 24px; }
.vitals-sub-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px; }
.vitals-sub-title { font-size: 18px; font-weight: 900; color: #0f172a; margin: 0; }

/* DYNAMIC LAST RECORDED BANNER */
.last-recorded-banner { background: #f8fafc; border: 1px solid #cbd5e1; border-radius: 8px; padding: 12px 20px; margin-bottom: 25px; display: flex; flex-wrap: wrap; gap: 20px; align-items: center; box-shadow: inset 0 2px 4px rgba(0,0,0,0.02);}
.lr-item { display: flex; flex-direction: column; gap: 2px; }
.lr-lbl { font-size: 11px; font-weight: 800; color: #64748b; text-transform: uppercase; letter-spacing: 0.5px; }
.lr-val { font-size: 16px; font-weight: 900; color: #1e3a8a; }

/* GRID LAYOUT */
.vitals-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); gap: 16px; }

/* VITAL CARD STYLING */
.vital-card { background: #f8fafc; border: 1px solid #e2e8f0; border-radius: 10px; padding: 16px; transition: border-color 0.2s; }
.vital-card:focus-within { border-color: #3b82f6; background: #fff; box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1); }
.vc-label { display: block; font-size: 14px; font-weight: 800; color: #1e293b; margin-bottom: 2px; }
.vc-sub { display: block; font-size: 11px; color: #94a3b8; font-weight: 600; margin-bottom: 12px; min-height: 14px; }

.vc-input-group { display: flex; align-items: center; gap: 8px; }
.vc-input-group input, .vc-input-group select { flex: 1; padding: 10px 12px; border: 1px solid #cbd5e1; border-radius: 6px; font-size: 15px; font-weight: 700; color: #0f172a; outline: none; width: 100%; }
.vc-input-group input[readonly] { background: #e2e8f0; color: #475569; }
.vc-unit { font-size: 14px; font-weight: 900; color: #1e3a8a; white-space: nowrap; }

/* SPECIAL BP LAYOUT */
.bp-group { display: flex; align-items: center; gap: 6px; flex: 1; }
.bp-group input { width: 45%; text-align: center; }
.bp-divider { font-size: 18px; font-weight: 800; color: #64748b; }

.btn-submit { background: #1e3a8a; color: #fff; border: none; padding: 16px 30px; border-radius: 8px; font-weight: 800; cursor: pointer; font-size: 16px; transition: 0.2s; width: 100%; margin-top: 25px; display: flex; justify-content: center; align-items: center; gap: 8px; }
.btn-submit:hover { background: #1e293b; }

/* MODAL STYLES */
.modal-overlay { position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(15, 23, 42, 0.6); display: none; align-items: center; justify-content: center; z-index: 9999; opacity: 0; transition: opacity 0.2s ease; backdrop-filter: blur(2px); }
.modal-overlay.active { display: flex; opacity: 1; }
.modal-box { background: #fff; width: 95%; max-width: 900px; border-radius: 12px; box-shadow: 0 25px 50px -12px rgba(0,0,0,0.25); transform: scale(0.95); transition: transform 0.2s ease; overflow: hidden; display: flex; flex-direction: column; max-height: 90vh; }
.modal-overlay.active .modal-box { transform: scale(1); }
.modal-header { padding: 20px 24px; border-bottom: 1px solid var(--border-color); display: flex; justify-content: space-between; align-items: center; background: #f8fafc; }
.modal-header h3 { margin: 0; font-size: 20px; font-weight: 900; color: var(--e-blue); }
.modal-close { background: none; border: none; font-size: 24px; color: var(--text-muted); cursor: pointer; }
.modal-body { padding: 24px; overflow-y: auto; flex: 1; }

/* HISTORY TABLE */
.history-table { width: 100%; border-collapse: collapse; font-size: 14px; }
.history-table th { background: #f1f5f9; padding: 12px; text-align: left; font-size: 12px; font-weight: 800; color: #475569; text-transform: uppercase; border-bottom: 2px solid #cbd5e1; white-space: nowrap; }
.history-table td { padding: 14px 12px; border-bottom: 1px solid #e2e8f0; color: var(--text-main); font-weight: 600; white-space: nowrap; }

/* SUCCESS MODAL OVERRIDES */
#successModal .modal-box { max-width: 420px; text-align: center; padding: 40px 30px; display:block; }
.modal-icon { font-size: 50px; margin-bottom: 15px; color: var(--e-green); }
</style>
</head>
<body>

<?php include('../../dripend/statpages/sidebar.php'); ?>

<div class="page-wrapper" id="mainWrapper">
    <?php if (!empty($error_message)): ?><div class="alert alert-error"><?php echo htmlspecialchars($error_message); ?></div><?php endif; ?>
    
    <?php include('../../dripend/statpages/patientProfileHeader.php'); ?>

    <form method="post" action="">
        <div class="triage-header-block">
            <h2 class="triage-header-title">1. Triage / Vitals (OPD)</h2>
            <button type="button" class="btn-history" onclick="fetchVitalsHistory('<?php echo htmlspecialchars($patient_no); ?>')">
                <i class="fa-solid fa-clock-rotate-left"></i> View Full History
            </button>
        </div>

        <div class="vitals-container">
            <div class="vitals-sub-header">
                <h3 class="vitals-sub-title">Add new vital reading</h3>
            </div>

            <?php if ($last_vitals): ?>
            <div class="last-recorded-banner">
                <div class="lr-item" style="border-right: 1px solid #cbd5e1; padding-right: 20px;">
                    <span class="lr-lbl">Last Captured</span>
                    <span class="lr-val" style="color:#0f172a;"><i class="fa-regular fa-clock"></i> <?php echo htmlspecialchars($last_vitals_date); ?></span>
                </div>
                <div class="lr-item"><span class="lr-lbl">BP</span> <span class="lr-val"><?php echo htmlspecialchars($last_vitals['bp_systolic'] ?? '--') . '/' . htmlspecialchars($last_vitals['bp_diastolic'] ?? '--'); ?> <small>mmHg</small></span></div>
                <div class="lr-item"><span class="lr-lbl">Pulse</span> <span class="lr-val"><?php echo htmlspecialchars($last_vitals['pulse_rate'] ?? '--'); ?> <small>bpm</small></span></div>
                <div class="lr-item"><span class="lr-lbl">Temp</span> <span class="lr-val"><?php echo htmlspecialchars($last_vitals['temperature'] ?? '--'); ?> <small>°C</small></span></div>
                <div class="lr-item"><span class="lr-lbl">SpO₂</span> <span class="lr-val"><?php echo htmlspecialchars($last_vitals['spo2'] ?? '--'); ?> <small>%</small></span></div>
                <div class="lr-item"><span class="lr-lbl">Weight</span> <span class="lr-val"><?php echo htmlspecialchars($last_vitals['weight_kg'] ?? '--'); ?> <small>kg</small></span></div>
            </div>
            <?php else: ?>
            <div class="last-recorded-banner" style="background:#fffbeb; border-color:#fcd34d;">
                <div class="lr-item"><span class="lr-lbl" style="color:#b45309;">Last Captured</span> <span class="lr-val" style="color:#92400e;">No previous vitals recorded for this patient.</span></div>
            </div>
            <?php endif; ?>

            <div class="vitals-grid">
                
                <div class="vital-card">
                    <span class="vc-label">Temperature</span>
                    <span class="vc-sub">—</span>
                    <div class="vc-input-group">
                        <input type="number" step="0.1" name="temperature">
                        <span class="vc-unit">°C</span>
                    </div>
                </div>

                <div class="vital-card">
                    <span class="vc-label">Pulse</span>
                    <span class="vc-sub">—</span>
                    <div class="vc-input-group">
                        <input type="number" name="pulse_rate">
                        <span class="vc-unit">/min</span>
                    </div>
                </div>

                <div class="vital-card" style="grid-column: span 1.5;">
                    <span class="vc-label">Blood Pressure</span>
                    <span class="vc-sub">—</span>
                    <div class="vc-input-group">
                        <div class="bp-group">
                            <input type="number" name="bp_systolic" placeholder="Sys">
                            <span class="bp-divider">/</span>
                            <input type="number" name="bp_diastolic" placeholder="Dia">
                        </div>
                        <span class="vc-unit">mmHg</span>
                    </div>
                </div>

                <div class="vital-card">
                    <span class="vc-label">Respiration</span>
                    <span class="vc-sub">—</span>
                    <div class="vc-input-group">
                        <input type="number" name="respiratory_rate">
                        <span class="vc-unit">/min</span>
                    </div>
                </div>

                <div class="vital-card">
                    <span class="vc-label">SpO₂</span>
                    <span class="vc-sub">—</span>
                    <div class="vc-input-group">
                        <input type="number" name="spo2">
                        <span class="vc-unit">%</span>
                    </div>
                </div>

                <div class="vital-card">
                    <span class="vc-label">Weight</span>
                    <span class="vc-sub">—</span>
                    <div class="vc-input-group">
                        <input type="number" step="0.1" id="weight" name="weight_kg">
                        <span class="vc-unit">kg</span>
                    </div>
                </div>

                <div class="vital-card">
                    <span class="vc-label">Height</span>
                    <span class="vc-sub">—</span>
                    <div class="vc-input-group">
                        <input type="number" step="0.1" id="height" name="height_cm">
                        <span class="vc-unit">cm</span>
                    </div>
                </div>

                <div class="vital-card">
                    <span class="vc-label">BMI</span>
                    <span class="vc-sub">—</span>
                    <div class="vc-input-group">
                        <input type="number" step="0.1" id="bmi" name="bmi" readonly>
                    </div>
                </div>

                <div class="vital-card">
                    <span class="vc-label">Fasting Blood Sugar</span>
                    <span class="vc-sub">—</span>
                    <div class="vc-input-group">
                        <input type="number" step="0.1" name="fasting_blood_sugar">
                        <span class="vc-unit">mmol/L</span>
                    </div>
                </div>

                <div class="vital-card">
                    <span class="vc-label">Random Blood Sugar</span>
                    <span class="vc-sub">—</span>
                    <div class="vc-input-group">
                        <input type="number" step="0.1" name="random_blood_sugar">
                        <span class="vc-unit">mmol/L</span>
                    </div>
                </div>

                <div class="vital-card">
                    <span class="vc-label">Urine Pregnancy Test</span>
                    <span class="vc-sub">—</span>
                    <div class="vc-input-group">
                        <select name="urine_pregnancy_test">
                            <option value="">--Select--</option>
                            <option value="Positive">Positive</option>
                            <option value="Negative">Negative</option>
                            <option value="Indeterminate">Indeterminate</option>
                        </select>
                    </div>
                </div>

                <div class="vital-card">
                    <span class="vc-label">Rapid Diagnostic Test (Malaria)</span>
                    <span class="vc-sub">—</span>
                    <div class="vc-input-group">
                        <select name="rapid_diagnostic_test">
                            <option value="">--Select--</option>
                            <option value="Positive">Positive</option>
                            <option value="Negative">Negative</option>
                        </select>
                    </div>
                </div>

                <div class="vital-card" style="grid-column: span 2;">
                    <span class="vc-label">Urine Remarks</span>
                    <span class="vc-sub">—</span>
                    <div class="vc-input-group">
                        <input type="text" name="urine_remarks" placeholder="Notes...">
                    </div>
                </div>

            </div>

            <button type="submit" class="btn-submit"><i class="fa-solid fa-save"></i> Save Triage & Update Status</button>
        </div>
    </form>
</div>

<div class="modal-overlay" id="historyModal">
    <div class="modal-box">
        <div class="modal-header">
            <h3><i class="fa-solid fa-book-medical"></i> Patient Vitals History</h3>
            <button class="modal-close" onclick="closeHistoryModal()"><i class="fa-solid fa-xmark"></i></button>
        </div>
        <div class="modal-body">
            <div style="overflow-x: auto;">
                <table class="history-table">
                    <thead>
                        <tr>
                            <th>Date & Context</th>
                            <th>BP (mmHg)</th>
                            <th>Pulse</th>
                            <th>Temp (°C)</th>
                            <th>SpO₂</th>
                            <th>Weight (kg)</th>
                            <th>Sugars (mmol/L)</th>
                            <th>Urine PT</th>
                            <th>Malaria RDT</th>
                        </tr>
                    </thead>
                    <tbody id="historyContent">
                        </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<div class="modal-overlay" id="successModal">
    <div class="modal-box">
        <div class="modal-icon"><i class="fa-solid fa-circle-check"></i></div>
        <div class="modal-title" style="font-size:22px; font-weight:800; color:var(--text-main); margin-bottom:10px;">Triage Complete</div>
        <div class="modal-desc" style="font-size:15px; color:var(--text-muted); margin-bottom:25px; line-height:1.5;" id="successDesc">Vitals saved successfully. Patient is now ready for consultation.</div>
        <button style="width:100%; padding:14px; background:var(--e-blue); color:#fff; border:none; border-radius:8px; font-size:16px; font-weight:700; cursor:pointer;" id="btnModalOk">Return to Calendar</button>
    </div>
</div>

<script>
// AJAX Fetch Logic for History
function fetchVitalsHistory(pNo) {
    const modal = document.getElementById('historyModal');
    const content = document.getElementById('historyContent');
    
    modal.classList.add('active');
    content.innerHTML = '<tr><td colspan="10" style="text-align:center; padding:30px;"><i class="fa-solid fa-spinner fa-spin" style="font-size:24px; color:var(--e-blue);"></i><br><br>Fetching secure records...</td></tr>';
    
    // FIX: Corrected relative path from views/vitals/ up to application/ then down to dripend/
    fetch(`../../dripend/includes/vitalsHistory/getVitalsHistory.php?patient_no=${pNo}`)
    .then(response => {
        if (!response.ok) throw new Error("Server returned " + response.status);
        return response.text();
    })
    .then(html => { 
        // Safety check: If it accidentally loads a 404 HTML page instead of table rows
        if(html.toLowerCase().includes('<!doctype html>')) {
            content.innerHTML = '<tr><td colspan="10" style="text-align:center; color:red; padding:20px;"><b>Error 404:</b> Could not find getVitalsHistory.php on the server. Please check the file path.</td></tr>';
        } else {
            content.innerHTML = html; 
        }
    })
    .catch(error => {
        console.error("AJAX Error:", error);
        content.innerHTML = '<tr><td colspan="10" style="text-align:center; color:red; padding:20px;"><b>Network Error:</b> Failed to connect to server.</td></tr>';
    });
}

function closeHistoryModal() {
    document.getElementById('historyModal').classList.remove('active');
}
</script>
</body>
</html>