<?php
ob_start();

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

/* ================= SESSION ================= */
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

include_once('includes/db.php');

/* ================= Auto Logout ================= */
$timeout_duration = 43200;

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY']) > $timeout_duration) {
    session_unset();
    session_destroy();
    header("Location: login.php?timeout=1");
    exit;
}

$_SESSION['LAST_ACTIVITY'] = time();

/* ================= Check Login ================= */
if (!isset($_SESSION['user_id'])) {
    echo '<div class="alert alert-danger">Please login to access this page.</div>';
    exit;
}

/* ================= ACCESS CONTROL - ALLOW NURSE ================= */
$user_role = $_SESSION['user_role'] ?? '';
$allowed_roles = ['Super_admin', 'Admin', 'Doctor', 'Dentist', 'Nurse'];

if (!in_array($user_role, $allowed_roles)) {
    echo '<div class="alert alert-danger">You do not have permission to access history.</div>';
    exit;
}

/* ================= Get Parameters ================= */
$visit_id = (int)($_GET['visit_id'] ?? 0);
$section = $_GET['section'] ?? '';

if (!$visit_id || !$section) {
    echo '<div class="alert alert-danger">Missing parameters.</div>';
    exit;
}

/* ================= Check if User Has Access ================= */
if (!isset($_SESSION['facility_id'])) {
    echo '<div class="alert alert-danger">Facility not set.</div>';
    exit;
}

$facility_id = (int) $_SESSION['facility_id'];

// Check if user has access to this visit
$stmt = $pdo->prepare("SELECT v.*, d.name AS department_name FROM visits v LEFT JOIN departments d ON v.department_id = d.id WHERE v.id = ?");
$stmt->execute([$visit_id]);
$visit = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$visit) {
    echo '<div class="alert alert-danger">Visit not found.</div>';
    exit;
}

if ($_SESSION['user_role'] !== 'Super_admin' && $facility_id != $visit['facility_id']) {
    echo '<div class="alert alert-danger">Unauthorized access.</div>';
    exit;
}

/* ================= DEPARTMENT CHECK - NURSE CAN ACCESS ALL ================= */
// Nurses can access all visits regardless of department
// Only Doctors and Dentists are department-restricted
$department_restricted_roles = ['Doctor', 'Dentist']; // Nurse NOT included

if (in_array($user_role, $department_restricted_roles)) {
    // Get the user's department
    $stmt = $pdo->prepare("SELECT department_id FROM users WHERE id = ?");
    $stmt->execute([$_SESSION['user_id']]);
    $user_department_id = $stmt->fetchColumn();
    
    // If user has a department and visit has a department, they must match
    if ($user_department_id && $visit['department_id'] && $user_department_id != $visit['department_id']) {
        echo '<div class="alert alert-danger">You don\'t have permission to view visits from this department.</div>';
        exit;
    }
}

/* ================= Fetch Visit Ticket ================= */
$stmt = $pdo->prepare("SELECT * FROM visit_tickets WHERE visit_id = ? LIMIT 1");
$stmt->execute([$visit_id]);
$ticket = $stmt->fetch(PDO::FETCH_ASSOC);

if (!$ticket) {
    echo '<div class="alert alert-info">No ticket found for this visit.</div>';
    exit;
}

$ticket_id = $ticket['id'];

/* ================= Section Names ================= */
$sectionNames = [
    'catchment' => 'Catchment Area / New Case',
    'vital_signs' => 'Vital Signs',
    'chief_complaints' => 'Chief Complaints',
    'physical_examination' => 'Physical Examination',
    'differential_diagnosis' => 'Differential Diagnosis',
    'lab_orders' => 'Lab Orders',
    'imaging_reports' => 'Imaging Reports',
    'final_diagnoses' => 'Final Diagnoses',
    'other_management' => 'Other Management',
    'hmis_report' => 'HMIS Report'
];

/* ================= Fetch History Data ================= */
function formatDate($date) {
    return date('M d, Y H:i:s', strtotime($date));
}

