<?php
declare(strict_types=1);

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

$conn = iscms_init();
$pageTitle = 'Application queue';
$activeNav = 'queue';

$queueStatuses = [
    'submitted', 'under_review', 'pending_payment', 'payment_confirmed', 'in_progress',
    'awaiting_inspection', 'awaiting_lab', 'awaiting_decision', 'on_hold',
];
$inList = "'" . implode("','", array_map(static fn ($s) => $conn->real_escape_string($s), $queueStatuses)) . "'";

$sql = "SELECT a.id, a.application_number, a.application_type, a.status, a.priority,
               a.submitted_at, a.due_date,
               o.org_name,
               p.product_name
        FROM applications a
        INNER JOIN organizations o ON a.org_id = o.id
        LEFT JOIN products p ON a.product_id = p.id
        WHERE a.status IN ($inList)
        ORDER BY
            FIELD(a.status,'submitted','under_review','pending_payment','awaiting_inspection','awaiting_lab','awaiting_decision','in_progress','on_hold','payment_confirmed'),
            a.due_date IS NULL, a.due_date ASC,
            a.submitted_at DESC
        LIMIT 300";
$result = $conn->query($sql);
$rows = $result ? $result->fetch_all(MYSQLI_ASSOC) : [];
$dbError = $result ? null : $conn->error;

$cntRes = $conn->query("SELECT COUNT(*) AS n FROM applications WHERE status IN ($inList)");
$queueCount = (int) ($cntRes ? ($cntRes->fetch_assoc()['n'] ?? 0) : 0);

iscms_render_head($pageTitle);
iscms_render_sidebar($activeNav);
iscms_render_topbar($pageTitle);
?>
    <div class="page-header">
        <h1>Application queue</h1>
        <p>Applications that are in-flight and need staff action (excludes draft, closed, withdrawn).</p>
    </div>

    <div class="kpi-grid mb-4">
        <div class="kpi-card" style="--card-color:#2a5298; --card-color-light:#e8f0fb">
            <div class="kpi-icon"><i class="ri-stack-line"></i></div>
            <div>
                <div class="kpi-value"><?= number_format($queueCount) ?></div>
                <div class="kpi-label">In queue</div>
            </div>
        </div>
    </div>

    <div class="section-card mb-4">
        <div class="section-header">
            <h2><i class="ri-links-line"></i> Quick links</h2>
        </div>
        <div class="quick-actions">
            <a class="qa-btn" href="applications.php"><i class="ri-file-list-3-line"></i> All applications</a>
            <a class="qa-btn" href="viewed_queue.php"><i class="ri-history-line"></i> Recent activity</a>
        </div>
    </div>

    <div class="section-card">
        <div class="section-header">
            <h2><i class="ri-list-check-2"></i> Queue</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>Number</th>
                        <th>Type</th>
                        <th>Organisation</th>
                        <th>Product</th>
                        <th>Status</th>
                        <th>Priority</th>
                        <th>Submitted</th>
                        <th>Due</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($rows)): ?>
                    <tr class="empty-row"><td colspan="8"><i class="ri-checkbox-circle-line me-2"></i>Queue is empty</td></tr>
                    <?php else: ?>
                        <?php foreach ($rows as $r): ?>
                        <tr>
                            <td class="iscms-mono" style="font-weight:600; color:var(--ssbs-blue)"><?= iscms_h($r['application_number']) ?></td>
                            <td><small><?= iscms_h(str_replace('_', ' ', (string) $r['application_type'])) ?></small></td>
                            <td><small><?= iscms_h($r['org_name']) ?></small></td>
                            <td><small><?= iscms_val($r['product_name'] ?? null) ?></small></td>
                            <td><?= iscms_status_badge((string) ($r['status'] ?? '')) ?></td>
                            <td><?= iscms_priority_badge((int) ($r['priority'] ?? 3)) ?></td>
                            <td><small class="text-muted"><?= !empty($r['submitted_at']) ? iscms_h(substr((string) $r['submitted_at'], 0, 16)) : '-' ?></small></td>
                            <td><small class="text-muted"><?= iscms_val($r['due_date'] ?? null) ?></small></td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>
    </div>
<?php
iscms_render_footer();
