<?php
// File: /dripend/includes/consultation/viewConsultationData.php
session_start();
require_once '../db.php';

if (!isset($_GET['visit_id'])) die("Invalid Visit ID");
$visit_id = (int)$_GET['visit_id'];

// 1. Fetch Master Visit Data
$stmtV = $conn->prepare("SELECT v.*, s.first_name, s.last_name FROM visit_master v LEFT JOIN staff s ON v.primary_doctor_id = s.staff_id WHERE v.id = ?");
$stmtV->bind_param("i", $visit_id); $stmtV->execute(); $visit = $stmtV->get_result()->fetch_assoc(); $stmtV->close();

// 2. Fetch Vitals
$stmtVit = $conn->prepare("SELECT * FROM patient_vitals WHERE visit_id = ? ORDER BY recorded_at DESC LIMIT 1");
$stmtVit->bind_param("i", $visit_id); $stmtVit->execute(); $vitals = $stmtVit->get_result()->fetch_assoc(); $stmtVit->close();

// 3. Fetch Notes & Audit Trail
$stmtN = $conn->prepare("SELECT * FROM clinical_notes WHERE visit_id = ?");
$stmtN->bind_param("i", $visit_id); $stmtN->execute(); $note = $stmtN->get_result()->fetch_assoc(); $stmtN->close();

// 4. Fetch Diagnoses (Sorted so Principal/Primary is always at the top)
$stmtD = $conn->prepare("SELECT * FROM clinical_diagnoses WHERE visit_id = ? ORDER BY is_principal DESC");
$stmtD->bind_param("i", $visit_id); $stmtD->execute(); $diags = $stmtD->get_result()->fetch_all(MYSQLI_ASSOC); $stmtD->close();

// 5. Fetch Prescriptions
$stmtRx = $conn->prepare("SELECT * FROM clinical_prescriptions WHERE visit_id = ?");
$stmtRx->bind_param("i", $visit_id); $stmtRx->execute(); $rxs = $stmtRx->get_result()->fetch_all(MYSQLI_ASSOC); $stmtRx->close();

// 6. Fetch Lab Requests
$stmtLab = $conn->prepare("SELECT * FROM clinical_lab_requests WHERE visit_id = ?");
$stmtLab->bind_param("i", $visit_id); $stmtLab->execute(); $labs = $stmtLab->get_result()->fetch_all(MYSQLI_ASSOC); $stmtLab->close();

if (!$note) die("<div style='text-align:center; color:red; padding:20px;'>No clinical notes found for this visit.</div>");

$doc_name = !empty($visit['first_name']) ? "Dr. ".$visit['first_name']." ".$visit['last_name'] : "Unknown Doctor";
$last_updated = !empty($note['updated_at']) ? date('d M Y, h:i A', strtotime($note['updated_at'])) : 'Never updated since creation';
?>

<div style="display:flex; justify-content:space-between; align-items:center; margin-bottom:20px; padding-bottom:10px; border-bottom:2px solid #e2e8f0;">
    <div>
        <h4 style="margin:0; color:#1e3a8a;">Attending: <?php echo htmlspecialchars($doc_name); ?></h4>
        <span style="font-size:12px; color:#64748b;">Last Updated: <?php echo $last_updated; ?></span>
    </div>
    <button onclick="window.location.href='../../views/consultation/updateConsultation.php?visit_id=<?php echo $visit_id; ?>'" class="btn-small" style="background:#f59e0b; color:#fff; font-weight:bold; border:none; padding:8px 15px; border-radius:6px; cursor:pointer;">
        <i class="fa-solid fa-pen-to-square"></i> Edit / Update Encounter
    </button>
</div>

