<?php
/**
 * Record VNG (Videonystagmography) Test Results
 * Includes coordination tests for review purposes
 */

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

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

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'AUDIOLOGIST', 'LAB_TECHNICIAN', 'ENT_DOCTOR', 'ENT_CONSULTANT'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) {
    header('Location: dashboard.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
        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
        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 existing results
$existing_results = [];
if ($test['result_value']) {
    $existing_results = json_decode($test['result_value'], true) ?? [];
}

$msg = '';
$error = '';

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $tested_by = $_SESSION['user_id'];
    $status = isset($_POST['complete']) ? 'COMPLETED' : 'IN_PROGRESS';
    $completed_at = isset($_POST['complete']) ? date('Y-m-d H:i:s') : NULL;
    
    // Get started_at if not already set
    $started_at = $test['started_at'] ?? date('Y-m-d H:i:s');
    
    // Build result data structure
    $result_data = [
        // Oculomotor Testing
        'oculomotor' => [
            'spontaneous_nystagmus' => [
                'with_fixation' => $_POST['spontaneous_with_fixation'] ?? '',
                'without_fixation' => $_POST['spontaneous_without_fixation'] ?? '',
                'notes' => $_POST['spontaneous_notes'] ?? ''
            ],
            'gaze_testing' => [
                'right' => $_POST['gaze_right'] ?? '',
                'left' => $_POST['gaze_left'] ?? '',
                'up' => $_POST['gaze_up'] ?? '',
                'down' => $_POST['gaze_down'] ?? '',
                'notes' => $_POST['gaze_notes'] ?? ''
            ],
            'smooth_pursuit' => [
                'horizontal' => $_POST['pursuit_horizontal'] ?? '',
                'vertical' => $_POST['pursuit_vertical'] ?? '',
                'notes' => $_POST['pursuit_notes'] ?? ''
            ],
            'saccades' => [
                'latency' => $_POST['saccades_latency'] ?? '',
                'velocity' => $_POST['saccades_velocity'] ?? '',
                'accuracy' => $_POST['saccades_accuracy'] ?? '',
                'notes' => $_POST['saccades_notes'] ?? ''
            ],
            'optokinetic' => [
                'horizontal' => $_POST['optokinetic_horizontal'] ?? '',
                'vertical' => $_POST['optokinetic_vertical'] ?? '',
                'notes' => $_POST['optokinetic_notes'] ?? ''
            ]
        ],
        
        // Positional Testing
        'positional' => [
            'positional_nystagmus' => [
                'supine_neutral' => $_POST['positional_supine_neutral'] ?? '',
                'supine_right' => $_POST['positional_supine_right'] ?? '',
                'supine_left' => $_POST['positional_supine_left'] ?? '',
                'notes' => $_POST['positional_notes'] ?? ''
            ],
            'dix_hallpike' => [
                'right' => $_POST['dix_hallpike_right'] ?? '',
                'left' => $_POST['dix_hallpike_left'] ?? '',
                'latency' => $_POST['dix_hallpike_latency'] ?? '',
                'duration' => $_POST['dix_hallpike_duration'] ?? '',
                'fatigability' => $_POST['dix_hallpike_fatigability'] ?? '',
                'notes' => $_POST['dix_hallpike_notes'] ?? ''
            ],
            'lateral_roll' => [
                'right' => $_POST['lateral_roll_right'] ?? '',
                'left' => $_POST['lateral_roll_left'] ?? '',
                'notes' => $_POST['lateral_roll_notes'] ?? ''
            ]
        ],
        
        // Caloric Testing
        'caloric' => [
            'right_warm' => [
                'slow_phase_velocity' => $_POST['caloric_rw_spv'] ?? '',
                'peak_velocity' => $_POST['caloric_rw_peak'] ?? '',
                'duration' => $_POST['caloric_rw_duration'] ?? '',
                'notes' => $_POST['caloric_rw_notes'] ?? ''
            ],
            'right_cold' => [
                'slow_phase_velocity' => $_POST['caloric_rc_spv'] ?? '',
                'peak_velocity' => $_POST['caloric_rc_peak'] ?? '',
                'duration' => $_POST['caloric_rc_duration'] ?? '',
                'notes' => $_POST['caloric_rc_notes'] ?? ''
            ],
            'left_warm' => [
                'slow_phase_velocity' => $_POST['caloric_lw_spv'] ?? '',
                'peak_velocity' => $_POST['caloric_lw_peak'] ?? '',
                'duration' => $_POST['caloric_lw_duration'] ?? '',
                'notes' => $_POST['caloric_lw_notes'] ?? ''
            ],
            'left_cold' => [
                'slow_phase_velocity' => $_POST['caloric_lc_spv'] ?? '',
                'peak_velocity' => $_POST['caloric_lc_peak'] ?? '',
                'duration' => $_POST['caloric_lc_duration'] ?? '',
                'notes' => $_POST['caloric_lc_notes'] ?? ''
            ],
            'unilateral_weakness' => $_POST['unilateral_weakness'] ?? '',
            'directional_preponderance' => $_POST['directional_preponderance'] ?? '',
            'caloric_notes' => $_POST['caloric_notes'] ?? ''
        ],
        
        // Coordination Tests (for review only)
        'coordination_tests' => [
            'finger_to_nose' => $_POST['coordination_finger_nose'] ?? '',
            'heel_to_shin' => $_POST['coordination_heel_shin'] ?? '',
            'rapid_alternating_movements' => $_POST['coordination_rapid_alternating'] ?? '',
            'past_pointing' => $_POST['coordination_past_pointing'] ?? '',
            'romberg_test' => $_POST['coordination_romberg'] ?? '',
            'fukuda_stepping' => $_POST['coordination_fukuda'] ?? '',
            'tandem_walk' => $_POST['coordination_tandem'] ?? '',
            'additional_notes' => $_POST['coordination_additional_notes'] ?? ''
        ],
        
        // Overall interpretation
        'interpretation' => $_POST['interpretation'] ?? '',
        'recommendations' => $_POST['recommendations'] ?? '',
        'abnormal_findings' => $_POST['abnormal_findings'] ?? ''
    ];
    
    $result_json = json_encode($result_data, JSON_PRETTY_PRINT);
    $interpretation = $_POST['interpretation'] ?? '';
    $abnormal_flag = $_POST['abnormal_flag'] ?? 'NORMAL';
    
    // Update test results
    $update_sql = "UPDATE lab_order_tests SET 
                   result_value = ?, 
                   interpretation = ?,
                   abnormal_flag = ?,
                   status = ?,
                   started_at = ?,
                   completed_at = ?,
                   tested_by = ?
                   WHERE order_test_id = ?";
    
    $stmt = $conn->prepare($update_sql);
    $stmt->bind_param("sssssssi", 
        $result_json, 
        $interpretation, 
        $abnormal_flag,
        $status,
        $started_at,
        $completed_at,
        $tested_by,
        $test_id
    );
    
    if ($stmt->execute()) {
        if ($status === 'COMPLETED') {
            header("Location: view_vng_results.php?test_id=" . $test_id);
            exit();
        } else {
            $msg = "Results saved as draft successfully.";
        }
    } else {
        $error = "Failed to save results: " . $conn->error;
    }
}

// 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 = "Record VNG Results";
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => $page_title)); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/sweetalert2/sweetalert2.min.css" rel="stylesheet">
    
    <style>
        .patient-info-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 12px;
            padding: 1.5rem;
            margin-bottom: 1.5rem;
        }
        
        .test-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;
        }
        
        .test-section h5 {
            color: #1e293b;
            font-weight: 600;
            margin-bottom: 1.25rem;
            padding-bottom: 0.75rem;
            border-bottom: 2px solid #e2e8f0;
        }
        
        .test-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;
        }
        
        .coordination-section h6 {
            color: #0c4a6e;
        }
        
        .form-label {
            font-weight: 500;
            color: #334155;
            margin-bottom: 0.5rem;
        }
        
        .info-badge {
            background: #dbeafe;
            color: #1e40af;
            padding: 0.25rem 0.75rem;
            border-radius: 6px;
            font-size: 0.75rem;
            font-weight: 500;
        }
    </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">Record Results</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <?php if ($msg): ?>
                        <div class="alert alert-success alert-dismissible fade show">
                            <i class="ri-check-line me-2"></i><?php echo $msg; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <?php if ($error): ?>
                        <div class="alert alert-danger alert-dismissible fade show">
                            <i class="ri-error-warning-line me-2"></i><?php echo $error; ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <!-- 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>Priority:</strong> 
                                    <span class="badge bg-<?php echo strtolower($test['priority']) == 'stat' ? 'danger' : (strtolower($test['priority']) == 'urgent' ? 'warning' : 'info'); ?>">
                                        <?php echo htmlspecialchars($test['priority']); ?>
                                    </span>
                                </p>
                                <?php if ($test['clinical_notes']): ?>
                                    <p class="mb-0"><strong>Clinical Notes:</strong> <?php echo htmlspecialchars(substr($test['clinical_notes'], 0, 100)); ?></p>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                    <form method="POST" id="vngResultsForm">
                        
                        <!-- Oculomotor Testing Section -->
                        <div class="test-section">
                            <h5><i class="ri-eye-line me-2"></i>Oculomotor Testing</h5>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <h6>Spontaneous Nystagmus</h6>
                                    <div class="mb-2">
                                        <label class="form-label">With Fixation</label>
                                        <input type="text" class="form-control" name="spontaneous_with_fixation" 
                                               value="<?php echo htmlspecialchars($existing_results['oculomotor']['spontaneous_nystagmus']['with_fixation'] ?? ''); ?>"
                                               placeholder="e.g., None, Right-beating, Left-beating">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Without Fixation</label>
                                        <input type="text" class="form-control" name="spontaneous_without_fixation"
                                               value="<?php echo htmlspecialchars($existing_results['oculomotor']['spontaneous_nystagmus']['without_fixation'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Notes</label>
                                        <textarea class="form-control" name="spontaneous_notes" rows="2"
                                                  placeholder="Additional observations..."><?php echo htmlspecialchars($existing_results['oculomotor']['spontaneous_nystagmus']['notes'] ?? ''); ?></textarea>
                                    </div>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <h6>Gaze Testing</h6>
                                    <div class="row">
                                        <div class="col-6 mb-2">
                                            <label class="form-label">Right</label>
                                            <input type="text" class="form-control" name="gaze_right"
                                                   value="<?php echo htmlspecialchars($existing_results['oculomotor']['gaze_testing']['right'] ?? ''); ?>">
                                        </div>
                                        <div class="col-6 mb-2">
                                            <label class="form-label">Left</label>
                                            <input type="text" class="form-control" name="gaze_left"
                                                   value="<?php echo htmlspecialchars($existing_results['oculomotor']['gaze_testing']['left'] ?? ''); ?>">
                                        </div>
                                        <div class="col-6 mb-2">
                                            <label class="form-label">Up</label>
                                            <input type="text" class="form-control" name="gaze_up"
                                                   value="<?php echo htmlspecialchars($existing_results['oculomotor']['gaze_testing']['up'] ?? ''); ?>">
                                        </div>
                                        <div class="col-6 mb-2">
                                            <label class="form-label">Down</label>
                                            <input type="text" class="form-control" name="gaze_down"
                                                   value="<?php echo htmlspecialchars($existing_results['oculomotor']['gaze_testing']['down'] ?? ''); ?>">
                                        </div>
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Notes</label>
                                        <textarea class="form-control" name="gaze_notes" rows="2"><?php echo htmlspecialchars($existing_results['oculomotor']['gaze_testing']['notes'] ?? ''); ?></textarea>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <h6>Smooth Pursuit</h6>
                                    <div class="mb-2">
                                        <label class="form-label">Horizontal</label>
                                        <input type="text" class="form-control" name="pursuit_horizontal"
                                               value="<?php echo htmlspecialchars($existing_results['oculomotor']['smooth_pursuit']['horizontal'] ?? ''); ?>"
                                               placeholder="e.g., Normal, Saccadic intrusions">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Vertical</label>
                                        <input type="text" class="form-control" name="pursuit_vertical"
                                               value="<?php echo htmlspecialchars($existing_results['oculomotor']['smooth_pursuit']['vertical'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Notes</label>
                                        <textarea class="form-control" name="pursuit_notes" rows="2"><?php echo htmlspecialchars($existing_results['oculomotor']['smooth_pursuit']['notes'] ?? ''); ?></textarea>
                                    </div>
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <h6>Saccades</h6>
                                    <div class="mb-2">
                                        <label class="form-label">Latency (ms)</label>
                                        <input type="text" class="form-control" name="saccades_latency"
                                               value="<?php echo htmlspecialchars($existing_results['oculomotor']['saccades']['latency'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Velocity (deg/s)</label>
                                        <input type="text" class="form-control" name="saccades_velocity"
                                               value="<?php echo htmlspecialchars($existing_results['oculomotor']['saccades']['velocity'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Accuracy</label>
                                        <input type="text" class="form-control" name="saccades_accuracy"
                                               value="<?php echo htmlspecialchars($existing_results['oculomotor']['saccades']['accuracy'] ?? ''); ?>"
                                               placeholder="e.g., Normal, Hypometric, Hypermetric">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Notes</label>
                                        <textarea class="form-control" name="saccades_notes" rows="2"><?php echo htmlspecialchars($existing_results['oculomotor']['saccades']['notes'] ?? ''); ?></textarea>
                                    </div>
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <h6>Optokinetic Testing</h6>
                                    <div class="mb-2">
                                        <label class="form-label">Horizontal</label>
                                        <input type="text" class="form-control" name="optokinetic_horizontal"
                                               value="<?php echo htmlspecialchars($existing_results['oculomotor']['optokinetic']['horizontal'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Vertical</label>
                                        <input type="text" class="form-control" name="optokinetic_vertical"
                                               value="<?php echo htmlspecialchars($existing_results['oculomotor']['optokinetic']['vertical'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Notes</label>
                                        <textarea class="form-control" name="optokinetic_notes" rows="2"><?php echo htmlspecialchars($existing_results['oculomotor']['optokinetic']['notes'] ?? ''); ?></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Positional Testing Section -->
                        <div class="test-section">
                            <h5><i class="ri-anticlockwise-line me-2"></i>Positional & Positioning Testing</h5>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <h6>Positional Nystagmus</h6>
                                    <div class="mb-2">
                                        <label class="form-label">Supine Neutral</label>
                                        <input type="text" class="form-control" name="positional_supine_neutral"
                                               value="<?php echo htmlspecialchars($existing_results['positional']['positional_nystagmus']['supine_neutral'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Supine Right</label>
                                        <input type="text" class="form-control" name="positional_supine_right"
                                               value="<?php echo htmlspecialchars($existing_results['positional']['positional_nystagmus']['supine_right'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Supine Left</label>
                                        <input type="text" class="form-control" name="positional_supine_left"
                                               value="<?php echo htmlspecialchars($existing_results['positional']['positional_nystagmus']['supine_left'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Notes</label>
                                        <textarea class="form-control" name="positional_notes" rows="2"><?php echo htmlspecialchars($existing_results['positional']['positional_nystagmus']['notes'] ?? ''); ?></textarea>
                                    </div>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <h6>Dix-Hallpike Maneuver</h6>
                                    <div class="row">
                                        <div class="col-6 mb-2">
                                            <label class="form-label">Right</label>
                                            <input type="text" class="form-control" name="dix_hallpike_right"
                                                   value="<?php echo htmlspecialchars($existing_results['positional']['dix_hallpike']['right'] ?? ''); ?>"
                                                   placeholder="e.g., Positive, Negative">
                                        </div>
                                        <div class="col-6 mb-2">
                                            <label class="form-label">Left</label>
                                            <input type="text" class="form-control" name="dix_hallpike_left"
                                                   value="<?php echo htmlspecialchars($existing_results['positional']['dix_hallpike']['left'] ?? ''); ?>">
                                        </div>
                                        <div class="col-6 mb-2">
                                            <label class="form-label">Latency (seconds)</label>
                                            <input type="text" class="form-control" name="dix_hallpike_latency"
                                                   value="<?php echo htmlspecialchars($existing_results['positional']['dix_hallpike']['latency'] ?? ''); ?>">
                                        </div>
                                        <div class="col-6 mb-2">
                                            <label class="form-label">Duration (seconds)</label>
                                            <input type="text" class="form-control" name="dix_hallpike_duration"
                                                   value="<?php echo htmlspecialchars($existing_results['positional']['dix_hallpike']['duration'] ?? ''); ?>">
                                        </div>
                                        <div class="col-12 mb-2">
                                            <label class="form-label">Fatigability</label>
                                            <input type="text" class="form-control" name="dix_hallpike_fatigability"
                                                   value="<?php echo htmlspecialchars($existing_results['positional']['dix_hallpike']['fatigability'] ?? ''); ?>"
                                                   placeholder="e.g., Fatigable, Non-fatigable">
                                        </div>
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Notes</label>
                                        <textarea class="form-control" name="dix_hallpike_notes" rows="2"><?php echo htmlspecialchars($existing_results['positional']['dix_hallpike']['notes'] ?? ''); ?></textarea>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <h6>Lateral Roll Test</h6>
                                    <div class="mb-2">
                                        <label class="form-label">Right Roll</label>
                                        <input type="text" class="form-control" name="lateral_roll_right"
                                               value="<?php echo htmlspecialchars($existing_results['positional']['lateral_roll']['right'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Left Roll</label>
                                        <input type="text" class="form-control" name="lateral_roll_left"
                                               value="<?php echo htmlspecialchars($existing_results['positional']['lateral_roll']['left'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Notes</label>
                                        <textarea class="form-control" name="lateral_roll_notes" rows="2"><?php echo htmlspecialchars($existing_results['positional']['lateral_roll']['notes'] ?? ''); ?></textarea>
                                    </div>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Caloric Testing Section -->
                        <div class="test-section">
                            <h5><i class="ri-temp-cold-line me-2"></i>Caloric Testing</h5>
                            
                            <div class="row">
                                <div class="col-md-3 mb-3">
                                    <h6>Right Warm</h6>
                                    <div class="mb-2">
                                        <label class="form-label">Slow Phase Velocity (deg/s)</label>
                                        <input type="text" class="form-control" name="caloric_rw_spv"
                                               value="<?php echo htmlspecialchars($existing_results['caloric']['right_warm']['slow_phase_velocity'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Peak Velocity (deg/s)</label>
                                        <input type="text" class="form-control" name="caloric_rw_peak"
                                               value="<?php echo htmlspecialchars($existing_results['caloric']['right_warm']['peak_velocity'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Duration (seconds)</label>
                                        <input type="text" class="form-control" name="caloric_rw_duration"
                                               value="<?php echo htmlspecialchars($existing_results['caloric']['right_warm']['duration'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Notes</label>
                                        <textarea class="form-control" name="caloric_rw_notes" rows="2"><?php echo htmlspecialchars($existing_results['caloric']['right_warm']['notes'] ?? ''); ?></textarea>
                                    </div>
                                </div>
                                
                                <div class="col-md-3 mb-3">
                                    <h6>Right Cold</h6>
                                    <div class="mb-2">
                                        <label class="form-label">Slow Phase Velocity (deg/s)</label>
                                        <input type="text" class="form-control" name="caloric_rc_spv"
                                               value="<?php echo htmlspecialchars($existing_results['caloric']['right_cold']['slow_phase_velocity'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Peak Velocity (deg/s)</label>
                                        <input type="text" class="form-control" name="caloric_rc_peak"
                                               value="<?php echo htmlspecialchars($existing_results['caloric']['right_cold']['peak_velocity'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Duration (seconds)</label>
                                        <input type="text" class="form-control" name="caloric_rc_duration"
                                               value="<?php echo htmlspecialchars($existing_results['caloric']['right_cold']['duration'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Notes</label>
                                        <textarea class="form-control" name="caloric_rc_notes" rows="2"><?php echo htmlspecialchars($existing_results['caloric']['right_cold']['notes'] ?? ''); ?></textarea>
                                    </div>
                                </div>
                                
                                <div class="col-md-3 mb-3">
                                    <h6>Left Warm</h6>
                                    <div class="mb-2">
                                        <label class="form-label">Slow Phase Velocity (deg/s)</label>
                                        <input type="text" class="form-control" name="caloric_lw_spv"
                                               value="<?php echo htmlspecialchars($existing_results['caloric']['left_warm']['slow_phase_velocity'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Peak Velocity (deg/s)</label>
                                        <input type="text" class="form-control" name="caloric_lw_peak"
                                               value="<?php echo htmlspecialchars($existing_results['caloric']['left_warm']['peak_velocity'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Duration (seconds)</label>
                                        <input type="text" class="form-control" name="caloric_lw_duration"
                                               value="<?php echo htmlspecialchars($existing_results['caloric']['left_warm']['duration'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Notes</label>
                                        <textarea class="form-control" name="caloric_lw_notes" rows="2"><?php echo htmlspecialchars($existing_results['caloric']['left_warm']['notes'] ?? ''); ?></textarea>
                                    </div>
                                </div>
                                
                                <div class="col-md-3 mb-3">
                                    <h6>Left Cold</h6>
                                    <div class="mb-2">
                                        <label class="form-label">Slow Phase Velocity (deg/s)</label>
                                        <input type="text" class="form-control" name="caloric_lc_spv"
                                               value="<?php echo htmlspecialchars($existing_results['caloric']['left_cold']['slow_phase_velocity'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Peak Velocity (deg/s)</label>
                                        <input type="text" class="form-control" name="caloric_lc_peak"
                                               value="<?php echo htmlspecialchars($existing_results['caloric']['left_cold']['peak_velocity'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Duration (seconds)</label>
                                        <input type="text" class="form-control" name="caloric_lc_duration"
                                               value="<?php echo htmlspecialchars($existing_results['caloric']['left_cold']['duration'] ?? ''); ?>">
                                    </div>
                                    <div class="mb-2">
                                        <label class="form-label">Notes</label>
                                        <textarea class="form-control" name="caloric_lc_notes" rows="2"><?php echo htmlspecialchars($existing_results['caloric']['left_cold']['notes'] ?? ''); ?></textarea>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Unilateral Weakness (%)</label>
                                    <input type="text" class="form-control" name="unilateral_weakness"
                                           value="<?php echo htmlspecialchars($existing_results['caloric']['unilateral_weakness'] ?? ''); ?>"
                                           placeholder="e.g., 25% right weakness">
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Directional Preponderance (%)</label>
                                    <input type="text" class="form-control" name="directional_preponderance"
                                           value="<?php echo htmlspecialchars($existing_results['caloric']['directional_preponderance'] ?? ''); ?>"
                                           placeholder="e.g., 30% right-beating">
                                </div>
                                <div class="col-12 mb-3">
                                    <label class="form-label">Caloric Testing Notes</label>
                                    <textarea class="form-control" name="caloric_notes" rows="3"
                                              placeholder="Overall caloric test observations..."><?php echo htmlspecialchars($existing_results['caloric']['caloric_notes'] ?? ''); ?></textarea>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Coordination Tests Section (For Review Only) -->
                        <div class="test-section coordination-section">
                            <h5><i class="ri-hand-finger-line me-2"></i>Coordination Tests <span class="info-badge">For Review Only</span></h5>
                            <p class="text-muted mb-3">Enter coordination test findings for clinical review and documentation.</p>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Finger-to-Nose Test</label>
                                    <textarea class="form-control" name="coordination_finger_nose" rows="3"
                                              placeholder="Describe findings: accuracy, tremor, past-pointing, etc."><?php echo htmlspecialchars($existing_results['coordination_tests']['finger_to_nose'] ?? ''); ?></textarea>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Heel-to-Shin Test</label>
                                    <textarea class="form-control" name="coordination_heel_shin" rows="3"
                                              placeholder="Describe findings: smoothness, accuracy, tremor, etc."><?php echo htmlspecialchars($existing_results['coordination_tests']['heel_to_shin'] ?? ''); ?></textarea>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Rapid Alternating Movements</label>
                                    <textarea class="form-control" name="coordination_rapid_alternating" rows="3"
                                              placeholder="Describe findings: rhythm, speed, accuracy, etc."><?php echo htmlspecialchars($existing_results['coordination_tests']['rapid_alternating_movements'] ?? ''); ?></textarea>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Past-Pointing Test</label>
                                    <textarea class="form-control" name="coordination_past_pointing" rows="3"
                                              placeholder="Describe findings: direction, magnitude of deviation, etc."><?php echo htmlspecialchars($existing_results['coordination_tests']['past_pointing'] ?? ''); ?></textarea>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Romberg Test</label>
                                    <textarea class="form-control" name="coordination_romberg" rows="3"
                                              placeholder="Describe findings: stability with eyes open/closed, sway direction, etc."><?php echo htmlspecialchars($existing_results['coordination_tests']['romberg_test'] ?? ''); ?></textarea>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Fukuda Stepping Test</label>
                                    <textarea class="form-control" name="coordination_fukuda" rows="3"
                                              placeholder="Describe findings: rotation angle, forward displacement, etc."><?php echo htmlspecialchars($existing_results['coordination_tests']['fukuda_stepping'] ?? ''); ?></textarea>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Tandem Walk</label>
                                    <textarea class="form-control" name="coordination_tandem" rows="3"
                                              placeholder="Describe findings: ability to maintain line, steps off, etc."><?php echo htmlspecialchars($existing_results['coordination_tests']['tandem_walk'] ?? ''); ?></textarea>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label class="form-label">Additional Coordination Notes</label>
                                    <textarea class="form-control" name="coordination_additional_notes" rows="3"
                                              placeholder="Any additional coordination test findings or observations..."><?php echo htmlspecialchars($existing_results['coordination_tests']['additional_notes'] ?? ''); ?></textarea>
                                </div>
                            </div>
                        </div>
                        
                        <!-- Interpretation & Summary Section -->
                        <div class="test-section">
                            <h5><i class="ri-file-text-line me-2"></i>Interpretation & Summary</h5>
                            
                            <div class="mb-3">
                                <label class="form-label">Abnormal Flag</label>
                                <select class="form-select" name="abnormal_flag" required>
                                    <option value="NORMAL" <?php echo ($test['abnormal_flag'] ?? 'NORMAL') == 'NORMAL' ? 'selected' : ''; ?>>Normal</option>
                                    <option value="ABNORMAL" <?php echo ($test['abnormal_flag'] ?? '') == 'ABNORMAL' ? 'selected' : ''; ?>>Abnormal</option>
                                    <option value="BORDERLINE" <?php echo ($test['abnormal_flag'] ?? '') == 'BORDERLINE' ? 'selected' : ''; ?>>Borderline</option>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Clinical Interpretation <span class="text-danger">*</span></label>
                                <textarea class="form-control" name="interpretation" rows="5" required
                                          placeholder="Provide comprehensive interpretation of all test findings, including oculomotor, positional, caloric, and coordination test results..."><?php echo htmlspecialchars($test['interpretation'] ?? $existing_results['interpretation'] ?? ''); ?></textarea>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Abnormal Findings</label>
                                <textarea class="form-control" name="abnormal_findings" rows="3"
                                          placeholder="List any abnormal findings identified during testing..."><?php echo htmlspecialchars($existing_results['abnormal_findings'] ?? ''); ?></textarea>
                            </div>
                            
                            <div class="mb-3">
                                <label class="form-label">Recommendations</label>
                                <textarea class="form-control" name="recommendations" rows="3"
                                          placeholder="Clinical recommendations based on test results (e.g., vestibular rehabilitation, further imaging, follow-up)..."><?php echo htmlspecialchars($existing_results['recommendations'] ?? ''); ?></textarea>
                            </div>
                        </div>
                        
                        <!-- Action Buttons -->
                        <div class="test-section">
                            <div class="d-flex justify-content-between gap-2">
                                <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>
                                    <button type="submit" name="save_draft" class="btn btn-warning">
                                        <i class="ri-save-3-line me-2"></i>Save Draft
                                    </button>
                                    <button type="submit" name="complete" class="btn btn-success" 
                                            onclick="return confirm('Are you sure you want to finalize these VNG results? This will mark the test as completed.');">
                                        <i class="ri-check-double-line me-2"></i>Finalize Results
                                    </button>
                                </div>
                            </div>
                        </div>
                        
                    </form>
                    
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="assets/libs/sweetalert2/sweetalert2.min.js"></script>
    <script>
        // Form validation
        document.getElementById('vngResultsForm').addEventListener('submit', function(e) {
            const interpretation = document.querySelector('textarea[name="interpretation"]').value.trim();
            
            if (!interpretation) {
                e.preventDefault();
                Swal.fire({
                    icon: 'error',
                    title: 'Missing Information',
                    text: 'Please provide a clinical interpretation before saving.',
                    confirmButtonColor: '#2d7a2d'
                });
                return false;
            }
        });
        
        // Auto-save warning
        let formChanged = false;
        const formInputs = document.querySelectorAll('#vngResultsForm input, #vngResultsForm textarea, #vngResultsForm select');
        formInputs.forEach(input => {
            input.addEventListener('change', () => {
                formChanged = true;
            });
        });
        
        window.addEventListener('beforeunload', function(e) {
            if (formChanged) {
                e.preventDefault();
                e.returnValue = 'You have unsaved changes. Are you sure you want to leave?';
            }
        });
    </script>
</body>
</html>
