<?php
/**
 * View Test Results Page
 * Display completed test results for lab tests
 */

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

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

$test_id = isset($_GET['test_id']) ? intval($_GET['test_id']) : 0;

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

// Fetch test details with all related information
$test_sql = "SELECT 
    lot.order_test_id, lot.order_id, lot.status, lot.result_value, lot.result_unit,
    lot.reference_range, lot.interpretation, lot.abnormal_flag, lot.result_files,
    lot.tested_by, lot.verified_by, lot.started_at, lot.completed_at, lot.created_at,
    lo.order_number, lo.order_date, lo.priority, lo.clinical_notes,
    p.patient_id, p.patient_number,
    u.full_name as patient_name, u.gender, u.date_of_birth, u.phone_primary, u.email,
    ett.test_name, ett.test_code, ett.category, ett.normal_range, ett.sample_type,
    ett.description as test_description,
    tech_user.full_name as technician_name,
    ver_user.full_name as verified_by_name,
    doc_user.full_name as ordered_by_name
FROM lab_order_tests lot
INNER JOIN lab_orders lo ON lot.order_id = lo.order_id
INNER JOIN patients p ON lo.patient_id = p.patient_id
INNER JOIN users u ON p.user_id = u.user_id
INNER JOIN ent_test_types ett ON lot.test_type_id = ett.test_type_id
LEFT JOIN users tech_user ON lot.tested_by = tech_user.user_id
LEFT JOIN users ver_user ON lot.verified_by = ver_user.user_id
LEFT JOIN users doc_user ON lo.ordered_by = doc_user.user_id
WHERE lot.order_test_id = ?";

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

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

// 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;
}

// Parse result files if JSON
$result_files = [];
if ($test['result_files']) {
    $result_files = json_decode($test['result_files'], true);
    if (!is_array($result_files)) {
        $result_files = [];
    }
}

// Parse result value if JSON (for audiometry tests)
$results_data = null;
if ($test['result_value']) {
    $decoded = json_decode($test['result_value'], true);
    if (json_last_error() === JSON_ERROR_NONE && is_array($decoded)) {
        $results_data = $decoded;
    }
}

$page_title = "Test Results - " . htmlspecialchars($test['test_name']);
?>

<?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>
        .result-card {
            background: white;
            border-radius: 12px;
            padding: 1.5rem;
            box-shadow: 0 1px 3px rgba(0,0,0,0.1);
            margin-bottom: 1.5rem;
            border: 1px solid #e2e8f0;
        }
        .result-header {
            border-bottom: 2px solid #e2e8f0;
            padding-bottom: 1rem;
            margin-bottom: 1.5rem;
        }
        .result-value {
            font-size: 1.5rem;
            font-weight: 700;
            margin: 0.5rem 0;
        }
        .result-value.normal {
            color: #10b981;
        }
        .result-value.abnormal {
            color: #ef4444;
        }
        .result-value.high {
            color: #f59e0b;
        }
        .result-value.low {
            color: #3b82f6;
        }
        .info-row {
            display: flex;
            justify-content: space-between;
            padding: 0.75rem 0;
            border-bottom: 1px solid #f1f5f9;
        }
        .info-row:last-child {
            border-bottom: none;
        }
        .info-label {
            font-weight: 600;
            color: #64748b;
            min-width: 150px;
        }
        .info-value {
            color: #1e293b;
            flex: 1;
        }
        .file-item {
            display: flex;
            align-items: center;
            padding: 0.75rem;
            background: #f8fafc;
            border-radius: 8px;
            margin-bottom: 0.5rem;
        }
        .file-icon {
            font-size: 2rem;
            margin-right: 1rem;
            color: #3b82f6;
        }
    </style>
</head>

