<?php
/**
 * View VNG (Videonystagmography) Test Results
 * Display completed VNG test results including coordination tests
 */

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

if (!isset($_SESSION['user_id'])) {
    header('Location: login.php');
    exit();
}

$test_id = $_GET['test_id'] ?? 0;

if (!$test_id) {
    header('Location: vng_testing.php');
    exit();
}

// Fetch test details
$sql = "SELECT lot.*, tt.test_name, tt.test_code, tt.category,
               lo.order_number, lo.priority, lo.clinical_notes,
               p.patient_id, p.patient_number, 
               u.full_name as patient_name, u.gender, u.date_of_birth,
               du.full_name as doctor_name,
               tu.full_name as technician_name
        FROM lab_order_tests lot
        INNER JOIN lab_orders lo ON lot.order_id = lo.order_id
        INNER JOIN ent_test_types tt ON lot.test_type_id = tt.test_type_id
        INNER JOIN patients p ON lo.patient_id = p.patient_id
        INNER JOIN users u ON p.user_id = u.user_id
        LEFT JOIN doctors d ON lo.ordered_by = d.doctor_id
        LEFT JOIN users du ON d.user_id = du.user_id
        LEFT JOIN users tu ON lot.tested_by = tu.user_id
        WHERE lot.order_test_id = ? AND (tt.test_name LIKE '%VNG%' OR tt.test_code LIKE '%VNG%')";

$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $test_id);
$stmt->execute();
$test = $stmt->get_result()->fetch_assoc();

if (!$test) {
    die("VNG test not found");
}

// Parse results
$results = [];
if ($test['result_value']) {
    $results = json_decode($test['result_value'], true) ?? [];
}

// Calculate patient age
$age = null;
if ($test['date_of_birth']) {
    $dob = new DateTime($test['date_of_birth']);
    $now = new DateTime();
    $age = $now->diff($dob)->y;
}

