<?php
/**
 * Admin Dashboard View
 * Command-center overview with KPIs, live charts, and quick action shortcuts.
 */
?>
<div class="container-fluid py-4 px-4">
    <!-- Page Header -->
    <div class="d-flex justify-content-between align-items-center mb-5">
        <div>
            <h2 class="fw-bold font-outfit text-dark m-0"><i class="fa-solid fa-gauge-high text-primary me-2"></i>Admin Dashboard</h2>
            <p class="text-muted mb-0">System overview — <?= date('l, d F Y') ?></p>
        </div>
        <div class="d-flex gap-2">
            <a href="<?= APP_URL ?>/admin/reports" class="btn btn-outline-secondary rounded-pill px-4 font-outfit fw-bold"><i class="fa-solid fa-file-chart-column me-2"></i>Reports</a>
            <a href="<?= APP_URL ?>/admin/settings" class="btn btn-primary rounded-pill px-4 font-outfit fw-bold"><i class="fa-solid fa-gear me-2"></i>Settings</a>
        </div>
    </div>

    <!-- KPI Cards -->
    <div class="row g-4 mb-5">
        <?php
        $kpis = [
            ['label' => 'Total Students',     'value' => $stats['total_students'] ?? 0,     'icon' => 'fa-user-graduate', 'color' => 'primary',  'delta' => $stats['new_students_week'] ?? 0,   'delta_label' => 'this week'],
            ['label' => 'Active Mentors',     'value' => $stats['total_mentors'] ?? 0,      'icon' => 'fa-user-tie',     'color' => 'success',  'delta' => $stats['new_mentors_week'] ?? 0,    'delta_label' => 'this week'],
            ['label' => 'Sessions Completed', 'value' => $stats['sessions_completed'] ?? 0, 'icon' => 'fa-video',        'color' => 'info',     'delta' => $stats['sessions_this_month'] ?? 0, 'delta_label' => 'this month'],
            ['label' => 'Scholarships Listed','value' => $stats['total_scholarships'] ?? 0, 'icon' => 'fa-graduation-cap','color' => 'warning', 'delta' => $stats['new_scholarships'] ?? 0,    'delta_label' => 'added recently'],
            ['label' => 'Universities',       'value' => $stats['total_universities'] ?? 0, 'icon' => 'fa-building-columns','color' => 'secondary','delta' => null,                              'delta_label' => ''],
            ['label' => 'Messages Sent',      'value' => $stats['total_messages'] ?? 0,     'icon' => 'fa-message',      'color' => 'primary',  'delta' => $stats['messages_today'] ?? 0,      'delta_label' => 'today'],
        ];
        foreach ($kpis as $kpi):
        ?>
            <div class="col-md-4 col-sm-6 col-12">
                <div class="card border-0 shadow-sm hover-lift h-100">
                    <div class="card-body p-4">
                        <div class="d-flex justify-content-between align-items-start mb-3">
                            <div>
                                <p class="text-muted text-xs font-outfit fw-bold text-uppercase mb-1" style="letter-spacing:1px;"><?= $kpi['label'] ?></p>
                                <h2 class="fw-bold font-outfit text-dark mb-0"><?= number_format($kpi['value']) ?></h2>
                            </div>
                            <div class="badge-icon-box bg-<?= $kpi['color'] ?>-subtle text-<?= $kpi['color'] ?> rounded-circle" style="width:48px;height:48px;display:flex;align-items:center;justify-content:center;">
                                <i class="fa-solid <?= $kpi['icon'] ?> fs-5"></i>
                            </div>
                        </div>
                        <?php if ($kpi['delta'] !== null): ?>
                            <span class="text-xs text-<?= $kpi['delta'] > 0 ? 'success' : 'muted' ?>">
                                <?= $kpi['delta'] > 0 ? '+' : '' ?><?= number_format($kpi['delta']) ?> <?= $kpi['delta_label'] ?>
                            </span>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <div class="row g-4 mb-5">
        <!-- Registration Trend Chart -->
        <div class="col-lg-8">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body p-4">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h6 class="fw-bold font-outfit text-dark m-0"><i class="fa-solid fa-chart-line text-primary me-2"></i>User Registration Trend (Last 30 Days)</h6>
                        <span class="badge bg-primary-subtle text-primary rounded-pill text-xs font-outfit">Students vs Mentors</span>
                    </div>
                    <canvas id="registrationChart" height="100"></canvas>
                </div>
            </div>
        </div>
        <!-- Role Distribution Pie -->
        <div class="col-lg-4">
            <div class="card border-0 shadow-sm h-100">
                <div class="card-body p-4">
                    <h6 class="fw-bold font-outfit text-dark mb-4"><i class="fa-solid fa-chart-pie text-warning me-2"></i>User Role Distribution</h6>
                    <canvas id="roleChart" height="220"></canvas>
                    <div class="mt-3">
                        <?php foreach ([
                            ['Students', $stats['total_students'] ?? 0, '#0d6efd'],
                            ['Mentors',  $stats['total_mentors'] ?? 0,  '#198754'],
                            ['Tutors',   $stats['total_tutors'] ?? 0,   '#6f42c1'],
                            ['Admins',   $stats['total_admins'] ?? 0,   '#fd7e14'],
                        ] as $item): ?>
                            <div class="d-flex justify-content-between align-items-center mb-1">
                                <div class="d-flex align-items-center gap-2">
                                    <div class="rounded-circle" style="width:10px;height:10px;background:<?= $item[2] ?>;"></div>
                                    <span class="text-sm text-muted font-outfit"><?= $item[0] ?></span>
                                </div>
                                <span class="fw-bold text-sm text-dark font-outfit"><?= number_format($item[1]) ?></span>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <div class="row g-4 mb-5">
        <!-- Recent Registrations Table -->
        <div class="col-lg-7">
            <div class="card border-0 shadow-sm">
                <div class="card-body p-4">
                    <div class="d-flex justify-content-between align-items-center mb-4">
                        <h6 class="fw-bold font-outfit text-dark m-0"><i class="fa-solid fa-users text-info me-2"></i>Recent Registrations</h6>
                        <a href="<?= APP_URL ?>/admin/users" class="btn btn-sm btn-outline-primary rounded-pill px-3 font-outfit fw-bold">View All</a>
                    </div>
                    <div class="table-responsive">
                        <table class="table table-hover align-middle text-sm">
                            <thead class="table-light">
                                <tr>
                                    <th class="font-outfit fw-bold text-muted border-0">User</th>
                                    <th class="font-outfit fw-bold text-muted border-0">Role</th>
                                    <th class="font-outfit fw-bold text-muted border-0">Joined</th>
                                    <th class="font-outfit fw-bold text-muted border-0">Status</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($recentUsers ?? [] as $user): ?>
                                    <tr>
                                        <td>
                                            <div class="d-flex align-items-center gap-2">
                                                <img src="<?= $user['profile_picture'] ?? APP_URL . '/public/assets/img/default-avatar.png' ?>" alt="<?= htmlspecialchars($user['full_name']) ?>" class="rounded-circle" width="34" height="34" style="object-fit:cover;">
                                                <div>
                                                    <span class="fw-bold text-dark font-outfit d-block"><?= htmlspecialchars($user['full_name']) ?></span>
                                                    <small class="text-muted"><?= htmlspecialchars($user['email']) ?></small>
                                                </div>
                                            </div>
                                        </td>
                                        <td><span class="badge bg-primary-subtle text-primary rounded-pill font-outfit"><?= ucfirst($user['role']) ?></span></td>
                                        <td class="text-muted"><?= formatDate($user['created_at']) ?></td>
                                        <td>
                                            <span class="badge bg-<?= $user['is_active'] ? 'success' : 'secondary' ?>-subtle text-<?= $user['is_active'] ? 'success' : 'secondary' ?> rounded-pill">
                                                <?= $user['is_active'] ? 'Active' : 'Inactive' ?>
                                            </span>
                                        </td>
                                    </tr>
                                <?php endforeach; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>

        <!-- Quick Actions + Pending Approvals -->
        <div class="col-lg-5">
            <div class="card border-0 shadow-sm mb-4">
                <div class="card-body p-4">
                    <h6 class="fw-bold font-outfit text-dark mb-3"><i class="fa-solid fa-bolt text-warning me-2"></i>Quick Actions</h6>
                    <div class="row g-2">
                        <?php
                        $quickActions = [
                            ['label' => 'Add University',    'url' => APP_URL . '/admin/universities/create', 'icon' => 'fa-building-columns', 'color' => 'primary'],
                            ['label' => 'Add Scholarship',   'url' => APP_URL . '/admin/scholarships/create', 'icon' => 'fa-graduation-cap',   'color' => 'success'],
                            ['label' => 'Manage Users',      'url' => APP_URL . '/admin/users',               'icon' => 'fa-users-gear',       'color' => 'info'],
                            ['label' => 'Add Resource',      'url' => APP_URL . '/admin/resources/create',    'icon' => 'fa-upload',           'color' => 'warning'],
                            ['label' => 'View Analytics',    'url' => APP_URL . '/admin/analytics',           'icon' => 'fa-chart-bar',        'color' => 'purple'],
                            ['label' => 'Audit Logs',        'url' => APP_URL . '/admin/audit-logs',          'icon' => 'fa-file-lines',       'color' => 'secondary'],
                        ];
                        foreach ($quickActions as $action):
                        ?>
                            <div class="col-6">
                                <a href="<?= $action['url'] ?>" class="btn btn-<?= $action['color'] ?? 'primary' ?>-subtle text-<?= $action['color'] ?? 'primary' ?> border rounded-3 p-3 w-100 text-start font-outfit fw-bold text-sm hover-lift text-decoration-none d-block">
                                    <i class="fa-solid <?= $action['icon'] ?> me-2"></i><?= $action['label'] ?>
                                </a>
                            </div>
                        <?php endforeach; ?>
                    </div>
                </div>
            </div>

            <!-- Pending Mentor Approvals -->
            <?php if (!empty($pendingMentors)): ?>
            <div class="card border-0 shadow-sm border-start border-warning border-4">
                <div class="card-body p-4">
                    <h6 class="fw-bold font-outfit text-dark mb-3"><i class="fa-solid fa-clock text-warning me-2"></i>Pending Mentor Approvals <span class="badge bg-warning text-dark rounded-pill ms-1"><?= count($pendingMentors) ?></span></h6>
                    <?php foreach (array_slice($pendingMentors, 0, 4) as $mentor): ?>
                        <div class="d-flex align-items-center gap-3 mb-3">
                            <img src="<?= $mentor['profile_picture'] ?? APP_URL . '/public/assets/img/default-avatar.png' ?>" alt="<?= htmlspecialchars($mentor['full_name']) ?>" class="rounded-circle" width="38" height="38" style="object-fit:cover;">
                            <div class="flex-grow-1 min-w-0">
                                <span class="fw-bold font-outfit text-dark text-sm d-block text-truncate"><?= htmlspecialchars($mentor['full_name']) ?></span>
                                <small class="text-muted"><?= htmlspecialchars($mentor['expertise'] ?? 'Mentor') ?></small>
                            </div>
                            <a href="<?= APP_URL ?>/admin/users/<?= $mentor['id'] ?>" class="btn btn-warning btn-sm rounded-pill px-3 font-outfit fw-bold">Review</a>
                        </div>
                    <?php endforeach; ?>
                    <?php if (count($pendingMentors) > 4): ?>
                        <a href="<?= APP_URL ?>/admin/users?role=mentor&status=pending" class="btn btn-sm btn-outline-warning rounded-pill w-100 font-outfit fw-bold mt-1">View all <?= count($pendingMentors) ?> pending</a>
                    <?php endif; ?>
                </div>
            </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    // Registration Trend Chart
    const regCtx = document.getElementById('registrationChart').getContext('2d');
    new Chart(regCtx, {
        type: 'line',
        data: {
            labels: <?= json_encode(array_column($registrationTrend ?? [], 'date')) ?>,
            datasets: [
                {
                    label: 'Students',
                    data: <?= json_encode(array_column($registrationTrend ?? [], 'students')) ?>,
                    borderColor: '#0d6efd',
                    backgroundColor: 'rgba(13,110,253,0.08)',
                    tension: 0.4,
                    fill: true,
                    pointRadius: 3,
                },
                {
                    label: 'Mentors',
                    data: <?= json_encode(array_column($registrationTrend ?? [], 'mentors')) ?>,
                    borderColor: '#198754',
                    backgroundColor: 'rgba(25,135,84,0.06)',
                    tension: 0.4,
                    fill: true,
                    pointRadius: 3,
                }
            ]
        },
        options: {
            responsive: true,
            plugins: { legend: { position: 'top', labels: { font: { family: 'Outfit', size: 12 } } } },
            scales: {
                x: { grid: { display: false }, ticks: { font: { family: 'Outfit' } } },
                y: { beginAtZero: true, grid: { color: 'rgba(0,0,0,0.04)' }, ticks: { font: { family: 'Outfit' } } }
            }
        }
    });

    // Role Pie Chart
    const roleCtx = document.getElementById('roleChart').getContext('2d');
    new Chart(roleCtx, {
        type: 'doughnut',
        data: {
            labels: ['Students', 'Mentors', 'Tutors', 'Admins'],
            datasets: [{
                data: [
                    <?= $stats['total_students'] ?? 0 ?>,
                    <?= $stats['total_mentors'] ?? 0 ?>,
                    <?= $stats['total_tutors'] ?? 0 ?>,
                    <?= $stats['total_admins'] ?? 0 ?>
                ],
                backgroundColor: ['#0d6efd', '#198754', '#6f42c1', '#fd7e14'],
                borderWidth: 0,
            }]
        },
        options: {
            responsive: true,
            cutout: '70%',
            plugins: { legend: { display: false } }
        }
    });
});
</script>