<body>
    <div id="layout-wrapper">
        <?php include 'layouts/menu.php'; ?>
        
        <div class="main-content">
            <div class="page-content">
                <div class="container-fluid">
                    
                    <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="pending_lab_tests.php">Pending Tests</a></li>
                                        <li class="breadcrumb-item active">Test Results</li>
                                    </ol>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Test Information Card -->
                    <div class="result-card">
                        <div class="result-header">
                            <h5 class="mb-0">
                                <i class="ri-file-text-line me-2"></i>
                                Test Information
                            </h5>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="info-row">
                                    <span class="info-label">Order Number:</span>
                                    <span class="info-value"><strong><?php echo htmlspecialchars($test['order_number']); ?></strong></span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Test Name:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($test['test_name']); ?> (<?php echo htmlspecialchars($test['test_code']); ?>)</span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Category:</span>
                                    <span class="info-value">
                                        <span class="badge bg-info"><?php echo htmlspecialchars($test['category']); ?></span>
                                    </span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Status:</span>
                                    <span class="info-value">
                                        <span class="badge bg-<?php echo $test['status'] == 'COMPLETED' ? 'success' : 'warning'; ?>">
                                            <?php echo htmlspecialchars($test['status']); ?>
                                        </span>
                                    </span>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="info-row">
                                    <span class="info-label">Ordered Date:</span>
                                    <span class="info-value"><?php echo date('M d, Y H:i', strtotime($test['order_date'])); ?></span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Started At:</span>
                                    <span class="info-value">
                                        <?php echo $test['started_at'] ? date('M d, Y H:i', strtotime($test['started_at'])) : 'N/A'; ?>
                                    </span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Completed At:</span>
                                    <span class="info-value">
                                        <?php echo $test['completed_at'] ? date('M d, Y H:i', strtotime($test['completed_at'])) : 'N/A'; ?>
                                    </span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Priority:</span>
                                    <span class="info-value">
                                        <span class="badge bg-<?php 
                                            echo $test['priority'] == 'STAT' ? 'danger' : 
                                                ($test['priority'] == 'URGENT' ? 'warning' : 'secondary'); 
                                        ?>">
                                            <?php echo htmlspecialchars($test['priority']); ?>
                                        </span>
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Patient Information Card -->
                    <div class="result-card">
                        <div class="result-header">
                            <h5 class="mb-0">
                                <i class="ri-user-line me-2"></i>
                                Patient Information
                            </h5>
                        </div>
                        
                        <div class="row">
                            <div class="col-md-6">
                                <div class="info-row">
                                    <span class="info-label">Patient Name:</span>
                                    <span class="info-value"><strong><?php echo htmlspecialchars($test['patient_name']); ?></strong></span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Patient Number:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($test['patient_number']); ?></span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Age:</span>
                                    <span class="info-value"><?php echo $age !== null ? $age . ' years' : 'N/A'; ?></span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Gender:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($test['gender'] ?? 'N/A'); ?></span>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="info-row">
                                    <span class="info-label">Phone:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($test['phone_primary'] ?? 'N/A'); ?></span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Email:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($test['email'] ?? 'N/A'); ?></span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Ordered By:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($test['ordered_by_name'] ?? 'N/A'); ?></span>
                                </div>
                                <div class="info-row">
                                    <span class="info-label">Tested By:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($test['technician_name'] ?? 'N/A'); ?></span>
                                </div>
                            </div>
                        </div>
                    </div>
                    
                    <!-- Test Results Card -->
                    <?php if ($test['status'] == 'COMPLETED'): ?>
                    <div class="result-card">
                        <div class="result-header">
                            <h5 class="mb-0">
                                <i class="ri-file-list-3-line me-2"></i>
                                Test Results
                            </h5>
                        </div>
                        
                        <?php if ($results_data && is_array($results_data)): ?>
                            <!-- Structured Results (JSON) -->
                            <div class="table-responsive">
                                <table class="table table-bordered">
                                    <thead class="table-light">
                                        <tr>
                                            <th>Parameter</th>
                                            <th>Result</th>
                                            <th>Unit</th>
                                            <th>Reference Range</th>
                                            <th>Status</th>
                                        </tr>
                                    </thead>
                                    <tbody>
                                        <?php foreach ($results_data as $param => $value): ?>
                                        <tr>
                                            <td><strong><?php echo htmlspecialchars($param); ?></strong></td>
                                            <td><?php echo htmlspecialchars(is_array($value) ? json_encode($value) : $value); ?></td>
                                            <td><?php echo htmlspecialchars($test['result_unit'] ?? 'N/A'); ?></td>
                                            <td><?php echo htmlspecialchars($test['reference_range'] ?? $test['normal_range'] ?? 'N/A'); ?></td>
                                            <td>
                                                <span class="badge bg-<?php 
                                                    echo strtoupper($test['abnormal_flag']) == 'NORMAL' ? 'success' : 'danger'; 
                                                ?>">
                                                    <?php echo htmlspecialchars($test['abnormal_flag']); ?>
                                                </span>
                                            </td>
                                        </tr>
                                        <?php endforeach; ?>
                                    </tbody>
                                </table>
                            </div>
                        <?php else: ?>
                            <!-- Simple Text Result -->
                            <div class="mb-3">
                                <div class="info-row">
                                    <span class="info-label">Result Value:</span>
                                    <span class="info-value">
                                        <span class="result-value <?php echo strtolower($test['abnormal_flag'] ?? 'normal'); ?>">
                                            <?php echo htmlspecialchars($test['result_value']); ?>
                                            <?php if ($test['result_unit']): ?>
                                                <small><?php echo htmlspecialchars($test['result_unit']); ?></small>
                                            <?php endif; ?>
                                        </span>
                                    </span>
                                </div>
                                <?php if ($test['reference_range'] || $test['normal_range']): ?>
                                <div class="info-row">
                                    <span class="info-label">Reference Range:</span>
                                    <span class="info-value"><?php echo htmlspecialchars($test['reference_range'] ?? $test['normal_range']); ?></span>
                                </div>
                                <?php endif; ?>
                                <div class="info-row">
                                    <span class="info-label">Abnormal Flag:</span>
                                    <span class="info-value">
                                        <span class="badge bg-<?php 
                                            echo strtoupper($test['abnormal_flag']) == 'NORMAL' ? 'success' : 'danger'; 
                                        ?>">
                                            <?php echo htmlspecialchars($test['abnormal_flag'] ?? 'NORMAL'); ?>
                                        </span>
                                    </span>
                                </div>
                            </div>
                        <?php endif; ?>
                        
                        <?php if ($test['interpretation']): ?>
                        <div class="mt-3">
                            <h6>Interpretation:</h6>
                            <div class="alert alert-info">
                                <?php echo nl2br(htmlspecialchars($test['interpretation'])); ?>
                            </div>
                        </div>
                        <?php endif; ?>
                        
                        <?php if (!empty($result_files)): ?>
                        <div class="mt-4">
                            <h6>Result Files:</h6>
                            <?php foreach ($result_files as $file): ?>
                            <div class="file-item">
                                <i class="ri-file-line file-icon"></i>
                                <div class="flex-grow-1">
                                    <div><strong><?php echo htmlspecialchars($file['filename'] ?? 'Unknown'); ?></strong></div>
                                    <?php if (isset($file['uploaded_at'])): ?>
                                    <small class="text-muted">Uploaded: <?php echo date('M d, Y H:i', strtotime($file['uploaded_at'])); ?></small>
                                    <?php endif; ?>
                                </div>
                                <?php if (isset($file['path']) && file_exists($file['path'])): ?>
                                <a href="<?php echo htmlspecialchars($file['path']); ?>" target="_blank" class="btn btn-sm btn-primary">
                                    <i class="ri-download-line"></i> Download
                                </a>
                                <?php endif; ?>
                            </div>
                            <?php endforeach; ?>
                        </div>
                        <?php endif; ?>
                    </div>
                    <?php else: ?>
                    <div class="result-card">
                        <div class="alert alert-warning">
                            <i class="ri-alert-line me-2"></i>
                            This test has not been completed yet. Results will be displayed here once the test is completed.
                        </div>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Clinical Notes -->
                    <?php if ($test['clinical_notes']): ?>
                    <div class="result-card">
                        <div class="result-header">
                            <h5 class="mb-0">
                                <i class="ri-file-text-line me-2"></i>
                                Clinical Notes
                            </h5>
                        </div>
                        <p class="mb-0"><?php echo nl2br(htmlspecialchars($test['clinical_notes'])); ?></p>
                    </div>
                    <?php endif; ?>
                    
                    <!-- Action Buttons -->
                    <div class="row">
                        <div class="col-12">
                            <div class="d-flex gap-2">
                                <a href="pending_lab_tests.php" class="btn btn-secondary">
                                    <i class="ri-arrow-left-line me-1"></i> Back to Pending Tests
                                </a>
                                <?php if ($test['status'] == 'COMPLETED'): ?>
                                <button onclick="window.print()" class="btn btn-primary">
                                    <i class="ri-printer-line me-1"></i> Print Results
                                </button>
                                <?php endif; ?>
                            </div>
                        </div>
                    </div>
                    
                </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 src="assets/js/app.js"></script>
</body>
</html>
