<?php
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: audiometry_tests.php');
    exit();
}

// Fetch Test Details
$sql = "SELECT t.order_test_id, t.order_id, t.status, t.result_value, t.interpretation, 
               t.started_at, t.completed_at, t.result_files,
               tt.test_name, tt.test_code, tt.category,
               o.order_number, o.order_date,
               p.patient_id, p.patient_number, u.full_name as patient_name, u.gender, u.date_of_birth,
               tech.full_name as technician_name,
               doc.full_name as ordered_by_name
        FROM lab_order_tests t
        INNER JOIN lab_orders o ON t.order_id = o.order_id
        INNER JOIN patients p ON o.patient_id = p.patient_id
        INNER JOIN users u ON p.user_id = u.user_id
        INNER JOIN ent_test_types tt ON t.test_type_id = tt.test_type_id
        LEFT JOIN users tech ON t.tested_by = tech.user_id
        LEFT JOIN users doc ON o.ordered_by = doc.user_id
        WHERE t.order_test_id = ?";

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

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

// Parse result value if JSON
$results_data = json_decode($test['result_value'] ?? '[]', true);
$is_audiometry = ($test['category'] === 'AUDIOMETRY');

// Calculate Age
$dob = new DateTime($test['date_of_birth']);
$now = new DateTime();
$age = $now->diff($dob)->y;

