<?php
session_start();
header('Content-Type: text/html; charset=utf-8');

include '../layouts/dbconn.php';

// Check authentication
if (!isset($_SESSION['user_id'])) {
    echo '<div class="alert alert-danger">Unauthorized access</div>';
    exit();
}

if (!isset($_POST['patient_id'])) {
    echo '<div class="alert alert-danger">Missing patient ID</div>';
    exit();
}

$patient_id = intval($_POST['patient_id']);

// Get lab orders for this patient
$query = "SELECT 
    lo.*,
    ett.test_name,
    ett.category,
    ett.sample_type,
    ett.normal_range,
    ett.estimated_time,
    c.consultation_id,
    c.consultation_date,
    ordered_user.full_name as ordered_by_name,
    performed_user.full_name as performed_by_name
FROM lab_orders lo
INNER JOIN ent_test_types ett ON lo.test_type_id = ett.test_type_id
LEFT JOIN consultations c ON lo.consultation_id = c.consultation_id
INNER JOIN users ordered_user ON lo.ordered_by = ordered_user.user_id
LEFT JOIN users performed_user ON lo.performed_by = performed_user.user_id
WHERE lo.patient_id = ?
ORDER BY lo.order_date DESC";

$stmt = $conn->prepare($query);
$stmt->bind_param("i", $patient_id);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows == 0) {
    echo '<div class="alert alert-info">No lab tests found for this patient.</div>';
    exit();
}
?>

<div class="table-responsive">
    <table class="table table-hover align-middle">
        <thead class="table-light">
            <tr>
                <th>Order Date</th>
                <th>Test Name</th>
                <th>Category</th>
                <th>Sample Type</th>
                <th>Ordered By</th>
                <th>Status</th>
                <th>Priority</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <?php while ($lab_test = $result->fetch_assoc()): ?>
            <tr>
                <td>
                    <?php echo date('M d, Y', strtotime($lab_test['order_date'])); ?>
                    <br>
                    <small class="text-muted"><?php echo date('h:i A', strtotime($lab_test['order_date'])); ?></small>
                </td>
                <td>
                    <strong><?php echo htmlspecialchars($lab_test['test_name']); ?></strong>
                    <?php if ($lab_test['special_instructions']): ?>
                    <br><small class="text-muted"><?php echo htmlspecialchars(substr($lab_test['special_instructions'], 0, 40)) . '...'; ?></small>
                    <?php endif; ?>
                </td>
                <td>
                    <span class="badge bg-info"><?php echo htmlspecialchars($lab_test['category']); ?></span>
                </td>
                <td>
                    <?php echo htmlspecialchars($lab_test['sample_type'] ?: 'N/A'); ?>
                    <?php if ($lab_test['sample_collected_date']): ?>
                    <br><small class="text-success">Collected: <?php echo date('M d', strtotime($lab_test['sample_collected_date'])); ?></small>
                    <?php endif; ?>
                </td>
                <td>
                    <?php echo htmlspecialchars($lab_test['ordered_by_name']); ?>
                    <br>
                    <small class="text-muted"><?php echo htmlspecialchars($lab_test['estimated_time'] ?: 'Standard'); ?></small>
                </td>
                <td>
                    <?php
                    $status_badge = [
                        'ORDERED' => 'secondary',
                        'SAMPLE_COLLECTED' => 'info',
                        'IN_PROGRESS' => 'warning',
                        'COMPLETED' => 'success',
                        'CANCELLED' => 'danger',
                        'REJECTED' => 'danger'
                    ];
                    $badge_class = $status_badge[$lab_test['status']] ?? 'secondary';
                    ?>
                    <span class="badge bg-<?php echo $badge_class; ?>">
                        <?php echo str_replace('_', ' ', htmlspecialchars($lab_test['status'])); ?>
                    </span>
                    <?php if ($lab_test['completed_date']): ?>
                    <br><small class="text-success">Completed: <?php echo date('M d', strtotime($lab_test['completed_date'])); ?></small>
                    <?php endif; ?>
                </td>
                <td>
                    <?php
                    $priority_badge = [
                        'ROUTINE' => 'secondary',
                        'URGENT' => 'warning',
                        'STAT' => 'danger'
                    ];
                    $priority_class = $priority_badge[$lab_test['priority']] ?? 'secondary';
                    ?>
                    <span class="badge bg-<?php echo $priority_class; ?>">
                        <?php echo htmlspecialchars($lab_test['priority']); ?>
                    </span>
                </td>
                <td>
                    <div class="btn-group btn-group-sm">
                        <?php if ($lab_test['status'] == 'COMPLETED'): ?>
                        <a href="view_lab_result.php?id=<?php echo $lab_test['order_id']; ?>" 
                           class="btn btn-outline-success" title="View Results">
                            <i class="ri-file-list-line"></i>
                        </a>
                        <?php endif; ?>
                        <?php if ($lab_test['consultation_id']): ?>
                        <a href="view_consultation.php?id=<?php echo $lab_test['consultation_id']; ?>" 
                           class="btn btn-outline-info" title="View Consultation">
                            <i class="ri-file-text-line"></i>
                        </a>
                        <?php endif; ?>
                    </div>
                </td>
            </tr>
            <?php endwhile; ?>
        </tbody>
    </table>
</div>

<?php
$conn->close();
?>