<?php
declare(strict_types=1);

require_once __DIR__ . '/includes/iscms_layout.php';

$conn = iscms_init();
$pageTitle = 'Lab test requests';
$activeNav = 'laboratory';

$sql = "SELECT lr.id, lr.request_number, lr.test_category, lr.test_type, lr.status, lr.priority,
               lr.required_by, lr.received_at, lr.completed_at,
               a.application_number,
               lab.lab_name,
               lab.lab_code,
               CONCAT(TRIM(ur.first_name),' ',TRIM(ur.last_name)) AS requested_by_name,
               CONCAT(TRIM(ua.first_name),' ',TRIM(ua.last_name)) AS assigned_officer_name
        FROM lab_test_requests lr
        INNER JOIN applications a ON lr.application_id = a.id
        LEFT JOIN laboratories lab ON lr.laboratory_id = lab.id
        INNER JOIN users ur ON lr.requested_by = ur.id
        LEFT JOIN users ua ON lr.assigned_lab_officer = ua.id
        ORDER BY lr.updated_at DESC
        LIMIT 400";
$result = $conn->query($sql);
$rows = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
$dbError = $result ? null : $conn->error;

iscms_render_head($pageTitle);
iscms_render_sidebar($activeNav);
iscms_render_topbar($pageTitle);
?>
    <div class="page-header">
        <h1>Lab test requests</h1>
        <p>Testing work linked to applications, labs, and officers.</p>
    </div>

    <div class="section-card mb-4">
        <div class="section-header">
            <h2><i class="ri-links-line"></i> Related registers</h2>
        </div>
        <div class="quick-actions">
            <a class="qa-btn" href="laboratories.php"><i class="ri-building-4-line"></i> Laboratories</a>
            <a class="qa-btn" href="lab_samples.php"><i class="ri-test-tube-line"></i> Samples</a>
            <a class="qa-btn" href="lab_test_results.php"><i class="ri-file-chart-line"></i> Results</a>
            <a class="qa-btn" href="lab_documents.php"><i class="ri-attachment-2"></i> Lab documents</a>
            <a class="qa-btn" href="applications.php"><i class="ri-file-list-3-line"></i> Applications</a>
        </div>
    </div>

    <div class="section-card">
        <div class="section-header">
            <h2><i class="ri-flask-line"></i> Requests</h2>
            <span class="text-muted" style="font-size:.75rem"><?= count($rows) ?> shown</span>
        </div>
        <div class="table-responsive">
            <?php if ($dbError): ?>
                <div class="alert alert-danger m-3" style="font-size:.85rem">Unable to load data: <?= iscms_h($dbError) ?></div>
            <?php else: ?>
            <table class="ssbs-table">
                <thead>
                    <tr>
                        <th>Request</th>
                        <th>Application</th>
                        <th>Lab</th>
                        <th>Category</th>
                        <th>Test type</th>
                        <th>Priority</th>
                        <th>Status</th>
                        <th>Requested by</th>
                        <th>Required by</th>
                        <th>Received</th>
                        <th>Completed</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($rows)): ?>
                    <tr class="empty-row"><td colspan="11"><i class="ri-inbox-line me-2"></i>No requests</td></tr>
                    <?php else: ?>
                        <?php foreach ($rows as $r): ?>
                        <?php
                            $pri = strtolower((string) ($r['priority'] ?? 'normal'));
                            $priCls = match ($pri) {
                                'critical' => 'bg-danger-subtle text-danger',
                                'urgent' => 'bg-warning-subtle text-warning',
                                default => 'bg-secondary-subtle text-secondary',
                            };
                            $priLabel = ucfirst($pri);
                            $labDisp = trim((string) ($r['lab_name'] ?? ''));
                            if ($labDisp === '') {
                                $labDisp = '-';
                            } else {
                                $code = trim((string) ($r['lab_code'] ?? ''));
                                $labDisp = $code !== '' ? $labDisp . ' (' . $code . ')' : $labDisp;
                            }
                        ?>
                        <tr>
                            <td class="iscms-mono" style="font-weight:600; color:var(--ssbs-blue)"><?= iscms_h($r['request_number']) ?></td>
                            <td class="iscms-mono"><small><?= iscms_h($r['application_number']) ?></small></td>
                            <td><small><?= iscms_h($labDisp) ?></small></td>
                            <td><small><?= iscms_val($r['test_category'] ?? null) ?></small></td>
                            <td><small><?= iscms_h(str_replace('_', ' ', (string) $r['test_type'])) ?></small></td>
                            <td><span class="badge <?= $priCls ?>" style="font-size:.65rem"><?= iscms_h($priLabel) ?></span></td>
                            <td><?= iscms_status_badge((string) ($r['status'] ?? '')) ?></td>
                            <td><small><?= iscms_h(trim((string) ($r['requested_by_name'] ?? ''))) ?></small></td>
                            <td><small class="text-muted"><?= iscms_val($r['required_by'] ?? null) ?></small></td>
                            <td><small class="text-muted"><?= !empty($r['received_at']) ? iscms_h(substr((string) $r['received_at'], 0, 16)) : '-' ?></small></td>
                            <td><small class="text-muted"><?= !empty($r['completed_at']) ? iscms_h(substr((string) $r['completed_at'], 0, 16)) : '-' ?></small></td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>
    </div>
<?php
iscms_render_footer();
