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

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

// Get user role to filter appropriately
$user_id = $_SESSION['user_id'];
$role_code = $_SESSION['role_code'] ?? '';

// Build query based on role
if ($role_code === 'AUDIOLOGIST') {
    // For audiologists, show only audiometry and vestibular tests
    // Show ALL pending tests regardless of tested_by assignment
    $sql = "SELECT t.order_test_id, t.order_id, t.test_type_id, t.status, t.created_at,
                   o.order_number, p.patient_number, u.full_name as patient_name,
                   tt.test_name, tt.category, tt.test_code
            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
            WHERE t.status IN ('PENDING', 'IN_PROGRESS', 'SCHEDULED', 'SAMPLE_COLLECTED')
            AND tt.category IN ('AUDIOMETRY', 'VESTIBULAR')
            AND (tt.is_active = 1 OR tt.is_active IS NULL)
            ORDER BY 
                CASE t.status
                    WHEN 'SCHEDULED' THEN 1
                    WHEN 'SAMPLE_COLLECTED' THEN 2
                    WHEN 'PENDING' THEN 3
                    ELSE 4
                END,
                t.created_at ASC";
    $result = $conn->query($sql);
    
    // Debug: Log query result count (remove in production)
    if (!$result) {
        error_log("Pending Lab Tests Query Error: " . $conn->error);
    }
} else {
    // For other roles (lab technicians, etc.), show all pending tests
    $sql = "SELECT t.order_test_id, t.order_id, t.test_type_id, t.status, t.created_at,
                   o.order_number, p.patient_number, u.full_name as patient_name,
                   tt.test_name, tt.category, tt.test_code
            FROM lab_order_tests t
            JOIN lab_orders o ON t.order_id = o.order_id
            JOIN patients p ON o.patient_id = p.patient_id
            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
            WHERE t.status IN ('PENDING', 'SCHEDULED', 'SAMPLE_COLLECTED')
            AND tt.test_type_id IS NOT NULL
            ORDER BY 
                CASE t.status
                    WHEN 'SCHEDULED' THEN 1
                    WHEN 'SAMPLE_COLLECTED' THEN 2
                    WHEN 'PENDING' THEN 3
                    ELSE 4
                END,
                t.created_at ASC";
    $result = $conn->query($sql);
}
?>

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

<head>
    <?php includeFileWithVariables('layouts/title-meta.php', array('title' => 'Pending Lab Tests')); ?>
    <?php include 'layouts/head-css.php'; ?>
    <link href="assets/libs/datatables.net-bs5/css/dataTables.bootstrap5.min.css" rel="stylesheet" />
</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">
                            <h4 class="mb-sm-0">Pending Lab Tests</h4>
                        </div>
                    </div>

                    <div class="card">
                        <div class="card-body">
                            <table id="pendingTable" class="table table-bordered dt-responsive nowrap">
                                <thead>
                                    <tr>
                                        <th>Order #</th>
                                        <th>Patient</th>
                                        <th>Test Name</th>
                                        <th>Ordered At</th>
                                        <th>Status</th>
                                        <th>Action</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php 
                                    if ($result && $result->num_rows > 0): 
                                        while ($row = $result->fetch_assoc()): 
                                    ?>
                                        <tr>
                                            <td><?php echo htmlspecialchars($row['order_number'] ?? 'N/A'); ?></td>
                                            <td><?php echo htmlspecialchars($row['patient_name'] ?? 'N/A'); ?></td>
                                            <td>
                                                <?php echo htmlspecialchars($row['test_name'] ?? 'N/A'); ?>
                                                <?php if (isset($row['test_code'])): ?>
                                                    <small class="text-muted d-block"><?php echo htmlspecialchars($row['test_code']); ?></small>
                                                <?php endif; ?>
                                            </td>
                                            <td><?php echo date('M d, Y H:i', strtotime($row['created_at'])); ?></td>
                                            <td>
                                                <span class="badge bg-<?php 
                                                    echo $row['status'] == 'PENDING' ? 'warning' : 
                                                        ($row['status'] == 'SCHEDULED' ? 'info' : 'primary'); 
                                                ?>">
                                                    <?php echo htmlspecialchars($row['status']); ?>
                                                </span>
                                            </td>
                                            <td>
                                                <?php if ($row['status'] == 'PENDING' || $row['status'] == 'SCHEDULED'): ?>
                                                    <?php if ($role_code === 'AUDIOLOGIST'): ?>
                                                        <a href="start_audio_test.php?test_id=<?php echo $row['order_test_id']; ?>"
                                                            class="btn btn-sm btn-success">Start Test</a>
                                                    <?php else: ?>
                                                        <a href="sample_collection.php?test_id=<?php echo $row['order_test_id']; ?>"
                                                            class="btn btn-sm btn-primary">Collect Sample</a>
                                                    <?php endif; ?>
                                                <?php elseif ($row['status'] == 'SAMPLE_COLLECTED'): ?>
                                                    <a href="test_results_entry.php?test_id=<?php echo $row['order_test_id']; ?>"
                                                        class="btn btn-sm btn-success">Start Test</a>
                                                <?php else: ?>
                                                    <a href="view_test_results.php?test_id=<?php echo $row['order_test_id']; ?>"
                                                        class="btn btn-sm btn-info">View</a>
                                                <?php endif; ?>
                                            </td>
                                        </tr>
                                    <?php 
                                        endwhile; 
                                    else: 
                                    ?>
                                        <tr>
                                            <td colspan="6" class="text-center">No pending tests found</td>
                                        </tr>
                                    <?php endif; ?>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <?php include 'layouts/footer.php'; ?>
        </div>
    </div>
    <?php include 'layouts/vendor-scripts.php'; ?>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="assets/libs/datatables.net/js/jquery.dataTables.min.js"></script>
    <script src="assets/libs/datatables.net-bs5/js/dataTables.bootstrap5.min.js"></script>
    <script>$('#pendingTable').DataTable();</script>
</body>

</html>