<?php
declare(strict_types=1);
require_once __DIR__ . '/../includes/middleware.php';
require_once __DIR__ . '/../config/database.php';
require_admin();
include __DIR__ . '/../includes/header.php';
?>

<style>
/* Professional Verification Dashboard */
.dashboard-header { display: flex; justify-content: space-between; align-items: flex-end; margin-bottom: 32px; gap: 20px; flex-wrap: wrap; }
.dashboard-title { margin: 0; font-size: 28px; font-weight: 800; color: var(--text); letter-spacing: -0.5px; }
.dashboard-subtitle { margin: 4px 0 0; color: var(--muted); font-size: 15px; }

/* Queue Grid */
.queue-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(350px, 1fr)); gap: 24px; margin-bottom: 32px; }
.queue-card { background: #fff; border: 1px solid var(--border); border-radius: 16px; overflow: hidden; }
.queue-header { padding: 20px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; }
.queue-title { font-size: 18px; font-weight: 700; color: var(--text); margin: 0; }
.queue-count { background: var(--primary); color: #fff; padding: 4px 12px; border-radius: 99px; font-size: 12px; font-weight: 600; }

/* Queue Items */
.queue-items { max-height: 400px; overflow-y: auto; }
.queue-item { padding: 16px 20px; border-bottom: 1px solid #f1f5f9; display: flex; align-items: flex-start; gap: 12px; transition: all 0.2s; cursor: pointer; }
.queue-item:hover { background: #f8fafc; }
.queue-item:last-child { border-bottom: none; }

.priority-high { border-left: 4px solid #dc2626; }
.priority-normal { border-left: 4px solid #f59e0b; }
.priority-low { border-left: 4px solid #10b981; }

.item-info { flex: 1; min-width: 0; }
.item-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 4px; }
.item-title { font-weight: 600; color: var(--text); font-size: 14px; }
.item-meta { display: flex; gap: 8px; align-items: center; }
.item-type { background: #e0e7ff; color: #3730a3; padding: 2px 8px; border-radius: 4px; font-size: 11px; font-weight: 500; }
.item-date { font-size: 12px; color: var(--muted); }
.item-client { font-size: 13px; color: var(--muted); margin-top: 2px; }

/* Status Pills */
.status-pending { background: #fef3c7; color: #d97706; }
.status-reviewing { background: #dbeafe; color: #1e40af; }
.status-verified { background: #dcfce7; color: #166534; }
.status-flagged { background: #fee2e2; color: #dc2626; }

/* Risk Assessment */
.risk-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 20px; margin-bottom: 32px; }
.risk-card { background: #fff; border: 1px solid var(--border); border-radius: 12px; padding: 20px; }
.risk-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 16px; }
.risk-title { font-size: 16px; font-weight: 700; color: var(--text); margin: 0; }
.risk-score { font-size: 24px; font-weight: 800; padding: 4px 12px; border-radius: 8px; }
.risk-low { background: #dcfce7; color: #166534; }
.risk-medium { background: #fef3c7; color: #d97706; }
.risk-high { background: #fee2e2; color: #dc2626; }

/* Compliance Tracking */
.compliance-list { background: #fff; border: 1px solid var(--border); border-radius: 12px; overflow: hidden; }
.compliance-header { padding: 20px; background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%); border-bottom: 1px solid var(--border); }
.compliance-title { font-size: 18px; font-weight: 700; color: var(--text); margin: 0; }
.compliance-items { max-height: 300px; overflow-y: auto; }
.compliance-item { padding: 12px 20px; border-bottom: 1px solid #f1f5f9; display: flex; justify-content: space-between; align-items: center; }
.compliance-item:last-child { border-bottom: none; }
.compliance-info { flex: 1; }
.compliance-name { font-weight: 600; color: var(--text); font-size: 14px; margin-bottom: 2px; }
.compliance-app { font-size: 12px; color: var(--muted); }
.compliance-status { padding: 4px 12px; border-radius: 99px; font-size: 12px; font-weight: 500; }
.status-completed { background: #dcfce7; color: #166534; }
.status-overdue { background: #fee2e2; color: #dc2626; }
.status-pending { background: #f3f4f6; color: #6b7280; }

/* Mobile */
@media (max-width: 768px) {
    .queue-grid { grid-template-columns: 1fr; }
    .risk-grid { grid-template-columns: 1fr; }
    .dashboard-header { flex-direction: column; align-items: flex-start; }
}
</style>

<div class="admin-header">
    <div>
        <h1 class="dashboard-title">Verification Dashboard</h1>
        <p class="dashboard-subtitle">Professional operations management with risk assessment and compliance tracking</p>
    </div>
    <div style="display:flex; gap:12px">
        <a href="/admin/dashboard.php" class="btn"><?=ui_icon('dashboard', 16)?> Dashboard</a>
        <a href="/admin/applications.php" class="btn"><?=ui_icon('open', 16)?> Applications</a>
    </div>
</div>

<?php
// Get verification queue data
$verificationQueue = $pdo->query("
    SELECT a.*, s.service_name, u.full_name as client_name,
           COUNT(vc.id) as verification_count,
           MAX(CASE WHEN vc.status = 'pending' THEN 1 ELSE 0 END) as has_pending_verification
    FROM applications a
    JOIN services s ON a.service_id = s.id
    JOIN users u ON a.user_id = u.id
    LEFT JOIN verification_checkpoints vc ON a.id = vc.application_id
    LEFT JOIN verification_checkpoints vc2 ON a.id = vc2.application_id AND vc2.status = 'pending'
    WHERE a.status IN ('draft', 'submitted', 'processing')
    GROUP BY a.id
    ORDER BY a.priority_level DESC, a.created_at ASC
    LIMIT 20
")->fetchAll();

// Group by priority level
$highPriority = array_filter($verificationQueue, fn($app) => $app['priority_level'] === 'high');
$normalPriority = array_filter($verificationQueue, fn($app) => $app['priority_level'] === 'normal');
$lowPriority = array_filter($verificationQueue, fn($app) => $app['priority_level'] === 'low');

// Get risk assessment data
$riskData = $pdo->query("
    SELECT 
        COUNT(CASE WHEN a.risk_score >= 80 THEN 1 END) as high_risk,
        COUNT(CASE WHEN a.risk_score >= 50 AND a.risk_score < 80 THEN 1 END) as medium_risk,
        COUNT(CASE WHEN a.risk_score < 50 THEN 1 END) as low_risk,
        AVG(a.risk_score) as avg_risk_score
    FROM applications a
    WHERE a.status IN ('draft', 'submitted', 'processing')
")->fetch();

// Get compliance tracking data
$complianceData = $pdo->query("
    SELECT ct.*, a.id as app_id, u.full_name as client_name, s.service_name
    FROM compliance_tracking ct
    JOIN applications a ON ct.application_id = a.id
    JOIN users u ON a.user_id = u.id
    JOIN services s ON a.service_id = s.id
    WHERE ct.status IN ('pending', 'overdue')
    ORDER BY ct.due_date ASC
    LIMIT 10
")->fetchAll();
?>

<!-- Verification Queue -->
<div class="queue-grid">
    <div class="queue-card">
        <div class="queue-header">
            <h2 class="queue-title">🔴 High Priority</h2>
            <span class="queue-count"><?=count($highPriority)?></span>
        </div>
        <div class="queue-items">
            <?php if (empty($highPriority)): ?>
                <div style="padding: 40px; text-align: center; color: var(--muted);">
                    No high priority applications
                </div>
            <?php else: foreach ($highPriority as $app): ?>
                <div class="queue-item priority-high" onclick="window.location.href='/admin/applications.php?view=<?=$app['id']?>'">
                    <div class="item-info">
                        <div class="item-header">
                            <div class="item-title">#<?=$app['id']?> - <?=$app['client_name']?></div>
                            <div class="item-meta">
                                <span class="item-type"><?=e($app['service_name'])?></span>
                                <span class="item-date"><?=date('M j', strtotime($app['created_at']))?></span>
                            </div>
                        </div>
                        <div class="item-client"><?=e($app['service_name'])?></div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>

    <div class="queue-card">
        <div class="queue-header">
            <h2 class="queue-title">🟡 Normal Priority</h2>
            <span class="queue-count"><?=count($normalPriority)?></span>
        </div>
        <div class="queue-items">
            <?php if (empty($normalPriority)): ?>
                <div style="padding: 40px; text-align: center; color: var(--muted);">
                    No normal priority applications
                </div>
            <?php else: foreach ($normalPriority as $app): ?>
                <div class="queue-item priority-normal" onclick="window.location.href='/admin/applications.php?view=<?=$app['id']?>'">
                    <div class="item-info">
                        <div class="item-header">
                            <div class="item-title">#<?=$app['id']?> - <?=$app['client_name']?></div>
                            <div class="item-meta">
                                <span class="item-type"><?=e($app['service_name'])?></span>
                                <span class="item-date"><?=date('M j', strtotime($app['created_at']))?></span>
                            </div>
                        </div>
                        <div class="item-client"><?=e($app['service_name'])?></div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>

    <div class="queue-card">
        <div class="queue-header">
            <h2 class="queue-title">🟢 Low Priority</h2>
            <span class="queue-count"><?=count($lowPriority)?></span>
        </div>
        <div class="queue-items">
            <?php if (empty($lowPriority)): ?>
                <div style="padding: 40px; text-align: center; color: var(--muted);">
                    No low priority applications
                </div>
            <?php else: foreach ($lowPriority as $app): ?>
                <div class="queue-item priority-low" onclick="window.location.href='/admin/applications.php?view=<?=$app['id']?>'">
                    <div class="item-info">
                        <div class="item-header">
                            <div class="item-title">#<?=$app['id']?> - <?=$app['client_name']?></div>
                            <div class="item-meta">
                                <span class="item-type"><?=e($app['service_name'])?></span>
                                <span class="item-date"><?=date('M j', strtotime($app['created_at']))?></span>
                            </div>
                        </div>
                        <div class="item-client"><?=e($app['service_name'])?></div>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<!-- Risk Assessment -->
<div class="risk-grid">
    <div class="risk-card">
        <div class="risk-header">
            <h3 class="risk-title">🔴 High Risk Applications</h3>
            <span class="risk-score risk-high"><?= (int)$riskData['high_risk'] ?></span>
        </div>
        <div style="font-size: 14px; color: var(--muted);">
            Applications requiring immediate attention and additional verification
        </div>
    </div>

    <div class="risk-card">
        <div class="risk-header">
            <h3 class="risk-title">🟡 Medium Risk Applications</h3>
            <span class="risk-score risk-medium"><?= (int)$riskData['medium_risk'] ?></span>
        </div>
        <div style="font-size: 14px; color: var(--muted);">
            Applications requiring standard verification procedures
        </div>
    </div>

    <div class="risk-card">
        <div class="risk-header">
            <h3 class="risk-title">🟢 Low Risk Applications</h3>
            <span class="risk-score risk-low"><?= (int)$riskData['low_risk'] ?></span>
        </div>
        <div style="font-size: 14px; color: var(--muted);">
            Applications with minimal risk factors
        </div>
    </div>

    <div class="risk-card">
        <div class="risk-header">
            <h3 class="risk-title">📊 Average Risk Score</h3>
            <span class="risk-score risk-medium"><?=round((float)$riskData['avg_risk_score'], 1)?></span>
        </div>
        <div style="font-size: 14px; color: var(--muted);">
            Overall risk assessment across all applications
        </div>
    </div>
</div>

<!-- Compliance Tracking -->
<div class="compliance-list">
    <div class="compliance-header">
        <h2 class="compliance-title">📋 Compliance Tracking</h2>
    </div>
    <div class="compliance-items">
        <?php if (empty($complianceData)): ?>
            <div style="padding: 40px; text-align: center; color: var(--muted);">
                No pending compliance items
            </div>
        <?php else: foreach ($complianceData as $item): ?>
            <div class="compliance-item">
                <div class="compliance-info">
                    <div class="compliance-name"><?=e($item['compliance_type'])?></div>
                    <div class="compliance-app">#<?=$item['app_id']?> - <?=$item['client_name']?></div>
                </div>
                <div class="compliance-status status-<?=e($item['status'])?>">
                    <?=ucfirst(e($item['status']))?>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
</div>

<?php include __DIR__ . '/../includes/footer.php'; ?>
