<?php
declare(strict_types=1);

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

$conn = iscms_init();
$pageTitle = 'Applications';
$activeNav = 'applications';

$allowedStatus = [
    '', 'draft', 'submitted', 'under_review', 'pending_payment', 'payment_confirmed',
    'in_progress', 'awaiting_inspection', 'awaiting_lab', 'awaiting_decision',
    'approved', 'rejected', 'withdrawn', 'on_hold', 'closed',
];
$statusFilter = isset($_GET['status']) ? (string) $_GET['status'] : '';
if (!in_array($statusFilter, $allowedStatus, true)) {
    $statusFilter = '';
}

$sql = "SELECT a.id, a.application_number, a.application_type, a.status, a.priority,
               a.submitted_at, a.due_date, a.fee_paid, a.updated_at,
               o.org_name,
               p.product_name,
               CONCAT(TRIM(u.first_name),' ',TRIM(u.last_name)) AS submitted_by_name,
               CONCAT(TRIM(ua.first_name),' ',TRIM(ua.last_name)) AS assigned_to_name
        FROM applications a
        INNER JOIN organizations o ON a.org_id = o.id
        LEFT JOIN products p ON a.product_id = p.id
        INNER JOIN users u ON a.submitted_by = u.id
        LEFT JOIN users ua ON a.assigned_to = ua.id";
if ($statusFilter !== '') {
    $sql .= " WHERE a.status = '" . $conn->real_escape_string($statusFilter) . "'";
}
$sql .= " ORDER BY COALESCE(a.submitted_at, a.created_at) DESC LIMIT 500";

$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>Applications</h1>
        <p>Central workflow hub: registrations, certification, permits, and renewals.</p>
    </div>

    <div class="section-card mb-4">
        <div class="section-header">
            <h2><i class="ri-filter-3-line"></i> Filter</h2>
        </div>
        <div class="p-3 d-flex flex-wrap align-items-end gap-3" style="font-size:.85rem">
            <form method="get" class="d-flex flex-wrap align-items-end gap-2">
                <div>
                    <label class="form-label text-muted mb-1" style="font-size:.72rem">Status</label>
                    <select name="status" class="form-select form-select-sm" style="min-width:200px">
                        <option value="">All statuses</option>
                        <?php foreach (array_slice($allowedStatus, 1) as $st): ?>
                        <option value="<?= iscms_h($st) ?>" <?= $statusFilter === $st ? 'selected' : '' ?>><?= iscms_h(ucwords(str_replace('_', ' ', $st))) ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>
                <button type="submit" class="btn btn-sm btn-primary">Apply</button>
                <?php if ($statusFilter !== ''): ?>
                <a href="applications.php" class="btn btn-sm btn-outline-secondary">Clear</a>
                <?php endif; ?>
            </form>
        </div>
    </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="application_documents.php"><i class="ri-attachment-2"></i> Documents</a>
            <a class="qa-btn" href="application_status_history.php"><i class="ri-git-commit-line"></i> Status history</a>
            <a class="qa-btn" href="application_comments.php"><i class="ri-chat-3-line"></i> Comments</a>
            <a class="qa-btn" href="workflow_templates.php"><i class="ri-flow-chart"></i> Workflow templates</a>
            <a class="qa-btn" href="queue_dashboard.php"><i class="ri-stack-line"></i> Queue</a>
        </div>
    </div>

    <div class="section-card">
        <div class="section-header">
            <h2><i class="ri-file-list-3-line"></i> Application register</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>
                        <th>Fee paid</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($rows)): ?>
                    <tr class="empty-row"><td colspan="9"><i class="ri-inbox-line me-2"></i>No applications match this filter</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>
                            <td><?= !empty($r['fee_paid']) ? '<span class="badge bg-success-subtle text-success" style="font-size:.65rem">Yes</span>' : '<span class="badge bg-secondary-subtle text-secondary" style="font-size:.65rem">No</span>' ?></td>
                        </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
            <?php endif; ?>
        </div>
    </div>
<?php
iscms_render_footer();
