<?php
require_once '../includes/header.php';

if (!isset($_SESSION['user_id']) || $_SESSION['role'] !== 'admin') {
    header('Location: /dashboard.php');
    exit;
}

// Statistik Total
$total_users = $pdo->query("SELECT COUNT(*) FROM users")->fetchColumn();
$total_courses = $pdo->query("SELECT COUNT(*) FROM courses")->fetchColumn();
$total_orders = $pdo->query("SELECT COUNT(*) FROM orders WHERE status = 'awaiting_confirmation'")->fetchColumn();

// Data Pendaftaran Pengguna 7 Hari Terakhir
$user_reg_stmt = $pdo->query("SELECT strftime('%Y-%m-%d', created_at) as reg_date, COUNT(id) as user_count FROM users WHERE created_at >= date('now', '-7 days') GROUP BY reg_date ORDER BY reg_date ASC");
$user_reg_data = $user_reg_stmt->fetchAll();
$user_reg_labels = array_column($user_reg_data, 'reg_date');
$user_reg_values = array_column($user_reg_data, 'user_count');

// Data Distribusi Role
$role_dist_stmt = $pdo->query("SELECT role, COUNT(id) as count FROM users GROUP BY role");
$role_dist_data = $role_dist_stmt->fetchAll();
$role_labels = array_column($role_dist_data, 'role');
$role_values = array_column($role_dist_data, 'count');

?>
<main class="container mx-auto p-4 md:p-8">
    <div class="mb-8">
        <h1 class="text-3xl font-bold text-gray-800">Admin Dashboard</h1>
        <p class="text-gray-600 mt-2">Selamat datang, <?= e($_SESSION['username']) ?>. Berikut adalah ringkasan aktivitas platform Anda.</p>
    </div>

    <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 mb-8">
        <div class="bg-white p-6 rounded-xl shadow-lg">
            <h3 class="text-lg font-semibold text-gray-500">Pesanan Perlu Dikonfirmasi</h3>
            <p class="text-4xl font-bold text-yellow-500 mt-2"><?= $total_orders ?></p>
            <a href="manage_orders.php" class="mt-4 inline-block text-blue-500 font-semibold hover:underline">Kelola Pesanan &rarr;</a>
        </div>
        <div class="bg-white p-6 rounded-xl shadow-lg">
            <h3 class="text-lg font-semibold text-gray-500">Total Pengguna</h3>
            <p class="text-4xl font-bold text-gray-800 mt-2"><?= $total_users ?></p>
            <a href="manage_users.php" class="mt-4 inline-block text-blue-500 font-semibold hover:underline">Kelola Pengguna &rarr;</a>
        </div>
        <div class="bg-white p-6 rounded-xl shadow-lg">
            <h3 class="text-lg font-semibold text-gray-500">Total Kursus</h3>
            <p class="text-4xl font-bold text-gray-800 mt-2"><?= $total_courses ?></p>
            <a href="manage_courses.php" class="mt-4 inline-block text-blue-500 font-semibold hover:underline">Kelola Kursus &rarr;</a>
        </div>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <div class="lg:col-span-2 bg-white p-6 rounded-xl shadow-lg">
            <h3 class="text-lg font-semibold text-gray-800 mb-4">Pendaftaran Pengguna Baru (7 Hari Terakhir)</h3>
            <canvas id="userRegistrationChart"></canvas>
        </div>
        <div class="bg-white p-6 rounded-xl shadow-lg">
            <h3 class="text-lg font-semibold text-gray-800 mb-4">Distribusi Role Pengguna</h3>
            <canvas id="roleDistributionChart"></canvas>
        </div>
    </div>
</main>

<script>
document.addEventListener('DOMContentLoaded', function () {
    // Data dari PHP
    const userRegLabels = <?= json_encode($user_reg_labels); ?>;
    const userRegValues = <?= json_encode($user_reg_values); ?>;
    const roleLabels = <?= json_encode($role_labels); ?>;
    const roleValues = <?= json_encode($role_values); ?>;

    // Grafik Pendaftaran Pengguna (Line Chart)
    const userChartCtx = document.getElementById('userRegistrationChart');
    if(userChartCtx) {
        new Chart(userChartCtx.getContext('2d'), {
            type: 'line', data: { labels: userRegLabels, datasets: [{ label: 'Pengguna Baru', data: userRegValues, backgroundColor: 'rgba(59, 130, 246, 0.1)', borderColor: 'rgba(59, 130, 246, 1)', borderWidth: 2, fill: true, tension: 0.3 }] },
            options: { scales: { y: { beginAtZero: true, ticks: { stepSize: 1 } } }, plugins: { legend: { display: false } } }
        });
    }

    // Grafik Distribusi Role (Doughnut Chart)
    const roleChartCtx = document.getElementById('roleDistributionChart');
    if(roleChartCtx) {
        new Chart(roleChartCtx.getContext('2d'), {
            type: 'doughnut', data: { labels: roleLabels, datasets: [{ label: 'Jumlah Pengguna', data: roleValues, backgroundColor: ['rgba(59, 130, 246, 0.7)', 'rgba(16, 185, 129, 0.7)'], borderColor: ['rgba(59, 130, 246, 1)', 'rgba(16, 185, 129, 1)'], borderWidth: 1 }] },
            options: { responsive: true, plugins: { legend: { position: 'top' } } }
        });
    }
});
</script>

<?php require_once '../includes/footer.php'; ?>