$page_title = "VNG Test Results";
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => $page_title)); ?>
    <?php include 'layouts/head-css.php'; ?>
    
    <style>
        .patient-info-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }
        
        .result-section {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
            box-shadow: 0 1px 3px 0 rgba(0, 0, 0, 0.1);
            border: 1px solid #e2e8f0;
        }
        
        .result-section h5 {
            color: #1e293b;
            font-weight: 600;
            margin-bottom: 1.25rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .result-section h6 {
            color: #475569;
            font-weight: 600;
            margin-top: 1rem;
            margin-bottom: 0.75rem;
        }
        
        .coordination-section {
            background: #f0f9ff;
            border-left: 4px solid #0ea5e9;
            padding: 1.5rem;
            border-radius: 8px;
            margin-top: 1.5rem;
        }
        
        .result-value {
            background: #f8fafc;
            padding: 0.75rem;
            border-radius: 6px;
            border-left: 3px solid #667eea;
            margin-bottom: 0.5rem;
        }
        
        .result-label {
            font-weight: 600;
            color: #475569;
            font-size: 0.875rem;
            margin-bottom: 0.25rem;
        }
        
        .result-text {
            color: #1e293b;
        }
        
        .badge-status {
            padding: 0.5rem 1rem;
            border-radius: 6px;
            font-weight: 500;
        }
        
        .badge-normal {
            background: #d1fae5;
            color: #065f46;
        }
        
        .badge-abnormal {
            background: #fee2e2;
            color: #991b1b;
        }
        
        .badge-borderline {
            background: #fef3c7;
            color: #92400e;
        }
        
        .print-section {
            display: none;
        }
        
        @media print {
            .no-print {
                display: none !important;
            }
            .print-section {
                display: block;
            }
        }
    </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 Title -->
                    <div class="row">
                        <div class="col-12">
                            <div class="page-title-box d-sm-flex align-items-center justify-content-between">
                                <h4 class="mb-sm-0"><?php echo $page_title; ?></h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="index.php">Dashboard</a></li>
                                        <li class="breadcrumb-item"><a href="vng_testing.php">VNG Testing</a></li>
                                        <li class="breadcrumb-item active">View Results</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Patient Information -->
                    <div class="patient-info-card">
                        <div class="row">
                            <div class="col-md-6">
                                <h5 class="mb-3"><i class="ri-user-line me-2"></i>Patient Information</h5>
                                <p class="mb-1"><strong>Name:</strong> <?php echo htmlspecialchars($test['patient_name']); ?></p>
                                <p class="mb-1"><strong>Patient #:</strong> <?php echo htmlspecialchars($test['patient_number']); ?></p>
                                <p class="mb-1"><strong>Age:</strong> <?php echo $age !== null ? $age . ' years' : 'N/A'; ?></p>
                                <p class="mb-0"><strong>Gender:</strong> <?php echo htmlspecialchars($test['gender'] ?? 'N/A'); ?></p>
                            </div>
                            <div class="col-md-6">
                                <h5 class="mb-3"><i class="ri-file-list-line me-2"></i>Test Information</h5>
                                <p class="mb-1"><strong>Test:</strong> <?php echo htmlspecialchars($test['test_name']); ?></p>
                                <p class="mb-1"><strong>Order #:</strong> <?php echo htmlspecialchars($test['order_number']); ?></p>
                                <p class="mb-1"><strong>Status:</strong> 
                                    <span class="badge bg-<?php echo $test['status'] == 'COMPLETED' ? 'success' : 'warning'; ?>">
                                        <?php echo htmlspecialchars($test['status']); ?>
                                    </span>
                                </p>
                                <p class="mb-1"><strong>Abnormal Flag:</strong> 
                                    <span class="badge-status badge-<?php echo strtolower($test['abnormal_flag'] ?? 'normal'); ?>">
                                        <?php echo htmlspecialchars($test['abnormal_flag'] ?? 'NORMAL'); ?>
                                    </span>
                                </p>
                                <?php if ($test['completed_at']): ?>
                                    <p class="mb-0"><strong>Completed:</strong> <?php echo date('M d, Y g:i A', strtotime($test['completed_at'])); ?></p>
                                <?php endif; ?>
                                <?php if ($test['technician_name']): ?>
                                    <p class="mb-0"><strong>Tested By:</strong> <?php echo htmlspecialchars($test['technician_name']); ?></p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Action Buttons -->
                    <div class="row mb-3 no-print">
                        <div class="col-12">
                            <div class="d-flex justify-content-between">
                                <a href="vng_testing.php" class="btn btn-outline-secondary">
                                    <i class="ri-arrow-left-line me-2"></i>Back to VNG Tests
                                </a>
                                <div>
                                    <?php if ($test['status'] == 'IN_PROGRESS'): ?>
                                        <a href="record_vng_results.php?test_id=<?php echo $test_id; ?>" class="btn btn-primary">
                                            <i class="ri-edit-line me-2"></i>Edit Results
                                        </a>
                                    <?php endif; ?>
                                    <button onclick="window.print()" class="btn btn-info">
                                        <i class="ri-printer-line me-2"></i>Print Results
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <?php if (empty($results)): ?>
                        <div class="alert alert-warning">
                            <i class="ri-alert-line me-2"></i>No test results available yet.
                        </div>
                    <?php else: ?>
                        
                        <!-- Oculomotor Testing Results -->
                        <?php if (isset($results['oculomotor'])): ?>
                        <div class="result-section">
                            <h5><i class="ri-eye-line me-2"></i>Oculomotor Testing</h5>
                            
                            <?php if (isset($results['oculomotor']['spontaneous_nystagmus'])): ?>
                            <h6>Spontaneous Nystagmus</h6>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="result-value">
                                        <div class="result-label">With Fixation:</div>
                                        <div class="result-text"><?php echo htmlspecialchars($results['oculomotor']['spontaneous_nystagmus']['with_fixation'] ?? 'Not recorded'); ?></div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="result-value">
                                        <div class="result-label">Without Fixation:</div>
                                        <div class="result-text"><?php echo htmlspecialchars($results['oculomotor']['spontaneous_nystagmus']['without_fixation'] ?? 'Not recorded'); ?></div>
                                    </div>
                                </div>
                                <?php if (!empty($results['oculomotor']['spontaneous_nystagmus']['notes'])): ?>
                                <div class="col-12">
                                    <div class="result-value">
                                        <div class="result-label">Notes:</div>
                                        <div class="result-text"><?php echo nl2br(htmlspecialchars($results['oculomotor']['spontaneous_nystagmus']['notes'])); ?></div>
                                    </div>
                                </div>
                                <?php endif; ?>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (isset($results['oculomotor']['gaze_testing'])): ?>
                            <h6>Gaze Testing</h6>
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="result-value">
                                        <div class="result-label">Right:</div>
                                        <div class="result-text"><?php echo htmlspecialchars($results['oculomotor']['gaze_testing']['right'] ?? 'Not recorded'); ?></div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="result-value">
                                        <div class="result-label">Left:</div>
                                        <div class="result-text"><?php echo htmlspecialchars($results['oculomotor']['gaze_testing']['left'] ?? 'Not recorded'); ?></div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="result-value">
                                        <div class="result-label">Up:</div>
                                        <div class="result-text"><?php echo htmlspecialchars($results['oculomotor']['gaze_testing']['up'] ?? 'Not recorded'); ?></div>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="result-value">
                                        <div class="result-label">Down:</div>
                                        <div class="result-text"><?php echo htmlspecialchars($results['oculomotor']['gaze_testing']['down'] ?? 'Not recorded'); ?></div>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (isset($results['oculomotor']['smooth_pursuit'])): ?>
                            <h6>Smooth Pursuit</h6>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="result-value">
                                        <div class="result-label">Horizontal:</div>
                                        <div class="result-text"><?php echo htmlspecialchars($results['oculomotor']['smooth_pursuit']['horizontal'] ?? 'Not recorded'); ?></div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="result-value">
                                        <div class="result-label">Vertical:</div>
                                        <div class="result-text"><?php echo htmlspecialchars($results['oculomotor']['smooth_pursuit']['vertical'] ?? 'Not recorded'); ?></div>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (isset($results['oculomotor']['saccades'])): ?>
                            <h6>Saccades</h6>
                            <div class="row">
                                <div class="col-md-4">
                                    <div class="result-value">
                                        <div class="result-label">Latency (ms):</div>
                                        <div class="result-text"><?php echo htmlspecialchars($results['oculomotor']['saccades']['latency'] ?? 'Not recorded'); ?></div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="result-value">
                                        <div class="result-label">Velocity (deg/s):</div>
                                        <div class="result-text"><?php echo htmlspecialchars($results['oculomotor']['saccades']['velocity'] ?? 'Not recorded'); ?></div>
                                    </div>
                                </div>
                                <div class="col-md-4">
                                    <div class="result-value">
                                        <div class="result-label">Accuracy:</div>
                                        <div class="result-text"><?php echo htmlspecialchars($results['oculomotor']['saccades']['accuracy'] ?? 'Not recorded'); ?></div>
                                    </div>
                                </div>
                            </div>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>
                        
                        <!-- Positional Testing Results -->
                        <?php if (isset($results['positional'])): ?>
                        <div class="result-section">
                            <h5><i class="ri-anticlockwise-line me-2"></i>Positional & Positioning Testing</h5>
                            
                            <?php if (isset($results['positional']['dix_hallpike'])): ?>
                            <h6>Dix-Hallpike Maneuver</h6>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="result-value">
                                        <div class="result-label">Right:</div>
                                        <div class="result-text"><?php echo htmlspecialchars($results['positional']['dix_hallpike']['right'] ?? 'Not recorded'); ?></div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="result-value">
                                        <div class="result-label">Left:</div>
                                        <div class="result-text"><?php echo htmlspecialchars($results['positional']['dix_hallpike']['left'] ?? 'Not recorded'); ?></div>
                                    </div>
                                </div>
                                <?php if (!empty($results['positional']['dix_hallpike']['latency'])): ?>
                                <div class="col-md-4">
                                    <div class="result-value">
                                        <div class="result-label">Latency (seconds):</div>
                                        <div class="result-text"><?php echo htmlspecialchars($results['positional']['dix_hallpike']['latency']); ?></div>
                                    </div>
                                </div>
                                <?php endif; ?>
                                <?php if (!empty($results['positional']['dix_hallpike']['duration'])): ?>
                                <div class="col-md-4">
                                    <div class="result-value">
                                        <div class="result-label">Duration (seconds):</div>
                                        <div class="result-text"><?php echo htmlspecialchars($results['positional']['dix_hallpike']['duration']); ?></div>
                                    </div>
                                </div>
                                <?php endif; ?>
                                <?php if (!empty($results['positional']['dix_hallpike']['fatigability'])): ?>
                                <div class="col-md-4">
                                    <div class="result-value">
                                        <div class="result-label">Fatigability:</div>
                                        <div class="result-text"><?php echo htmlspecialchars($results['positional']['dix_hallpike']['fatigability']); ?></div>
                                    </div>
                                </div>
                                <?php endif; ?>
                            </div>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>
                        
                        <!-- Caloric Testing Results -->
                        <?php if (isset($results['caloric'])): ?>
                        <div class="result-section">
                            <h5><i class="ri-temp-cold-line me-2"></i>Caloric Testing</h5>
                            
                            <div class="row">
                                <?php if (isset($results['caloric']['right_warm'])): ?>
                                <div class="col-md-3 mb-3">
                                    <h6>Right Warm</h6>
                                    <div class="result-value">
                                        <div class="result-label">SPV (deg/s):</div>
                                        <div class="result-text"><?php echo htmlspecialchars($results['caloric']['right_warm']['slow_phase_velocity'] ?? 'Not recorded'); ?></div>
                                    </div>
                                </div>
                                <?php endif; ?>
                                
                                <?php if (isset($results['caloric']['right_cold'])): ?>
                                <div class="col-md-3 mb-3">
                                    <h6>Right Cold</h6>
                                    <div class="result-value">
                                        <div class="result-label">SPV (deg/s):</div>
                                        <div class="result-text"><?php echo htmlspecialchars($results['caloric']['right_cold']['slow_phase_velocity'] ?? 'Not recorded'); ?></div>
                                    </div>
                                </div>
                                <?php endif; ?>
                                
                                <?php if (isset($results['caloric']['left_warm'])): ?>
                                <div class="col-md-3 mb-3">
                                    <h6>Left Warm</h6>
                                    <div class="result-value">
                                        <div class="result-label">SPV (deg/s):</div>
                                        <div class="result-text"><?php echo htmlspecialchars($results['caloric']['left_warm']['slow_phase_velocity'] ?? 'Not recorded'); ?></div>
                                    </div>
                                </div>
                                <?php endif; ?>
                                
                                <?php if (isset($results['caloric']['left_cold'])): ?>
                                <div class="col-md-3 mb-3">
                                    <h6>Left Cold</h6>
                                    <div class="result-value">
                                        <div class="result-label">SPV (deg/s):</div>
                                        <div class="result-text"><?php echo htmlspecialchars($results['caloric']['left_cold']['slow_phase_velocity'] ?? 'Not recorded'); ?></div>
                                    </div>
                                </div>
                                <?php endif; ?>
                            </div>
                            
                            <?php if (!empty($results['caloric']['unilateral_weakness'])): ?>
                            <div class="result-value">
                                <div class="result-label">Unilateral Weakness:</div>
                                <div class="result-text"><?php echo htmlspecialchars($results['caloric']['unilateral_weakness']); ?></div>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (!empty($results['caloric']['directional_preponderance'])): ?>
                            <div class="result-value">
                                <div class="result-label">Directional Preponderance:</div>
                                <div class="result-text"><?php echo htmlspecialchars($results['caloric']['directional_preponderance']); ?></div>
                            </div>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>
                        
                        <!-- Coordination Tests Results -->
                        <?php if (isset($results['coordination_tests'])): ?>
                        <div class="result-section coordination-section">
                            <h5><i class="ri-hand-finger-line me-2"></i>Coordination Tests <span class="badge bg-info">For Review</span></h5>
                            
                            <?php if (!empty($results['coordination_tests']['finger_to_nose'])): ?>
                            <h6>Finger-to-Nose Test</h6>
                            <div class="result-value">
                                <div class="result-text"><?php echo nl2br(htmlspecialchars($results['coordination_tests']['finger_to_nose'])); ?></div>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (!empty($results['coordination_tests']['heel_to_shin'])): ?>
                            <h6>Heel-to-Shin Test</h6>
                            <div class="result-value">
                                <div class="result-text"><?php echo nl2br(htmlspecialchars($results['coordination_tests']['heel_to_shin'])); ?></div>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (!empty($results['coordination_tests']['rapid_alternating_movements'])): ?>
                            <h6>Rapid Alternating Movements</h6>
                            <div class="result-value">
                                <div class="result-text"><?php echo nl2br(htmlspecialchars($results['coordination_tests']['rapid_alternating_movements'])); ?></div>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (!empty($results['coordination_tests']['past_pointing'])): ?>
                            <h6>Past-Pointing Test</h6>
                            <div class="result-value">
                                <div class="result-text"><?php echo nl2br(htmlspecialchars($results['coordination_tests']['past_pointing'])); ?></div>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (!empty($results['coordination_tests']['romberg_test'])): ?>
                            <h6>Romberg Test</h6>
                            <div class="result-value">
                                <div class="result-text"><?php echo nl2br(htmlspecialchars($results['coordination_tests']['romberg_test'])); ?></div>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (!empty($results['coordination_tests']['fukuda_stepping'])): ?>
                            <h6>Fukuda Stepping Test</h6>
                            <div class="result-value">
                                <div class="result-text"><?php echo nl2br(htmlspecialchars($results['coordination_tests']['fukuda_stepping'])); ?></div>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (!empty($results['coordination_tests']['tandem_walk'])): ?>
                            <h6>Tandem Walk</h6>
                            <div class="result-value">
                                <div class="result-text"><?php echo nl2br(htmlspecialchars($results['coordination_tests']['tandem_walk'])); ?></div>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (!empty($results['coordination_tests']['additional_notes'])): ?>
                            <h6>Additional Coordination Notes</h6>
                            <div class="result-value">
                                <div class="result-text"><?php echo nl2br(htmlspecialchars($results['coordination_tests']['additional_notes'])); ?></div>
                            </div>
                            <?php endif; ?>
                        </div>
                        <?php endif; ?>
                        
                        <!-- Interpretation & Summary -->
                        <div class="result-section">
                            <h5><i class="ri-file-text-line me-2"></i>Clinical Interpretation & Summary</h5>
                            
                            <?php if ($test['interpretation']): ?>
                            <div class="result-value">
                                <div class="result-label">Clinical Interpretation:</div>
                                <div class="result-text"><?php echo nl2br(htmlspecialchars($test['interpretation'])); ?></div>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (!empty($results['abnormal_findings'])): ?>
                            <div class="result-value">
                                <div class="result-label">Abnormal Findings:</div>
                                <div class="result-text"><?php echo nl2br(htmlspecialchars($results['abnormal_findings'])); ?></div>
                            </div>
                            <?php endif; ?>
                            
                            <?php if (!empty($results['recommendations'])): ?>
                            <div class="result-value">
                                <div class="result-label">Recommendations:</div>
                                <div class="result-text"><?php echo nl2br(htmlspecialchars($results['recommendations'])); ?></div>
                            </div>
                            <?php endif; ?>
                        </div>
                        
                    <?php endif; ?>
                    
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>
</html>