<div style="display:flex; flex-direction:column; gap:20px;">

    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:8px; padding:15px;">
        <h4 style="margin:0 0 10px 0; color:#1e3a8a; border-bottom:1px solid #e2e8f0; padding-bottom:5px;"><i class="fa-solid fa-heart-pulse"></i> 1. Triage & Vitals</h4>
        <?php if($vitals): ?>
        <div style="display:grid; grid-template-columns: repeat(auto-fit, minmax(120px, 1fr)); gap:10px; font-size:13px;">
            <div><strong>BP:</strong> <?php echo htmlspecialchars($vitals['bp_systolic'].'/'.$vitals['bp_diastolic']); ?> mmHg</div>
            <div><strong>Pulse:</strong> <?php echo htmlspecialchars($vitals['pulse_rate']); ?> bpm</div>
            <div><strong>Temp:</strong> <?php echo htmlspecialchars($vitals['temperature']); ?> °C</div>
            <div><strong>SpO2:</strong> <?php echo htmlspecialchars($vitals['spo2']); ?> %</div>
            <div><strong>Weight:</strong> <?php echo htmlspecialchars($vitals['weight_kg']); ?> kg</div>
        </div>
        <?php else: echo "<span style='color:#64748b; font-size:13px;'>No vitals recorded for this specific encounter.</span>"; endif; ?>
    </div>

    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:8px; padding:15px;">
        <h4 style="margin:0 0 10px 0; color:#1e3a8a; border-bottom:1px solid #e2e8f0; padding-bottom:5px;"><i class="fa-solid fa-clipboard-user"></i> 2. History & Exam</h4>
        <p style="font-size:14px;"><strong>Chief Complaint:</strong><br><?php echo nl2br(htmlspecialchars($note['chief_complaint'] ?? '--')); ?></p>
        <p style="font-size:14px;"><strong>HPI:</strong><br><?php echo nl2br(htmlspecialchars($note['clinical_history'] ?? '--')); ?></p>
        <p style="font-size:14px;"><strong>Examination:</strong><br><?php echo nl2br(htmlspecialchars($note['examination_notes'] ?? '--')); ?></p>
    </div>

    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:8px; padding:15px;">
        <h4 style="margin:0 0 10px 0; color:#1e3a8a; border-bottom:1px solid #e2e8f0; padding-bottom:5px;"><i class="fa-solid fa-user-nurse"></i> 3. Diagnosis & Plan</h4>
        <?php if(!empty($diags)): ?>
            <ul style="margin:0 0 15px 0; padding-left:20px; font-size:14px;">
            <?php foreach($diags as $d): ?>
                <li style="margin-bottom:8px;">
                    <?php if($d['is_principal'] == 1): ?>
                        <span style='color:#dc2626; font-weight:900; font-size:12px; text-transform:uppercase; border:1px solid #dc2626; padding:1px 4px; border-radius:3px; margin-right:5px;'>Principal</span>
                    <?php endif; ?>
                    <strong>[<?php echo htmlspecialchars($d['code']); ?>] - <?php echo htmlspecialchars($d['description']); ?></strong> 
                    <span style="font-size:11px; background:#f1f5f9; padding:2px 6px; border-radius:4px; margin-left:5px; color:#475569;"><?php echo htmlspecialchars($d['diagnosis_type']); ?></span>
                </li>
            <?php endforeach; ?>
            </ul>
        <?php else: echo "<p style='font-size:13px; color:#64748b;'>No formal diagnosis recorded.</p>"; endif; ?>
        
        <p style="font-size:14px;"><strong>Treatment Plan:</strong><br><?php echo nl2br(htmlspecialchars($note['treatment_plan_notes'] ?? '--')); ?></p>
    </div>

    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:8px; padding:15px;">
        <h4 style="margin:0 0 10px 0; color:#1e3a8a; border-bottom:1px solid #e2e8f0; padding-bottom:5px;"><i class="fa-solid fa-pills"></i> 4. Orders, Labs & Rx</h4>
        
        <strong style="font-size:13px; color:#475569;">Medications:</strong>
        <?php if(!empty($rxs)): ?>
            <table style="width:100%; border-collapse:collapse; margin-top:5px; margin-bottom:15px; font-size:13px;">
                <tr style="background:#f8fafc;"><th style="padding:8px; text-align:left;">Drug</th><th style="padding:8px; text-align:left;">Dose/Freq</th><th style="padding:8px; text-align:left;">Duration</th><th style="padding:8px; text-align:left;">Status</th></tr>
                <?php foreach($rxs as $rx): ?>
                <tr>
                    <td style="padding:8px; border-top:1px solid #e2e8f0;"><strong><?php echo htmlspecialchars($rx['drug_name']); ?></strong></td>
                    <td style="padding:8px; border-top:1px solid #e2e8f0;"><?php echo htmlspecialchars($rx['dose'].' - '.$rx['frequency']); ?></td>
                    <td style="padding:8px; border-top:1px solid #e2e8f0;"><?php echo htmlspecialchars($rx['duration_days']); ?> Days</td>
                    <td style="padding:8px; border-top:1px solid #e2e8f0;"><span style="background:#fef3c7; color:#d97706; padding:2px 6px; border-radius:4px; font-size:11px;"><?php echo htmlspecialchars($rx['status']); ?></span></td>
                </tr>
                <?php endforeach; ?>
            </table>
        <?php else: echo "<div style='font-size:13px; color:#64748b; margin-bottom:15px;'>No medications prescribed.</div>"; endif; ?>

        <strong style="font-size:13px; color:#475569;">Investigations & Procedures:</strong>
        <?php if(!empty($labs)): ?>
            <table style="width:100%; border-collapse:collapse; margin-top:5px; margin-bottom:15px; font-size:13px;">
                <tr style="background:#f8fafc;"><th style="padding:8px; text-align:left;">Test Name</th><th style="padding:8px; text-align:left;">Status</th></tr>
                <?php foreach($labs as $lab): ?>
                <tr>
                    <td style="padding:8px; border-top:1px solid #e2e8f0;"><strong><?php echo htmlspecialchars($lab['test_name']); ?></strong></td>
                    <td style="padding:8px; border-top:1px solid #e2e8f0;"><span style="background:#e0f2fe; color:#0369a1; padding:2px 6px; border-radius:4px; font-size:11px; font-weight:bold;"><?php echo htmlspecialchars($lab['status']); ?></span></td>
                </tr>
                <?php endforeach; ?>
            </table>
        <?php else: echo "<div style='font-size:13px; color:#64748b; padding-top:5px;'>No labs or procedures ordered.</div>"; endif; ?>
    </div>

    <div style="background:#fff; border:1px solid #e2e8f0; border-radius:8px; padding:15px;">
        <h4 style="margin:0 0 10px 0; color:#1e3a8a; border-bottom:1px solid #e2e8f0; padding-bottom:5px;"><i class="fa-solid fa-door-open"></i> 5. Outcome & Tracking</h4>
        
        <div style="display:flex; gap:30px; flex-wrap:wrap;">
            <div>
                <p style="font-size:12px; color:#64748b; margin-bottom:2px; text-transform:uppercase; font-weight:bold;">Clinical Outcome</p>
                <p style="font-size:15px; font-weight:bold; color:#0f172a; margin-top:0;"><?php echo htmlspecialchars($visit['clinical_outcome'] ?? 'Pending'); ?></p>
            </div>
            
            <div>
                <p style="font-size:12px; color:#64748b; margin-bottom:2px; text-transform:uppercase; font-weight:bold;">Encounter Status</p>
                <p style="margin-top:0;"><span style="background:#dcfce7; color:#166534; padding:3px 8px; border-radius:12px; font-weight:bold; font-size:12px;"><?php echo htmlspecialchars($visit['status']); ?></span></p>
            </div>

            <div style="border-left:2px solid #e2e8f0; padding-left:30px;">
                <p style="font-size:12px; color:#b45309; margin-bottom:2px; text-transform:uppercase; font-weight:bold;"><i class="fa-regular fa-calendar-check"></i> Next Scheduled Review</p>
                <p style="font-size:15px; font-weight:bold; color:#b45309; margin-top:0;">
                    <?php 
                        if (!empty($visit['next_review_date'])) {
                            echo date('l, d F Y', strtotime($visit['next_review_date']));
                        } else {
                            echo "<span style='color:#94a3b8; font-weight:normal;'>No Review Scheduled</span>";
                        }
                    ?>
                </p>
            </div>
        </div>
    </div>

</div>