?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Test Details')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <style>
        .test-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem;
            border-radius: 12px;
            margin-bottom: 2rem;
        }

        .info-label {
            color: #64748b;
            font-size: 0.875rem;
            font-weight: 600;
            text-transform: uppercase;
        }

        .info-value {
            font-size: 1rem;
            font-weight: 500;
            color: #1e293b;
        }

        .status-badge {
            padding: 0.5rem 1rem;
            border-radius: 20px;
            font-weight: 600;
            font-size: 0.875rem;
        }

        .status-PENDING {
            background: #fef3c7;
            color: #92400e;
        }

        .status-IN_PROGRESS {
            background: #dbeafe;
            color: #1e40af;
        }

        .status-COMPLETED {
            background: #d1fae5;
            color: #065f46;
        }

        .audiometry-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
            gap: 1px;
            background: #e2e8f0;
            border: 1px solid #e2e8f0;
        }

        .grid-header,
        .grid-cell {
            background: white;
            padding: 0.75rem;
            text-align: center;
        }

        .grid-header {
            font-weight: 600;
            background: #f8fafc;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>

        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">

                    <!-- Breadcrumbs -->
                    <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">Test Details</h4>
                                <div class="page-title-right">
                                    <ol class="breadcrumb m-0">
                                        <li class="breadcrumb-item"><a href="audiometry_tests.php">Audiometry</a></li>
                                        <li class="breadcrumb-item active">Details</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Header -->
                    <div class="test-header">
                        <div class="d-flex justify-content-between align-items-start">
                            <div>
                                <h2 class="text-white mb-2">
                                    <?php echo htmlspecialchars($test['test_name']); ?>
                                </h2>
                                <p class="mb-0 opacity-75">
                                    Code:
                                    <?php echo htmlspecialchars($test['test_code']); ?> |
                                    Order: #
                                    <?php echo htmlspecialchars($test['order_number']); ?>
                                </p>
                            </div>
                            <span class="status-badge status-<?php echo $test['status']; ?>">
                                <?php echo str_replace('_', ' ', $test['status']); ?>
                            </span>
                        </div>
                    </div>

                    <div class="row">
                        <!-- Left Column: Patient & Test Info -->
                        <div class="col-xl-4">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Patient Information</h5>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <div class="info-label">Name</div>
                                        <div class="info-value">
                                            <?php echo htmlspecialchars($test['patient_name']); ?>
                                        </div>
                                    </div>
                                    <div class="d-flex justify-content-between mb-3">
                                        <div>
                                            <div class="info-label">Patient ID</div>
                                            <div class="info-value">
                                                <?php echo htmlspecialchars($test['patient_number']); ?>
                                            </div>
                                        </div>
                                        <div class="text-end">
                                            <div class="info-label">Age / Gender</div>
                                            <div class="info-value">
                                                <?php echo $age; ?>y /
                                                <?php echo $test['gender']; ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Test Information</h5>
                                </div>
                                <div class="card-body">
                                    <div class="mb-3">
                                        <div class="info-label">Ordered By</div>
                                        <div class="info-value">Dr.
                                            <?php echo htmlspecialchars($test['ordered_by_name']); ?>
                                        </div>
                                    </div>
                                    <div class="mb-3">
                                        <div class="info-label">Performed By</div>
                                        <div class="info-value">
                                            <?php echo htmlspecialchars($test['technician_name'] ?? 'Pending'); ?>
                                        </div>
                                    </div>
                                    <div class="mb-3">
                                        <div class="info-label">Date Performed</div>
                                        <div class="info-value">
                                            <?php echo $test['completed_at'] ? date('M d, Y h:i A', strtotime($test['completed_at'])) : '-'; ?>
                                        </div>
                                    </div>
                                </div>
                            </div>

                            <div class="card">
                                <div class="card-body">
                                    <div class="d-grid gap-2">
                                        <?php if ($test['status'] !== 'COMPLETED'): ?>
                                            <?php if ($is_audiometry): ?>
                                                <!-- Audiometry: Redirect to Interactive Page -->
                                                <a href="interactive_pure_tone_audiometry.php?id=<?php echo $test_id; ?>"
                                                    class="btn btn-primary btn-lg">
                                                    <i class="ri-volume-up-line me-2"></i>Perform Audiometry Test
                                                </a>
                                            <?php else: ?>
                                                <!-- Other Tests: Generic Entry Page -->
                                                <a href="enter_test_results.php?test_id=<?php echo $test_id; ?>"
                                                    class="btn btn-primary btn-lg">
                                                    <i class="ri-edit-line me-2"></i>Enter Results
                                                </a>
                                            <?php endif; ?>
                                        <?php else: ?>
                                            <?php if ($is_audiometry): ?>
                                                <!-- Audiometry: View/Edit in Interactive Page -->
                                                <a href="interactive_pure_tone_audiometry.php?id=<?php echo $test_id; ?>"
                                                    class="btn btn-outline-secondary">
                                                    <i class="ri-pencil-line me-2"></i>View/Edit Audiometry
                                                </a>
                                                <a href="generate_audiometry_report.php?id=<?php echo $test_id; ?>"
                                                    class="btn btn-success" target="_blank">
                                                    <i class="ri-file-pdf-line me-2"></i>View Report
                                                </a>
                                            <?php else: ?>
                                                <!-- Other Tests: Generic Edit -->
                                                <a href="enter_test_results.php?test_id=<?php echo $test_id; ?>"
                                                    class="btn btn-outline-secondary">
                                                    <i class="ri-pencil-line me-2"></i>Edit Results
                                                </a>
                                                <button onclick="window.print()" class="btn btn-success">
                                                    <i class="ri-printer-line me-2"></i>Print Report
                                                </button>
                                            <?php endif; ?>
                                        <?php endif; ?>
                                        
                                        <a href="audiometry_tests.php" class="btn btn-outline-secondary">
                                            <i class="ri-arrow-left-line me-2"></i>Back to Tests
                                        </a>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!-- Right Column: Results -->
                        <div class="col-xl-8">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title mb-0">Test Results</h5>
                                </div>
                                <div class="card-body">

                                    <?php if ($test['status'] === 'PENDING'): ?>
                                        <div class="alert alert-warning">
                                            <i class="ri-time-line me-2"></i>Test is pending. No results available yet.
                                        </div>
                                    <?php elseif ($is_audiometry && !empty($test['result_files'])): ?>
                                        <?php
                                        // Parse audiometry data from result_files JSON
                                        $audiometry_data = json_decode($test['result_files'], true);
                                        ?>
                                        
                                        <!-- Audiometry Results Summary -->
                                        <div class="alert alert-info">
                                            <i class="ri-information-line me-2"></i>
                                            <strong>Interactive Audiometry Test Completed</strong>
                                            <p class="mb-0 mt-2">This test was performed using the interactive audiometry system with separate ear charts.</p>
                                        </div>

                                        <?php if (isset($audiometry_data['right_pta']) || isset($audiometry_data['left_pta'])): ?>
                                            <!-- Pure Tone Average Results -->
                                            <div class="row g-3 mb-4">
                                                <div class="col-md-6">
                                                    <div class="card bg-danger bg-opacity-10 border-danger">
                                                        <div class="card-body text-center">
                                                            <h6 class="text-danger mb-2">RIGHT EAR PTA</h6>
                                                            <h2 class="mb-0 text-danger">
                                                                <?php echo isset($audiometry_data['right_pta']) ? number_format($audiometry_data['right_pta'], 1) : '-'; ?>
                                                                <small class="fs-6">dB HL</small>
                                                            </h2>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div class="col-md-6">
                                                    <div class="card bg-primary bg-opacity-10 border-primary">
                                                        <div class="card-body text-center">
                                                            <h6 class="text-primary mb-2">LEFT EAR PTA</h6>
                                                            <h2 class="mb-0 text-primary">
                                                                <?php echo isset($audiometry_data['left_pta']) ? number_format($audiometry_data['left_pta'], 1) : '-'; ?>
                                                                <small class="fs-6">dB HL</small>
                                                            </h2>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        <?php endif; ?>

                                        <!-- Clinical Tests -->
                                        <?php if (!empty($audiometry_data['weber_result']) || !empty($audiometry_data['rinne_right']) || !empty($audiometry_data['rinne_left'])): ?>
                                            <div class="mb-4">
                                                <h6 class="text-uppercase text-muted fs-12 fw-bold mb-3">Clinical Tuning Fork Tests</h6>
                                                <div class="table-responsive">
                                                    <table class="table table-bordered">
                                                        <?php if (!empty($audiometry_data['weber_result'])): ?>
                                                            <tr>
                                                                <td class="fw-semibold" width="200">Weber Test (512 Hz)</td>
                                                                <td><?php echo ucwords(str_replace('_', ' ', strtolower($audiometry_data['weber_result']))); ?></td>
                                                            </tr>
                                                        <?php endif; ?>
                                                        <?php if (!empty($audiometry_data['rinne_right'])): ?>
                                                            <tr>
                                                                <td class="fw-semibold">Rinne Test - Right</td>
                                                                <td><?php echo ucfirst(strtolower($audiometry_data['rinne_right'])); ?></td>
                                                            </tr>
                                                        <?php endif; ?>
                                                        <?php if (!empty($audiometry_data['rinne_left'])): ?>
                                                            <tr>
                                                                <td class="fw-semibold">Rinne Test - Left</td>
                                                                <td><?php echo ucfirst(strtolower($audiometry_data['rinne_left'])); ?></td>
                                                            </tr>
                                                        <?php endif; ?>
                                                    </table>
                                                </div>
                                            </div>
                                        <?php endif; ?>

                                        <!-- Audiogram Images -->
                                        <?php if (isset($audiometry_data['images']) && is_array($audiometry_data['images'])): ?>
                                            <div class="mb-4">
                                                <h6 class="text-uppercase text-muted fs-12 fw-bold mb-3">Audiogram Charts</h6>
                                                <div class="row g-3">
                                                    <?php if (isset($audiometry_data['images']['right_ear']) && file_exists($audiometry_data['images']['right_ear'])): ?>
                                                        <div class="col-md-6">
                                                            <div class="card">
                                                                <div class="card-header bg-danger text-white">
                                                                    <h6 class="mb-0">Right Ear Audiogram</h6>
                                                                </div>
                                                                <div class="card-body p-2">
                                                                    <img src="<?php echo $audiometry_data['images']['right_ear']; ?>" 
                                                                         class="img-fluid" 
                                                                         alt="Right Ear Audiogram">
                                                                </div>
                                                            </div>
                                                        </div>
                                                    <?php endif; ?>
                                                    
                                                    <?php if (isset($audiometry_data['images']['left_ear']) && file_exists($audiometry_data['images']['left_ear'])): ?>
                                                        <div class="col-md-6">
                                                            <div class="card">
                                                                <div class="card-header bg-primary text-white">
                                                                    <h6 class="mb-0">Left Ear Audiogram</h6>
                                                                </div>
                                                                <div class="card-body p-2">
                                                                    <img src="<?php echo $audiometry_data['images']['left_ear']; ?>" 
                                                                         class="img-fluid" 
                                                                         alt="Left Ear Audiogram">
                                                                </div>
                                                            </div>
                                                        </div>
                                                    <?php endif; ?>
                                                </div>
                                            </div>
                                        <?php endif; ?>

                                        <!-- Comments and Recommendations -->
                                        <?php if (!empty($audiometry_data['comments'])): ?>
                                            <div class="mb-3">
                                                <h6 class="text-uppercase text-muted fs-12 fw-bold">Clinical Comments</h6>
                                                <div class="p-3 border rounded bg-light">
                                                    <?php echo nl2br(htmlspecialchars($audiometry_data['comments'])); ?>
                                                </div>
                                            </div>
                                        <?php endif; ?>

                                        <?php if (!empty($audiometry_data['recommendations'])): ?>
                                            <div class="mb-3">
                                                <h6 class="text-uppercase text-muted fs-12 fw-bold">Recommendations</h6>
                                                <div class="p-3 border rounded bg-light">
                                                    <?php echo nl2br(htmlspecialchars($audiometry_data['recommendations'])); ?>
                                                </div>
                                            </div>
                                        <?php endif; ?>

                                    <?php elseif (!empty($results_data)): ?>
                                        <!-- Legacy Audiometry Data Display (Old Format) -->
                                        <h6 class="mb-3">Pure Tone Audiometry (dB HL)</h6>
                                        <div class="table-responsive">
                                            <table class="table table-bordered table-sm text-center">
                                                <thead class="table-light">
                                                    <tr>
                                                        <th>Ear / Freq (Hz)</th>
                                                        <th>250</th>
                                                        <th>500</th>
                                                        <th>1000</th>
                                                        <th>2000</th>
                                                        <th>4000</th>
                                                        <th>8000</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr>
                                                        <td class="fw-bold text-danger">Right Ear (Red)</td>
                                                        <td>
                                                            <?php echo $results_data['right'][250] ?? '-'; ?>
                                                        </td>
                                                        <td>
                                                            <?php echo $results_data['right'][500] ?? '-'; ?>
                                                        </td>
                                                        <td>
                                                            <?php echo $results_data['right'][1000] ?? '-'; ?>
                                                        </td>
                                                        <td>
                                                            <?php echo $results_data['right'][2000] ?? '-'; ?>
                                                        </td>
                                                        <td>
                                                            <?php echo $results_data['right'][4000] ?? '-'; ?>
                                                        </td>
                                                        <td>
                                                            <?php echo $results_data['right'][8000] ?? '-'; ?>
                                                        </td>
                                                    </tr>
                                                    <tr>
                                                        <td class="fw-bold text-primary">Left Ear (Blue)</td>
                                                        <td>
                                                            <?php echo $results_data['left'][250] ?? '-'; ?>
                                                        </td>
                                                        <td>
                                                            <?php echo $results_data['left'][500] ?? '-'; ?>
                                                        </td>
                                                        <td>
                                                            <?php echo $results_data['left'][1000] ?? '-'; ?>
                                                        </td>
                                                        <td>
                                                            <?php echo $results_data['left'][2000] ?? '-'; ?>
                                                        </td>
                                                        <td>
                                                            <?php echo $results_data['left'][4000] ?? '-'; ?>
                                                        </td>
                                                        <td>
                                                            <?php echo $results_data['left'][8000] ?? '-'; ?>
                                                        </td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>

                                        <div class="mt-4">
                                            <h6 class="mb-2">Bone Conduction</h6>
                                            <div class="row">
                                                <div class="col-md-6">
                                                    <table
                                                        class="table table-bordered table-caption-top table-sm text-center">
                                                        <caption>Right Ear [ < ]</caption>
                                                        <thead class="table-light">
                                                            <tr>
                                                                <th>500</th>
                                                                <th>1000</th>
                                                                <th>2000</th>
                                                                <th>4000</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <tr>
                                                                <td>
                                                                    <?php echo $results_data['bone_right'][500] ?? '-'; ?>
                                                                </td>
                                                                <td>
                                                                    <?php echo $results_data['bone_right'][1000] ?? '-'; ?>
                                                                </td>
                                                                <td>
                                                                    <?php echo $results_data['bone_right'][2000] ?? '-'; ?>
                                                                </td>
                                                                <td>
                                                                    <?php echo $results_data['bone_right'][4000] ?? '-'; ?>
                                                                </td>
                                                            </tr>
                                                        </tbody>
                                                    </table>
                                                </div>
                                                <div class="col-md-6">
                                                    <table
                                                        class="table table-bordered table-caption-top table-sm text-center">
                                                        <caption>Left Ear [ > ]</caption>
                                                        <thead class="table-light">
                                                            <tr>
                                                                <th>500</th>
                                                                <th>1000</th>
                                                                <th>2000</th>
                                                                <th>4000</th>
                                                            </tr>
                                                        </thead>
                                                        <tbody>
                                                            <tr>
                                                                <td>
                                                                    <?php echo $results_data['bone_left'][500] ?? '-'; ?>
                                                                </td>
                                                                <td>
                                                                    <?php echo $results_data['bone_left'][1000] ?? '-'; ?>
                                                                </td>
                                                                <td>
                                                                    <?php echo $results_data['bone_left'][2000] ?? '-'; ?>
                                                                </td>
                                                                <td>
                                                                    <?php echo $results_data['bone_left'][4000] ?? '-'; ?>
                                                                </td>
                                                            </tr>
                                                        </tbody>
                                                    </table>
                                                </div>
                                            </div>
                                        </div>

                                    <?php else: ?>
                                        <!-- Generic Result Display -->
                                        <div class="p-3 bg-light rounded">
                                            <pre
                                                class="mb-0"><?php echo htmlspecialchars($test['result_value'] ?? 'No results entered'); ?></pre>
                                        </div>
                                    <?php endif; ?>

                                    <!-- Interpretation -->
                                    <?php if (!empty($test['interpretation'])): ?>
                                        <div class="mt-4">
                                            <h6 class="text-uppercase text-muted fs-12 fw-bold">Clinical Interpretation</h6>
                                            <div class="p-3 border rounded bg-white">
                                                <?php echo nl2br(htmlspecialchars($test['interpretation'])); ?>
                                            </div>
                                        </div>
                                    <?php endif; ?>

                                </div>
                            </div>
                        </div>
                    </div>

                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
</body>

</html>