function getUserInfo($user_id, $pdo) {
    if (!$user_id) return ['username' => 'System', 'user_role' => 'System'];
    $stmt = $pdo->prepare("SELECT username, user_role FROM users WHERE id = ?");
    $stmt->execute([$user_id]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
    return $user ?: ['username' => 'Unknown User', 'user_role' => 'Unknown'];
}

// Check if history table exists
$historyTableExists = false;
try {
    $stmt = $pdo->query("SHOW TABLES LIKE 'visit_ticket_history'");
    $historyTableExists = $stmt->rowCount() > 0;
} catch (PDOException $e) {
    $historyTableExists = false;
}

/* ================= Display History ================= */
echo '<div class="history-container">';
echo '<h5 class="mb-3"><i class="icon-history"></i> ' . ($sectionNames[$section] ?? ucfirst(str_replace('_', ' ', $section))) . ' - History</h5>';

if ($historyTableExists) {
    // Fetch history from audit table with user details
    $stmt = $pdo->prepare("
        SELECT h.*, u.username, u.user_role 
        FROM visit_ticket_history h
        LEFT JOIN users u ON h.changed_by = u.id
        WHERE h.visit_ticket_id = ? AND h.section = ?
        ORDER BY h.changed_at DESC
        LIMIT 50
    ");
    $stmt->execute([$ticket_id, $section]);
    $history = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (!empty($history)) {
        echo '<div class="table-responsive">';
        echo '<table class="table table-sm table-bordered table-hover">';
        echo '<thead class="thead-light">';
        echo '<tr>';
        echo '<th width="20%">Date & Time</th>';
        echo '<th width="20%">Changed By</th>';
        echo '<th width="25%">Previous Value</th>';
        echo '<th width="25%">New Value</th>';
        echo '<th width="10%">Action</th>';
        echo '</tr>';
        echo '</thead>';
        echo '<tbody>';
        
        foreach ($history as $record) {
            $userInfo = $record['username'] 
                ? ['username' => $record['username'], 'user_role' => $record['user_role']]
                : getUserInfo($record['changed_by'], $pdo);
            
            // Get role badge color
            $roleBadgeClass = 'badge-secondary';
            $userRole = strtolower($userInfo['user_role'] ?? '');
            
            if (strpos($userRole, 'admin') !== false) $roleBadgeClass = 'badge-danger';
            elseif (strpos($userRole, 'doctor') !== false) $roleBadgeClass = 'badge-primary';
            elseif (strpos($userRole, 'nurse') !== false) $roleBadgeClass = 'badge-info';
            elseif (strpos($userRole, 'lab') !== false) $roleBadgeClass = 'badge-warning';
            else $roleBadgeClass = 'badge-secondary';
            
            echo '<tr>';
            echo '<td><small class="text-muted">' . formatDate($record['changed_at']) . '</small></td>';
            echo '<td>';
            echo '<div><strong>' . htmlspecialchars($userInfo['username']) . '</strong></div>';
            echo '<small><span class="badge ' . $roleBadgeClass . '">' . htmlspecialchars($userInfo['user_role']) . '</span></small>';
            echo '</td>';
            
            // Format and display values based on section type
            echo '<td class="lab-history-cell">' . formatHistoryValue($section, $record['old_value'], $pdo, $ticket_id, $facility_id, true) . '</td>';
            echo '<td class="lab-history-cell">' . formatHistoryValue($section, $record['new_value'], $pdo, $ticket_id, $facility_id, false) . '</td>';
            
            // Action column - Delete button for Super_admin only
            echo '<td class="text-center">';
            if ($user_role === 'Super_admin') {
                echo '<button class="btn btn-sm btn-danger delete-history-btn" data-id="' . $record['id'] . '" title="Delete this history record">';
                echo '<i class="icon-trash2"></i>';
                echo '</button>';
            } else {
                echo '<span class="text-muted">—</span>';
            }
            echo '</td>';
            
            echo '</tr>';
        }
        
        echo '</tbody>';
        echo '</table>';
        echo '</div>';
        
        // Summary
        echo '<div class="mt-3 text-muted">';
        echo '<small><i class="icon-info"></i> Showing ' . count($history) . ' most recent changes</small>';
        echo '</div>';
        
        // Add JavaScript for delete functionality (only for Super_admin)
        if ($user_role === 'Super_admin') {
            echo '
            <script>
            document.addEventListener("DOMContentLoaded", function() {
                var deleteButtons = document.querySelectorAll(".delete-history-btn");
                deleteButtons.forEach(function(button) {
                    button.addEventListener("click", function() {
                        var historyId = this.getAttribute("data-id");
                        if (confirm("Are you sure you want to delete this history record? This action cannot be undone.")) {
                            // Create a form and submit via POST
                            var form = document.createElement("form");
                            form.method = "POST";
                            form.action = "delete_history.php"; // You need to create this file
                            
                            var csrfInput = document.createElement("input");
                            csrfInput.type = "hidden";
                            csrfInput.name = "csrf_token";
                            csrfInput.value = "' . $_SESSION['csrf_token'] ?? '' . '";
                            form.appendChild(csrfInput);
                            
                            var idInput = document.createElement("input");
                            idInput.type = "hidden";
                            idInput.name = "history_id";
                            idInput.value = historyId;
                            form.appendChild(idInput);
                            
                            var sectionInput = document.createElement("input");
                            sectionInput.type = "hidden";
                            sectionInput.name = "section";
                            sectionInput.value = "' . $section . '";
                            form.appendChild(sectionInput);
                            
                            var visitInput = document.createElement("input");
                            visitInput.type = "hidden";
                            visitInput.name = "visit_id";
                            visitInput.value = "' . $visit_id . '";
                            form.appendChild(visitInput);
                            
                            document.body.appendChild(form);
                            form.submit();
                        }
                    });
                });
            });
            </script>
            ';
        }
    } else {
        echo '<div class="alert alert-info">';
        echo '<i class="icon-info"></i> No history found for this section.';
        echo '</div>';
    }
} else {
    // History table doesn't exist
    echo '<div class="alert alert-warning">';
    echo '<h6><i class="icon-alert-triangle"></i> History Tracking Not Enabled</h6>';
    echo '<p>History tracking requires the <code>visit_ticket_history</code> table to be created in the database.</p>';
    echo '<p class="mb-0">Please contact your system administrator to enable audit logging.</p>';
    echo '</div>';
    
    // Show current data
    echo '<h6 class="mt-4"><i class="icon-eye"></i> Current Data:</h6>';
    echo '<div class="current-data p-3 bg-light rounded">';
    displayCurrentData($section, $ticket, $pdo, $ticket_id, $facility_id);
    echo '</div>';
}

echo '</div>'; // End history-container

ob_end_flush();

/* ================= Helper Functions ================= */

function getLabTestDetails($lab_order_id, $pdo) {
    $stmt = $pdo->prepare("
        SELECT lo.*, p.name AS lab_name, 
               lt.sub_tests AS sub_tests_json,
               pr.category_id AS lab_test_category_id
        FROM lab_orders lo
        JOIN products p ON lo.product_id = p.id
        LEFT JOIN products pr ON pr.id = lo.product_id
        LEFT JOIN lab_test lt ON lt.id = pr.category_id
        WHERE lo.id = ?
    ");
    $stmt->execute([$lab_order_id]);
    $labOrder = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$labOrder) {
        return null;
    }
    
    // Parse sub_tests
    $subTests = [];
    if (!empty($labOrder['sub_tests_json'])) {
        $subTests = json_decode($labOrder['sub_tests_json'], true);
        if (!$subTests) {
            $subTests = [];
        }
    }
    
    // Parse result_value
    $resultValue = $labOrder['result_value'] ?? '';
    $resultArray = [];
    if (!empty($resultValue)) {
        $decoded = json_decode($resultValue, true);
        $resultArray = $decoded !== null ? $decoded : ['value' => $resultValue];
    }
    
    return [
        'id' => $labOrder['id'],
        'lab_name' => $labOrder['lab_name'],
        'product_id' => $labOrder['product_id'],
        'status' => $labOrder['status'],
        'sub_tests' => $subTests,
        'result_value' => $resultArray
    ];
}

function formatHistoryValue($section, $value, $pdo, $ticket_id, $facility_id, $isOldValue = true) {
    if (empty($value) || $value === 'null') {
        return '<em class="text-muted">Empty</em>';
    }
    
    // Try to decode JSON first
    $decoded = json_decode($value, true);
    if ($decoded !== null) {
        return formatJsonValue($section, $decoded, $pdo, $ticket_id, $facility_id, $isOldValue);
    }
    
    // For plain text
    $value = htmlspecialchars($value);
    
    // Special formatting for certain sections
    switch ($section) {
        case 'chief_complaints':
        case 'physical_examination':
        case 'differential_diagnosis':
        case 'other_management':
        case 'vital_comment':
            return '<div style="max-height: 100px; overflow-y: auto; font-size: 14px;">' . nl2br($value) . '</div>';
        default:
            return '<span style="font-size: 14px;">' . $value . '</span>';
    }
}

function formatJsonValue($section, $data, $pdo, $ticket_id, $facility_id, $isOldValue = true) {
    if (!is_array($data)) {
        return '<span style="font-size: 14px;">' . htmlspecialchars((string)$data) . '</span>';
    }
    
    $output = '';
    
    switch ($section) {
        case 'catchment':
            foreach ($data as $key => $value) {
                $label = ucfirst(str_replace('_', ' ', $key));
                $output .= "<div style='font-size: 14px;'><strong>{$label}:</strong> " . htmlspecialchars($value) . "</div>";
            }
            break;
            
        case 'vital_signs':
            $vitalLabels = [
                'systolic' => 'Systolic',
                'diastolic' => 'Diastolic', 
                'heart_rate' => 'Heart Rate',
                'temperature' => 'Temperature',
                'resp_rate' => 'Resp. Rate',
                'spo2' => 'SpO2',
                'weight' => 'Weight',
                'height' => 'Height',
                'vital_comment' => 'Comment'
            ];
            
            foreach ($data as $key => $value) {
                if (!empty($value) || $value === '0') {
                    $label = $vitalLabels[$key] ?? ucfirst(str_replace('_', ' ', $key));
                    $output .= "<div style='font-size: 14px;'><strong>{$label}:</strong> " . htmlspecialchars($value) . "</div>";
                }
            }
            break;
            
        case 'lab_orders':
            // Check if this is the format with only previous/current lab info (not the full changes format)
            if (isset($data['previous_lab_names']) && !isset($data['lab_changes'])) {
                // This is a simplified format with just previous lab info
                $output .= '<div class="lab-history-display" style="font-size: 14px;">';
                
                if (isset($data['previous_lab_names']) && !empty($data['previous_lab_names'])) {
                    $output .= '<div>';
                    $output .= '<strong>Labs (' . ($data['previous_lab_count'] ?? count($data['previous_lab_names'])) . '):</strong>';
                    $output .= '<ul class="mb-0 pl-3" style="font-size: 14px;">';
                    foreach ($data['previous_lab_names'] as $labName) {
                        $output .= '<li>' . htmlspecialchars($labName) . '</li>';
                    }
                    $output .= '</ul>';
                    $output .= '</div>';
                } else {
                    $output .= '<div><strong>Labs:</strong> None</div>';
                }
                
                $output .= '</div>';
            }
            // Check if this is the new format with lab_changes array
            elseif (isset($data['lab_changes']) && is_array($data['lab_changes'])) {
                $output .= '<div class="lab-history-display" style="font-size: 14px;">';
                
                // If $isOldValue is TRUE, this is the "Previous Value" column
                if ($isOldValue) {
                    // Show previous labs for "Previous Value" column
                    if (isset($data['previous_lab_names']) && !empty($data['previous_lab_names'])) {
                        $output .= '<div class="mb-2">';
                        $output .= '<strong>Previous Labs (' . ($data['previous_lab_count'] ?? count($data['previous_lab_names'])) . '):</strong>';
                        $output .= '<ul class="mb-1 pl-3" style="font-size: 14px;">';
                        foreach ($data['previous_lab_names'] as $labName) {
                            $output .= '<li>' . htmlspecialchars($labName) . '</li>';
                        }
                        $output .= '</ul>';
                        $output .= '</div>';
                    } else {
                        $output .= '<div class="mb-2"><strong>Previous Labs:</strong> None</div>';
                    }
                } 
                // If $isOldValue is FALSE, this is the "New Value" column
                else {
                    // Show changes for "New Value" column
                    if (!empty($data['lab_changes'])) {
                        $output .= '<div>';
                        $output .= '<strong>Changes:</strong>';
                        foreach ($data['lab_changes'] as $change) {
                            $action = $change['action'] ?? '';
                            $labName = $change['lab_name'] ?? '';
                            $labId = $change['lab_id'] ?? '';
                            
                            $badgeClass = 'badge-secondary';
                            if ($action === 'added') $badgeClass = 'badge-success';
                            elseif ($action === 'deleted') $badgeClass = 'badge-danger';
                            elseif ($action === 'updated') $badgeClass = 'badge-info';
                            
                            $output .= '<div class="mt-1" style="font-size: 14px;">';
                            $output .= '<span class="badge ' . $badgeClass . '">' . htmlspecialchars($action) . '</span> ';
                            $output .= htmlspecialchars($labName);
                            if ($labId) {
                                $output .= ' <span class="text-muted">(ID: ' . htmlspecialchars($labId) . ')</span>';
                            }
                            $output .= '</div>';
                        }
                        $output .= '</div>';
                    }
                    
                    // Show current labs for "New Value" column
                    if (isset($data['current_lab_names']) && !empty($data['current_lab_names'])) {
                        $output .= '<div class="mt-2">';
                        $output .= '<strong>Current Labs (' . ($data['current_lab_count'] ?? count($data['current_lab_names'])) . '):</strong>';
                        $output .= '<ul class="mb-0 pl-3" style="font-size: 14px;">';
                        foreach ($data['current_lab_names'] as $labName) {
                            $output .= '<li>' . htmlspecialchars($labName) . '</li>';
                        }
                        $output .= '</ul>';
                        $output .= '</div>';
                    } else {
                        $output .= '<div class="mt-2"><strong>Current Labs:</strong> None</div>';
                    }
                }
                
                $output .= '</div>';
            }
            // Check for action format (old format)
            elseif (isset($data['action'])) {
                $action = $data['action'];
                $labOrderId = $data['lab_order_id'] ?? null;
                
                $output .= '<div style="font-size: 14px;">';
                
                if ($action === 'added' && $labOrderId) {
                    $labDetails = getLabTestDetails($labOrderId, $pdo);
                    if ($labDetails) {
                        $output .= '<span class="badge badge-success">Added</span> ';
                        $output .= '<strong>' . htmlspecialchars($labDetails['lab_name']) . '</strong>';
                        
                        // Show sub-tests if available
                        if (!empty($labDetails['sub_tests'])) {
                            $output .= '<div class="mt-2"><strong>Sub-tests:</strong>';
                            $output .= '<table class="table table-sm table-borderless mb-0" style="font-size: 14px;">';
                            foreach ($labDetails['sub_tests'] as $subTest) {
                                $subTestName = $subTest['name'] ?? '';
                                $resultValue = $labDetails['result_value'][$subTestName] ?? '';
                                
                                $output .= '<tr>';
                                $output .= '<td width="40%">' . htmlspecialchars($subTestName) . '</td>';
                                $output .= '<td width="60%">' . htmlspecialchars($resultValue) . '</td>';
                                $output .= '</tr>';
                            }
                            $output .= '</table>';
                            $output .= '</div>';
                        } elseif (!empty($labDetails['result_value'])) {
                            $output .= '<div class="mt-1"><strong>Result:</strong> ' . htmlspecialchars($labDetails['result_value']['value'] ?? $labDetails['result_value']) . '</div>';
                        }
                    } else {
                        $output .= '<span class="badge badge-success">Added</span> Lab Order #' . htmlspecialchars($labOrderId);
                    }
                } elseif ($action === 'deleted' && $labOrderId) {
                    $output .= '<span class="badge badge-danger">Deleted</span> Lab Order #' . htmlspecialchars($labOrderId);
                } elseif ($action === 'updated' && $labOrderId) {
                    $labDetails = getLabTestDetails($labOrderId, $pdo);
                    if ($labDetails) {
                        $output .= '<span class="badge badge-info">Updated</span> ';
                        $output .= '<strong>' . htmlspecialchars($labDetails['lab_name']) . '</strong>';
                        
                        // Show updated results
                        if (!empty($labDetails['result_value'])) {
                            $output .= '<div class="mt-1"><strong>Updated Result:</strong>';
                            if (is_array($labDetails['result_value'])) {
                                foreach ($labDetails['result_value'] as $key => $value) {
                                    $output .= '<div>' . htmlspecialchars($key) . ': ' . htmlspecialchars($value) . '</div>';
                                }
                            } else {
                                $output .= '<div>' . htmlspecialchars($labDetails['result_value']) . '</div>';
                            }
                            $output .= '</div>';
                        }
                    } else {
                        $output .= '<span class="badge badge-info">Updated</span> Lab Order #' . htmlspecialchars($labOrderId);
                    }
                } elseif ($action === 'no_lab_order') {
                    $output .= '<em class="text-muted">No lab order</em>';
                } else {
                    $output .= '<span class="badge badge-secondary">' . htmlspecialchars($action) . '</span> ';
                    if ($labOrderId) {
                        $output .= 'Lab Order #' . htmlspecialchars($labOrderId);
                    }
                }
                
                $output .= '</div>';
            }
            // Check for lab_test_ids format
            elseif (isset($data['lab_test_ids'])) {
                $labTestIds = $data['lab_test_ids'];
                if (is_array($labTestIds) && !empty($labTestIds)) {
                    $output .= '<div style="font-size: 14px;">';
                    $output .= '<strong>' . count($labTestIds) . ' lab test(s)</strong>';
                    
                    // Fetch lab test names
                    $placeholders = implode(',', array_fill(0, count($labTestIds), '?'));
                    $stmt = $pdo->prepare("SELECT id, name FROM products WHERE id IN ($placeholders)");
                    $stmt->execute($labTestIds);
                    $labTests = $stmt->fetchAll(PDO::FETCH_ASSOC);
                    
                    if (!empty($labTests)) {
                        $output .= '<ul class="mb-0 pl-3">';
                        foreach ($labTests as $test) {
                            $output .= '<li>' . htmlspecialchars($test['name']) . '</li>';
                        }
                        $output .= '</ul>';
                    }
                    $output .= '</div>';
                } else {
                    $output .= '<em class="text-muted" style="font-size: 14px;">No lab tests</em>';
                }
            }
            // Generic JSON display for other formats
            else {
                $output .= '<pre class="mb-0 small" style="font-size: 13px;">' . htmlspecialchars(json_encode($data, JSON_PRETTY_PRINT)) . '</pre>';
            }
            break;
            
        case 'imaging_reports':
            if (isset($data[0])) { // Multiple reports
                $output .= '<div style="font-size: 14px;">';
                $output .= '<strong>' . count($data) . ' report(s)</strong>';
                foreach ($data as $index => $report) {
                    $output .= '<div class="border-top pt-1 mt-1">';
                    $output .= '<strong>Report ' . ($index + 1) . ':</strong><br>';
                    $output .= '<strong>Type:</strong> ' . htmlspecialchars($report['type'] ?? '') . '<br>';
                    if (!empty($report['report'])) {
                        $output .= '<strong>Report:</strong> ' . htmlspecialchars(substr($report['report'], 0, 100)) . (strlen($report['report']) > 100 ? '...' : '') . '<br>';
                    }
                    if (!empty($report['recommendation'])) {
                        $output .= '<strong>Recommendation:</strong> ' . htmlspecialchars(substr($report['recommendation'], 0, 100)) . (strlen($report['recommendation']) > 100 ? '...' : '') . '';
                    }
                    $output .= '</div>';
                }
                $output .= '</div>';
            } else { // Single report or partial data
                foreach ($data as $key => $value) {
                    $label = ucfirst($key);
                    $output .= "<div style='font-size: 14px;'><strong>{$label}:</strong> " . htmlspecialchars($value) . "</div>";
                }
            }
            break;
            
        case 'final_diagnoses':
            if (isset($data['titles']) || isset($data['codes']) || isset($data['comments'])) {
                // This is from the new logging format
                $titles = $data['titles'] ?? [];
                $codes = $data['codes'] ?? [];
                $comments = $data['comments'] ?? [];
                
                $count = max(count($titles), count($codes), count($comments));
                if ($count > 0) {
                    $output .= '<div style="font-size: 14px;">';
                    $output .= '<strong>' . $count . ' diagnosis(es)</strong>';
                    for ($i = 0; $i < $count; $i++) {
                        $hasData = !empty($titles[$i]) || !empty($codes[$i]) || !empty($comments[$i]);
                        if ($hasData) {
                            $output .= '<div class="border-top pt-1 mt-1">';
                            if (!empty($titles[$i])) $output .= '<div><strong>Title:</strong> ' . htmlspecialchars($titles[$i]) . '</div>';
                            if (!empty($codes[$i])) $output .= '<div><strong>Code:</strong> ' . htmlspecialchars($codes[$i]) . '</div>';
                            if (!empty($comments[$i])) $output .= '<div><strong>Comment:</strong> ' . htmlspecialchars($comments[$i]) . '</div>';
                            $output .= '</div>';
                        }
                    }
                    $output .= '</div>';
                } else {
                    $output .= '<em class="text-muted" style="font-size: 14px;">No diagnoses</em>';
                }
            } else {
                // Old format or other data
                $output .= '<pre class="mb-0 small" style="font-size: 13px;">' . htmlspecialchars(json_encode($data, JSON_PRETTY_PRINT)) . '</pre>';
            }
            break;
            
        case 'hmis_report':
            if (is_array($data) && !empty($data)) {
                $output .= '<div style="font-size: 14px;">';
                $output .= '<strong>' . count($data) . ' indicator(s)</strong>';
                
                // Fetch indicator names
                $placeholders = implode(',', array_fill(0, count($data), '?'));
                $stmt = $pdo->prepare("
                    SELECT hi.id, hi.indicator_name, hc.name AS category_name
                    FROM hmis_indicators hi
                    JOIN hmis_category hc ON hi.category_id = hc.id
                    WHERE hi.id IN ($placeholders)
                    LIMIT 5
                ");
    $stmt->execute($data);
    $indicators = $stmt->fetchAll(PDO::FETCH_ASSOC);
    
    if (!empty($indicators)) {
        $output .= '<ul class="mb-0 pl-3">';
        foreach ($indicators as $indicator) {
            $output .= '<li>' . htmlspecialchars($indicator['indicator_name']) . ' <span class="text-muted">(' . htmlspecialchars($indicator['category_name']) . ')</span></li>';
        }
        if (count($data) > 5) {
            $output .= '<li><span class="text-muted">... and ' . (count($data) - 5) . ' more</span></li>';
        }
        $output .= '</ul>';
    }
    $output .= '</div>';
} else {
    $output .= '<em class="text-muted" style="font-size: 14px;">No indicators</em>';
}
break;

default:
    $output .= '<pre class="mb-0 small" style="font-size: 13px;">' . htmlspecialchars(json_encode($data, JSON_PRETTY_PRINT)) . '</pre>';
    break;
}

return $output ?: '<em class="text-muted" style="font-size: 14px;">Empty</em>';
}

function displayCurrentData($section, $ticket, $pdo, $ticket_id, $facility_id) {
switch ($section) {
    case 'catchment':
        echo '<p style="font-size: 14px;"><strong>Catchment Area:</strong> ' . htmlspecialchars($ticket['catchment_area'] ?? 'Not set') . '</p>';
        echo '<p style="font-size: 14px;"><strong>New Case:</strong> ' . htmlspecialchars($ticket['new_case'] ?? 'Not set') . '</p>';
        break;
        
    case 'vital_signs':
        $vitals = [
            'Systolic' => $ticket['systolic'] ?? null,
            'Diastolic' => $ticket['diastolic'] ?? null,
            'Heart Rate' => $ticket['heart_rate'] ?? null,
            'Temperature' => $ticket['temperature'] ?? null,
            'Resp. Rate' => $ticket['resp_rate'] ?? null,
            'SpO2 (%)' => $ticket['spo2'] ?? null,
            'Weight (kg)' => $ticket['weight'] ?? null,
            'Height (cm)' => $ticket['height'] ?? null,
            'Comment' => $ticket['vital_comment'] ?? null
        ];
        
        foreach ($vitals as $label => $value) {
            if ($value !== null) {
                echo '<p style="font-size: 14px;"><strong>' . $label . ':</strong> ' . htmlspecialchars($value) . '</p>';
            }
        }
        break;
        
    case 'chief_complaints':
        echo '<div style="max-height: 200px; overflow-y: auto; font-size: 14px;">';
        echo nl2br(htmlspecialchars($ticket['chief_complaints'] ?? 'Not set'));
        echo '</div>';
        break;
        
    case 'physical_examination':
        echo '<div style="max-height: 200px; overflow-y: auto; font-size: 14px;">';
        echo nl2br(htmlspecialchars($ticket['physical_examination'] ?? 'Not set'));
        echo '</div>';
        break;
        
    case 'differential_diagnosis':
        echo '<div style="max-height: 200px; overflow-y: auto; font-size: 14px;">';
        echo nl2br(htmlspecialchars($ticket['differential_diagnosis'] ?? 'Not set'));
        echo '</div>';
        break;
        
    case 'lab_orders':
        $stmtLab = $pdo->prepare("
            SELECT lo.*, p.name AS lab_name,
                   pr.category_id AS lab_test_category_id,
                   lt.sub_tests AS sub_tests_json
            FROM lab_orders lo
            JOIN products p ON lo.product_id = p.id
            LEFT JOIN products pr ON pr.id = lo.product_id
            LEFT JOIN lab_test lt ON lt.id = pr.category_id
            WHERE lo.visit_ticket_id = ? AND lo.facility_id = ?
            ORDER BY lo.id
        ");
        $stmtLab->execute([$ticket_id, $facility_id]);
        $labOrders = $stmtLab->fetchAll(PDO::FETCH_ASSOC);
        
        if (!empty($labOrders)) {
            echo '<p style="font-size: 14px;"><strong>Total Lab Orders:</strong> ' . count($labOrders) . '</p>';
            
            foreach ($labOrders as $order) {
                echo '<div class="border p-2 mb-2" style="font-size: 14px;">';
                echo '<p><strong>' . htmlspecialchars($order['lab_name']) . '</strong>';
                echo ' <span class="badge badge-' . ($order['status'] === 'completed' ? 'success' : 'warning') . '">' . htmlspecialchars($order['status']) . '</span>';
                echo '</p>';
                
                // Parse sub_tests
                $subTests = [];
                if (!empty($order['sub_tests_json'])) {
                    $subTests = json_decode($order['sub_tests_json'], true);
                }
                
                // Parse result_value
                $resultValue = $order['result_value'] ?? '';
                $resultArray = [];
                if (!empty($resultValue)) {
                    $decoded = json_decode($resultValue, true);
                    $resultArray = $decoded !== null ? $decoded : ['value' => $resultValue];
                }
                
                if (!empty($subTests)) {
                    echo '<p><strong>Sub-tests:</strong></p>';
                    echo '<table class="table table-sm table-borderless" style="font-size: 14px;">';
                    echo '<thead><tr><th>Test</th><th>Result</th></tr></thead>';
                    echo '<tbody>';
                    foreach ($subTests as $subTest) {
                        $subTestName = $subTest['name'] ?? '';
                        $testResult = $resultArray[$subTestName] ?? '';
                        echo '<tr>';
                        echo '<td>' . htmlspecialchars($subTestName) . '</td>';
                        echo '<td>' . htmlspecialchars($testResult) . '</td>';
                        echo '</tr>';
                    }
                    echo '</tbody>';
                    echo '</table>';
                } elseif (!empty($resultArray)) {
                    echo '<p><strong>Result:</strong> ' . htmlspecialchars($resultArray['value'] ?? $resultArray) . '</p>';
                }
                
                echo '</div>';
            }
        } else {
            echo '<p class="text-muted" style="font-size: 14px;">No lab orders found.</p>';
        }
        break;
        
    case 'imaging_reports':
        $imagingReports = !empty($ticket['imaging_reports']) ? json_decode($ticket['imaging_reports'], true) : [];
        
        if (!empty($imagingReports)) {
            echo '<p style="font-size: 14px;"><strong>Total Imaging Reports:</strong> ' . count($imagingReports) . '</p>';
            foreach ($imagingReports as $index => $report) {
                echo '<div class="border p-2 mb-2" style="font-size: 14px;">';
                echo '<p><strong>Report ' . ($index + 1) . ':</strong></p>';
                echo '<p><strong>Type:</strong> ' . htmlspecialchars($report['type'] ?? '') . '</p>';
                echo '<p><strong>Report:</strong> ' . nl2br(htmlspecialchars($report['report'] ?? '')) . '</p>';
                echo '<p><strong>Recommendation:</strong> ' . nl2br(htmlspecialchars($report['recommendation'] ?? '')) . '</p>';
                echo '</div>';
            }
        } else {
            echo '<p class="text-muted" style="font-size: 14px;">No imaging reports found.</p>';
        }
        break;
        
    case 'final_diagnoses':
        $titles = json_decode($ticket['final_diagnosis_title'] ?? '[]', true) ?: [];
        $codes = json_decode($ticket['final_diagnosis_code'] ?? '[]', true) ?: [];
        $comments = json_decode($ticket['final_diagnosis_comment'] ?? '[]', true) ?: [];
        
        if (!empty($titles) || !empty($codes) || !empty($comments)) {
            $count = max(count($titles), count($codes), count($comments));
            echo '<p style="font-size: 14px;"><strong>Total Diagnoses:</strong> ' . $count . '</p>';
            for ($i = 0; $i < $count; $i++) {
                echo '<div class="border p-2 mb-2" style="font-size: 14px;">';
                echo '<p><strong>Diagnosis ' . ($i + 1) . ':</strong></p>';
                if (!empty($titles[$i])) echo '<p><strong>Title:</strong> ' . htmlspecialchars($titles[$i]) . '</p>';
                if (!empty($codes[$i])) echo '<p><strong>ICD-11 Code:</strong> ' . htmlspecialchars($codes[$i]) . '</p>';
                if (!empty($comments[$i])) echo '<p><strong>Comment:</strong> ' . nl2br(htmlspecialchars($comments[$i])) . '</p>';
                echo '</div>';
            }
        } else {
            echo '<p class="text-muted" style="font-size: 14px;">No final diagnoses found.</p>';
        }
        break;
        
    case 'other_management':
        echo '<div style="max-height: 200px; overflow-y: auto; font-size: 14px;">';
        echo nl2br(htmlspecialchars($ticket['other_management'] ?? 'Not set'));
        echo '</div>';
        break;
        
    case 'hmis_report':
        $hmis_report = !empty($ticket['hmis_report']) ? json_decode($ticket['hmis_report'], true) : [];
        
        if (!empty($hmis_report)) {
            echo '<p style="font-size: 14px;"><strong>Total HMIS Indicators:</strong> ' . count($hmis_report) . '</p>';
            
            $placeholders = implode(',', array_fill(0, count($hmis_report), '?'));
            $stmtHmis = $pdo->prepare("
                SELECT hi.id, hi.indicator_name, hc.name AS category_name
                FROM hmis_indicators hi
                JOIN hmis_category hc ON hi.category_id = hc.id
                WHERE hi.id IN ($placeholders)
            ");
            $stmtHmis->execute($hmis_report);
            $indicators = $stmtHmis->fetchAll(PDO::FETCH_ASSOC);
            
            if (!empty($indicators)) {
                echo '<ul class="list-unstyled" style="font-size: 14px;">';
                foreach ($indicators as $indicator) {
                    echo '<li class="mb-1">';
                    echo '<span class="badge badge-light">' . htmlspecialchars($indicator['category_name']) . '</span> ';
                    echo htmlspecialchars($indicator['indicator_name']);
                    echo '</li>';
                }
                echo '</ul>';
            } else {
                echo '<p class="text-muted" style="font-size: 14px;">HMIS indicator details not found.</p>';
            }
        } else {
            echo '<p class="text-muted" style="font-size: 14px;">No HMIS indicators selected.</p>';
        }
        break;
        
    default:
        echo '<p class="text-muted" style="font-size: 14px;">No data available for this section.</p>';
        break;
}
}
?>