<?php
require_once 'config.php';
require_admin();

// --- Data Fetching Logic ---
$totalStudents = $pdo->query("SELECT COUNT(id) FROM users WHERE role = 'student'")->fetchColumn();
$totalLessons = $pdo->query("SELECT COUNT(id) FROM lessons")->fetchColumn();
$totalLessonPacks = $pdo->query("SELECT COUNT(id) FROM lesson_packs")->fetchColumn();

// --- Chart Data Logic (7 Days, 1 Month, 3 Months) ---
$range = $_GET['range'] ?? '7days';
$timeframes = [
    '7days' => ['label' => 'Last 7 Days', 'days' => 7],
    '1month' => ['label' => 'Last 30 Days', 'days' => 30],
    '3months' => ['label' => 'Last 90 Days', 'days' => 90],
];
$days = $timeframes[$range]['days'];
$startDate = date('Y-m-d', strtotime("-{$days} days"));

// Helper function to fetch aggregated data
function fetch_daily_analytics($pdo, $eventType, $startDate, $days) {
    $stmt = $pdo->prepare("
        SELECT DATE(created_at) as day, COUNT(id) as count
        FROM analytics_log
        WHERE event_type = ? AND created_at >= ?
        GROUP BY day
        ORDER BY day
    ");
    $stmt->execute([$eventType, $startDate]);
    $data = $stmt->fetchAll();

    // Initialize array with all days in the range
    $dateRange = [];
    for ($i = 0; $i < $days; $i++) {
        $date = date('Y-m-d', strtotime("-{$i} days"));
        $dateRange[$date] = 0;
    }

    // Merge fetched data
    foreach ($data as $row) {
        $dateRange[$row['day']] = (int)$row['count'];
    }

    // Prepare for JavaScript Chart
    $labels = array_keys(array_reverse($dateRange));
    $counts = array_values(array_reverse($dateRange));

    return ['labels' => $labels, 'counts' => $counts];
}

$registrationData = fetch_daily_analytics($pdo, 'registration', $startDate, $days);
$purchaseData = fetch_daily_analytics($pdo, 'purchase', $startDate, $days);

require_once 'layouts.php';
render_header('Admin Dashboard');
render_sidebar($_SESSION['user_role'], basename(__FILE__));
render_topbar('Admin Dashboard & Analytics');

// Admin Navigation Cards (as requested)
$adminNavCards = [
    ['title' => 'Analytics', 'description' => 'View site statistics', 'icon' => 'fa-solid fa-chart-pie', 'url' => 'dashboard.php'],
    ['title' => 'Lesson Packs', 'description' => 'Manage class bundles', 'icon' => 'fa-solid fa-box-open', 'url' => 'addpack.php'],
    ['title' => 'Add Lessons', 'description' => 'Upload video classes', 'icon' => 'fa-solid fa-video', 'url' => 'addclass.php'],
    ['title' => 'Add Notice', 'description' => 'Post announcements', 'icon' => 'fa-solid fa-bullhorn', 'url' => 'addnotice.php'],
    ['title' => 'User Management', 'description' => 'Handle student accounts', 'icon' => 'fa-solid fa-users-cog', 'url' => 'usermanage.php'],
    ['title' => 'Slip Requests', 'description' => 'Approve student payments', 'icon' => 'fa-solid fa-file-invoice-dollar', 'url' => 'sliprequests.php'],
];
?>

<div class="space-y-8">
    <h2 class="text-2xl font-bold text-gray-900">Quick Navigation</h2>
    <?php render_admin_cards($adminNavCards); ?>

    <h2 class="text-2xl font-bold text-gray-900 pt-4 border-t mt-8">Site Summary</h2>
    <!-- Summary Statistics -->
    <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
        <div class="bg-white p-6 rounded-xl shadow-lg border-b-4 border-indigo-500 text-center">
            <h2 class="text-sm font-medium text-gray-500 uppercase">Total Students</h2>
            <p class="text-4xl font-extrabold text-gray-900 mt-2"><?php echo $totalStudents; ?></p>
        </div>
        <div class="bg-white p-6 rounded-xl shadow-lg border-b-4 border-green-500 text-center">
            <h2 class="text-sm font-medium text-gray-500 uppercase">Total Lesson Packs</h2>
            <p class="text-4xl font-extrabold text-gray-900 mt-2"><?php echo $totalLessonPacks; ?></p>
        </div>
        <div class="bg-white p-6 rounded-xl shadow-lg border-b-4 border-red-500 text-center">
            <h2 class="text-sm font-medium text-gray-500 uppercase">Total Lessons</h2>
            <p class="text-4xl font-extrabold text-gray-900 mt-2"><?php echo $totalLessons; ?></p>
        </div>
    </div>

    <!-- Charts -->
    <h2 class="text-2xl font-bold text-gray-900 pt-4 border-t mt-8">Data Trends</h2>
    <div class="flex space-x-2 mb-4">
        <?php foreach ($timeframes as $key => $tf): ?>
            <a href="?range=<?php echo $key; ?>"
               class="px-4 py-2 rounded-lg font-semibold transition duration-150
               <?php echo ($range === $key) ? 'bg-indigo-600 text-white shadow-md' : 'bg-white text-gray-700 hover:bg-gray-100'; ?>">
                <?php echo $tf['label']; ?>
            </a>
        <?php endforeach; ?>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
        <div class="bg-white p-6 rounded-xl shadow-lg">
            <h3 class="text-xl font-semibold mb-4 text-gray-800">New Student Registrations (<?php echo $timeframes[$range]['label']; ?>)</h3>
            <canvas id="registrationChart"></canvas>
        </div>
        <div class="bg-white p-6 rounded-xl shadow-lg">
            <h3 class="text-xl font-semibold mb-4 text-gray-800">Lesson Purchases (<?php echo $timeframes[$range]['label']; ?>)</h3>
            <canvas id="purchaseChart"></canvas>
        </div>
    </div>
</div>

<!-- Chart.js CDN -->
<script src="https://cdn.jsdelivr.net/npm/chart.js@3.7.1/dist/chart.min.js"></script>
<script>
    const registrationLabels = <?php echo json_encode($registrationData['labels']); ?>;
    const registrationCounts = <?php echo json_encode($registrationData['counts']); ?>;
    const purchaseLabels = <?php echo json_encode($purchaseData['labels']); ?>;
    const purchaseCounts = <?php echo json_encode($purchaseData['counts']); ?>;

    function createChart(ctxId, labels, data, labelText, color) {
        new Chart(document.getElementById(ctxId), {
            type: 'line',
            data: {
                labels: labels,
                datasets: [{
                    label: labelText,
                    data: data,
                    borderColor: color,
                    backgroundColor: color + '33', // 20% opacity
                    borderWidth: 2,
                    fill: true,
                    tension: 0.4,
                    pointRadius: 4,
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    legend: { display: false },
                    title: { display: false }
                },
                scales: {
                    y: {
                        beginAtZero: true,
                        ticks: { precision: 0 }
                    }
                }
            }
        });
    }

    createChart('registrationChart', registrationLabels, registrationCounts, 'New Students', '#4f46e5');
    createChart('purchaseChart', purchaseLabels, purchaseCounts, 'Lesson Purchases', '#10b981');
</script>

<?php render_main_content_end(); ?>