<?php
/**
 * Admin Analytics Dashboard View
 * Platform-wide metrics with charts for sessions, messages, scholarship applications,
 * and geographic distribution.
 */
?>
<div class="container-fluid py-4 px-4">
    <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-chart-bar text-primary me-2"></i>Platform Analytics</h2>
            <p class="text-muted mb-0">Comprehensive insights into platform activity and user engagement.</p>
        </div>
        <!-- Date Range Selector -->
        <form action="<?= APP_URL ?>/admin/analytics" method="GET" class="d-flex gap-2 align-items-center">
            <select name="range" class="form-select form-select-sm rounded-pill" style="width:auto;" onchange="this.form.submit()">
                <option value="7" <?= ($range ?? 30) == 7 ? 'selected' : '' ?>>Last 7 Days</option>
                <option value="30" <?= ($range ?? 30) == 30 ? 'selected' : '' ?>>Last 30 Days</option>
                <option value="90" <?= ($range ?? 30) == 90 ? 'selected' : '' ?>>Last 90 Days</option>
                <option value="365" <?= ($range ?? 30) == 365 ? 'selected' : '' ?>>Last Year</option>
            </select>
        </form>
    </div>

    <!-- KPI Summary Row -->
    <div class="row g-3 mb-5">
        <?php
        $analyticsKpis = [
            ['label' => 'Total Users',         'value' => $analytics['total_users'] ?? 0,         'icon' => 'fa-users',          'color' => 'primary',  'sub' => ($analytics['active_users_pct'] ?? 0) . '% active'],
            ['label' => 'Sessions This Period', 'value' => $analytics['sessions_period'] ?? 0,      'icon' => 'fa-video',          'color' => 'success',  'sub' => 'avg ' . number_format($analytics['avg_session_duration'] ?? 0) . ' min'],
            ['label' => 'Messages Sent',        'value' => $analytics['messages_period'] ?? 0,      'icon' => 'fa-message',        'color' => 'info',     'sub' => 'in selected period'],
            ['label' => 'Scholarship Apps',     'value' => $analytics['scholarship_apps'] ?? 0,     'icon' => 'fa-graduation-cap', 'color' => 'warning',  'sub' => ($analytics['scholarship_success_rate'] ?? 0) . '% success rate'],
            ['label' => 'Career Assessments',   'value' => $analytics['career_assessments'] ?? 0,   'icon' => 'fa-brain',          'color' => 'purple',   'sub' => 'completed this period'],
            ['label' => 'Resources Downloaded', 'value' => $analytics['resource_downloads'] ?? 0,   'icon' => 'fa-download',       'color' => 'secondary','sub' => 'total downloads'],
        ];
        foreach ($analyticsKpis as $kpi):
        ?>
            <div class="col-md-4 col-sm-6">
                <div class="card border-0 shadow-sm hover-lift">
                    <div class="card-body p-4 d-flex align-items-center gap-3">
                        <div class="badge-icon-box bg-<?= $kpi['color'] ?>-subtle text-<?= $kpi['color'] ?> rounded-circle flex-shrink-0" style="width:52px;height:52px;display:flex;align-items:center;justify-content:center;">
                            <i class="fa-solid <?= $kpi['icon'] ?> fs-5"></i>
                        </div>
                        <div>
                            <p class="text-muted text-xs font-outfit fw-bold text-uppercase mb-0" style="letter-spacing:1px;"><?= $kpi['label'] ?></p>
                            <h3 class="fw-bold font-outfit text-dark mb-0"><?= number_format($kpi['value']) ?></h3>
                            <small class="text-muted text-xs"><?= $kpi['sub'] ?></small>
                        </div>
                    </div>
                </div>
            </div>
        <?php endforeach; ?>
    </div>

    <!-- Charts Row 1 -->
    <div class="row g-4 mb-4">
        <!-- Session Trend -->
        <div class="col-lg-6">
            <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-video text-success me-2"></i>Mentorship Sessions Over Time</h6>
                    <canvas id="sessionTrendChart" height="200"></canvas>
                </div>
            </div>
        </div>
        <!-- Message Activity -->
        <div class="col-lg-6">
            <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-message text-info me-2"></i>Daily Message Activity</h6>
                    <canvas id="messageChart" height="200"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- Charts Row 2 -->
    <div class="row g-4 mb-4">
        <!-- Top Scholarship Applications -->
        <div class="col-lg-5">
            <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-graduation-cap text-warning me-2"></i>Top Scholarships by Applications</h6>
                    <canvas id="scholarshipBarChart" height="220"></canvas>
                </div>
            </div>
        </div>
        <!-- Regional Distribution -->
        <div class="col-lg-7">
            <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-globe-africa text-primary me-2"></i>Student Distribution by Region</h6>
                    <canvas id="regionChart" height="220"></canvas>
                </div>
            </div>
        </div>
    </div>

    <!-- Charts Row 3 -->
    <div class="row g-4 mb-4">
        <!-- Top Career Interests -->
        <div class="col-lg-6">
            <div class="card border-0 shadow-sm">
                <div class="card-body p-4">
                    <h6 class="fw-bold font-outfit text-dark mb-4"><i class="fa-solid fa-briefcase text-primary me-2"></i>Top Career Interests (Assessment Results)</h6>
                    <div class="d-flex flex-column gap-3">
                        <?php foreach ($analytics['top_careers'] ?? [] as $career): ?>
                            <div>
                                <div class="d-flex justify-content-between mb-1">
                                    <span class="text-sm font-outfit fw-bold text-dark"><?= htmlspecialchars($career['title']) ?></span>
                                    <span class="text-sm text-muted"><?= $career['count'] ?> students</span>
                                </div>
                                <div class="progress rounded-pill" style="height:8px;">
                                    <div class="progress-bar bg-primary rounded-pill" style="width:<?= min(100, ($career['count'] / max(1, $analytics['total_assessments'] ?? 1)) * 100) ?>%;"></div>
                                </div>
                            </div>
                        <?php endforeach; ?>
                        <?php if (empty($analytics['top_careers'])): ?>
                            <p class="text-muted text-sm text-center py-3">No assessment data available.</p>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>
        <!-- Top Active Mentors -->
        <div class="col-lg-6">
            <div class="card border-0 shadow-sm">
                <div class="card-body p-4">
                    <h6 class="fw-bold font-outfit text-dark mb-4"><i class="fa-solid fa-trophy text-warning me-2"></i>Top Active Mentors</h6>
                    <div class="table-responsive">
                        <table class="table table-hover align-middle text-sm mb-0">
                            <thead class="table-light">
                                <tr>
                                    <th class="border-0 font-outfit fw-bold text-muted">Mentor</th>
                                    <th class="border-0 font-outfit fw-bold text-muted text-center">Sessions</th>
                                    <th class="border-0 font-outfit fw-bold text-muted text-center">Rating</th>
                                    <th class="border-0 font-outfit fw-bold text-muted text-center">Students</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php foreach ($analytics['top_mentors'] ?? [] as $idx => $mentor): ?>
                                    <tr>
                                        <td>
                                            <div class="d-flex align-items-center gap-2">
                                                <span class="badge bg-<?= $idx === 0 ? 'warning' : 'light text-secondary' ?> rounded-circle font-outfit fw-bold" style="width:26px;height:26px;display:flex;align-items:center;justify-content:center;"><?= $idx + 1 ?></span>
                                                <span class="fw-bold font-outfit text-dark"><?= htmlspecialchars($mentor['full_name']) ?></span>
                                            </div>
                                        </td>
                                        <td class="text-center fw-bold font-outfit"><?= $mentor['session_count'] ?></td>
                                        <td class="text-center text-warning fw-bold">⭐ <?= number_format($mentor['avg_rating'], 1) ?></td>
                                        <td class="text-center fw-bold font-outfit"><?= $mentor['student_count'] ?></td>
                                    </tr>
                                <?php endforeach; ?>
                                <?php if (empty($analytics['top_mentors'])): ?>
                                    <tr><td colspan="4" class="text-center text-muted py-3">No data available.</td></tr>
                                <?php endif; ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const font = { family: 'Outfit', size: 12 };

    // Sessions Trend
    new Chart(document.getElementById('sessionTrendChart').getContext('2d'), {
        type: 'bar',
        data: {
            labels: <?= json_encode(array_column($analytics['session_trend'] ?? [], 'date')) ?>,
            datasets: [{
                label: 'Sessions',
                data: <?= json_encode(array_column($analytics['session_trend'] ?? [], 'count')) ?>,
                backgroundColor: 'rgba(25,135,84,0.7)',
                borderRadius: 6,
            }]
        },
        options: { responsive: true, plugins: { legend: { display: false } }, scales: { x: { grid: { display: false }, ticks: { font } }, y: { beginAtZero: true, ticks: { font } } } }
    });

    // Messages
    new Chart(document.getElementById('messageChart').getContext('2d'), {
        type: 'line',
        data: {
            labels: <?= json_encode(array_column($analytics['message_trend'] ?? [], 'date')) ?>,
            datasets: [{
                label: 'Messages',
                data: <?= json_encode(array_column($analytics['message_trend'] ?? [], 'count')) ?>,
                borderColor: '#0dcaf0',
                backgroundColor: 'rgba(13,202,240,0.1)',
                tension: 0.4,
                fill: true,
                pointRadius: 3,
            }]
        },
        options: { responsive: true, plugins: { legend: { display: false } }, scales: { x: { grid: { display: false }, ticks: { font } }, y: { beginAtZero: true, ticks: { font } } } }
    });

    // Scholarship Bar
    new Chart(document.getElementById('scholarshipBarChart').getContext('2d'), {
        type: 'horizontalBar',
        data: {
            labels: <?= json_encode(array_column($analytics['top_scholarships'] ?? [], 'name')) ?>,
            datasets: [{
                data: <?= json_encode(array_column($analytics['top_scholarships'] ?? [], 'app_count')) ?>,
                backgroundColor: 'rgba(255,193,7,0.7)',
                borderRadius: 6,
            }]
        },
        options: { indexAxis: 'y', responsive: true, plugins: { legend: { display: false } }, scales: { x: { beginAtZero: true, ticks: { font } }, y: { ticks: { font } } } }
    });

    // Region Doughnut
    new Chart(document.getElementById('regionChart').getContext('2d'), {
        type: 'doughnut',
        data: {
            labels: <?= json_encode(array_column($analytics['region_distribution'] ?? [], 'region')) ?>,
            datasets: [{
                data: <?= json_encode(array_column($analytics['region_distribution'] ?? [], 'count')) ?>,
                backgroundColor: ['#0d6efd','#198754','#ffc107','#0dcaf0','#6f42c1','#fd7e14','#20c997','#dc3545','#6c757d','#adb5bd'],
                borderWidth: 0,
            }]
        },
        options: { responsive: true, cutout: '60%', plugins: { legend: { position: 'right', labels: { font, boxWidth: 12 } } } }
    });
});
</script>
