
<?php
header("Refresh: 5");
include_once 'mongodb_config.php';
$db = new DbManager();
$conn = $db->getConnection();

$dbname="myWebhook";
$collection_absensi="soal";
/*
// $dbname="myakun";
$collection_user="user";
$collection_soal="soal";
$collection_kunci="kunci";
$chat_id_admin="304835260";

$filter1 = [];
//$options = ['projection' => ['_id' => 0.0]];
$options1 = [];
$read1 = new MongoDB\Driver\Query($filter1, $options1);
$records1 = $conn->executeQuery("$dbname.$collection_soal", $read1);
 $res1= json_encode(iterator_to_array($records1)); //echo  
$result1= json_decode($res1, true); 

var_dump($result1);
*/

// $pipeline = [
//         [
//             // The $group stage combines documents by a specified key (_id)
//             '$group' => [
//                 '_id' => '$category', // Group by the 'category' field
//                 'count' => ['$sum' => 1] // Use $sum accumulator to count documents in each group
//             ]
//         ]
//     ];

//     // Execute the aggregation pipeline
//     $cursor = $collection->aggregate($pipeline);

//     // Iterate over the results and print them
//     echo "Count by Category:\n";
//     foreach ($cursor as $document) {
//         printf("Category: %s, Count: %d\n", $document['_id'], $document['count']);
//     }


// $regex = new Regex('/^x/');

    $pipeline = [ 
        [
            // The $group stage combines documents by a specified key (_id)
            '$group' => [
                '_id' => '$nama', // Group by the 'category' field
                'skor' => ['$sum' => 1], // Use $sum accumulator to count documents in each group
           
            ],
            
        ], 
        ['$limit' => 20],
        // ['$match' => ['kls' => $regex]]
        // [
        //     '$match' => [
        //         'kelas' => "X-APL"
        //     ]
        // ]
        
           ]; 
               $aggregate = new \MongoDB\Driver\Command([ 
                  'aggregate' => $collection_absensi,  
                  'cursor' => new stdClass, 
                  'pipeline' => $pipeline, 
                  ]); 
               $cursor = $conn->executeCommand($dbname, $aggregate); 
               $jsonkls= json_encode(iterator_to_array($cursor));//showjson 
               $resultkls= json_decode($jsonkls, true); 
            //    var_dump  ($resultkls[0]);
//echo $jsonkls ;
            //    foreach ($resultkls as $document) {
            //     echo $document['_id'],$document['skor'];
            //     // echo "<br>";
            //     // printf("kelas: %s, Count: %d\n", $document['_id'], $document['skor']."\n");
            // }



   $filter1 = ['Gsoal' => 'A'];
	//$options = ['projection' => ['_id' => 0.0]];
    $options1 = ['projection' => [
        '_id' => 0.0,
        'id' => 0.0,
        'kelas' => 0.0,
        '01' => 0.0,
        'Gsoal' => 0.0,
        'created_at' => 0.0,
        '02' => 0.0,
        '03' => 0.0,
        '04' => 0.0,
        '05' => 0.0,
        '06' => 0.0,
        '07' => 0.0,
        '08' => 0.0,
        '09' => 0.0,
        '10' => 0.0,
        'end_at' => 0.0,
        'nama' => 0.0,
        'sesi' => 0.0
    ]];
	$read1 = new MongoDB\Driver\Query($filter1, $options1);
	$records1 = $conn->executeQuery("$dbname.$collection_absensi", $read1);
 	$res1= json_encode(iterator_to_array($records1)); //echo  
    $result1= json_decode($res1, true); 


echo  $res1;















?>





<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard Statistik Siswa</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .dashboard-container {
            max-width: 1400px;
            margin: 0 auto;
        }

        .header {
            text-align: center;
            margin-bottom: 40px;
            color: white;
        }

        .header h1 {
            font-size: 2.5rem;
            font-weight: 700;
            margin-bottom: 10px;
            text-shadow: 0 2px 4px rgba(0,0,0,0.3);
        }

        .header p {
            font-size: 1.1rem;
            opacity: 0.9;
        }

        .stats-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin-bottom: 40px;
        }

        .stat-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            padding: 25px;
            text-align: center;
            box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
            border: 1px solid rgba(255, 255, 255, 0.18);
            transition: transform 0.3s ease, box-shadow 0.3s ease;
        }

        .stat-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 12px 40px rgba(31, 38, 135, 0.5);
        }

        .stat-number {
            font-size: 2.5rem;
            font-weight: bold;
            color: #4a5568;
            margin-bottom: 5px;
        }

        .stat-label {
            color: #718096;
            font-size: 0.9rem;
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .charts-grid {
            display: grid;
            grid-template-columns: 1fr 1fr;
            gap: 30px;
            margin-bottom: 40px;
        }

        .chart-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 20px;
            padding: 30px;
            box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
            border: 1px solid rgba(255, 255, 255, 0.18);
        }

        .chart-title {
            font-size: 1.3rem;
            font-weight: 600;
            color: #2d3748;
            margin-bottom: 20px;
            text-align: center;
        }

        .chart-container {
            position: relative;
            height: 400px;
        }

        .additional-stats {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
        }

        .detail-card {
            background: rgba(255, 255, 255, 0.95);
            backdrop-filter: blur(10px);
            border-radius: 15px;
            padding: 25px;
            box-shadow: 0 8px 32px rgba(31, 38, 135, 0.37);
            border: 1px solid rgba(255, 255, 255, 0.18);
        }

        .detail-card h3 {
            color: #2d3748;
            margin-bottom: 15px;
            font-size: 1.2rem;
        }

        .detail-list {
            list-style: none;
        }

        .detail-list li {
            display: flex;
            justify-content: space-between;
            padding: 8px 0;
            border-bottom: 1px solid #e2e8f0;
            color: #4a5568;
        }

        .detail-list li:last-child {
            border-bottom: none;
        }

        .percentage {
            font-weight: 600;
            color: #667eea;
        }

        @media (max-width: 768px) {
            .charts-grid {
                grid-template-columns: 1fr;
            }
            
            .header h1 {
                font-size: 2rem;
            }
            
            .chart-container {
                height: 300px;
            }
        }

        .refresh-btn {
            background: linear-gradient(45deg, #667eea, #764ba2);
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 25px;
            font-size: 1rem;
            cursor: pointer;
            transition: transform 0.2s ease;
            box-shadow: 0 4px 15px rgba(0,0,0,0.2);
        }

        .refresh-btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 20px rgba(0,0,0,0.3);
        }
    </style>
</head>
<body>
    <div class="dashboard-container">
        <div class="header">
            <h1>📊 Dashboard Statistik Siswa</h1>
            <p>Analisis Data Siswa per Kelas - Tahun Ajaran 2024/2025</p>
            <br>
            <button class="refresh-btn" onclick="refreshData()">🔄 Refresh Data</button>
        </div>

        <div class="stats-grid" id="statsGrid">
            <!-- Stats cards will be populated by JavaScript -->
        </div>

        <div class="charts-grid">
            <div class="chart-card">
                <h3 class="chart-title">📊 Distribusi Siswa per Kelas (Bar Chart)</h3>
                <div class="chart-container">
                    <canvas id="barChart"></canvas>
                </div>
            </div>

            <div class="chart-card">
                <h3 class="chart-title">🥧 Persentase Siswa per Kelas (Pie Chart)</h3>
                <div class="chart-container">
                    <canvas id="pieChart"></canvas>
                </div>
            </div>
        </div>

        <div class="additional-stats">
            <div class="detail-card">
                <h3>📈 Detail Statistik</h3>
                <ul class="detail-list" id="detailStats">
                    <!-- Detail stats will be populated by JavaScript -->
                </ul>
            </div>

            <div class="detail-card">
                <h3>🎯 Ringkasan</h3>
                <ul class="detail-list" id="summary">
                    <!-- Summary will be populated by JavaScript -->
                </ul>
            </div>
        </div>
    </div>

    <script>
        // Data dummy untuk demonstrasi
        
        var studentData = <?php echo $res1; ?>;
        //  console.log(dataJS); // Output: "Ini data dari PHP!"
        //  studentData = dataJS ;
        //  studentData =
        // [
        //     { "_id": 'Teknik Informatika', "jumlah": 240 },
        //     { "_id": 'Sistem Informasi', "jumlah": 198 },
        //     { "_id": 'Teknik Elektro', "jumlah": 167 },
        //     { "_id": 'Manajemen', "jumlah": 223 },
        //     { "_id": 'Akuntansi', "jumlah": 189 },
        //     { "_id": 'Teknik Mesin', "jumlah": 134 },
        //     { "_id": 'Psikologi', "jumlah": 156 },
        //     { "_id": 'Psikologi', "jumlah": 156 }
        // ];

        let barChart, pieChart;

        // Fungsi untuk membuat stats cards
        function createStatsCards(data) {
            const total = data.reduce((sum, item) => sum + item.skor, 0);
            const maxuser = data.reduce((max, item) => item.skor > max.skor ? item : max);
            const avgStudents = Math.round(total / data.length);

            const statsGrid = document.getElementById('statsGrid');
            statsGrid.innerHTML = `
                <div class="stat-card">
                    <div class="stat-number">${total}</div>
                    <div class="stat-label">Total skor</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number">${data.length}</div>
                    <div class="stat-label">skor Kelas</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number">${avgStudents}</div>
                    <div class="stat-label">Rata-rata per Kelas</div>
                </div>
                <div class="stat-card">
                    <div class="stat-number">${maxuser.skor}</div>
                    <div class="stat-label">Kelas Terbanyak</div>
                </div>
            `;
        }

        // Fungsi untuk membuat detail stats
        function createDetailStats(data) {
            const total = data.reduce((sum, item) => sum + item.skor, 0);
            const detailStats = document.getElementById('detailStats');
            
            detailStats.innerHTML = data.map(item => `
                <li>
                    <span>${item.user}</span>
                    <span class="percentage">${((item.skor / total) * 100).toFixed(1)}%</span>
                </li>
            `).join('');

            // Summary
            const sortedData = [...data].sort((a, b) => b.skor - a.skor);
            const summary = document.getElementById('summary');
            summary.innerHTML = `
                <li>
                    <span>Kelas Terpopuler</span>
                    <span class="percentage">${sortedData[0].user}</span>
                </li>
                <li>
                    <span>Kelas Terkecil</span>
                    <span class="percentage">${sortedData[sortedData.length - 1].user}</span>
                </li>
                <li>
                    <span>Selisih Terbesar</span>
                    <span class="percentage">${sortedData[0].skor - sortedData[sortedData.length - 1].skor} siswa</span>
                </li>
                <li>
                    <span>Status</span>
                    <span class="percentage">Aktif</span>
                </li>
            `;
        }

        // Fungsi untuk membuat charts
        function createCharts(data) {
            const labels = data.map(item => item.user);
            const values = data.map(item => item.skor);
            
            const colors = [
                '#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', 
                '#9966FF', '#FF9F40', '#FF6B6B', '#4ECDC4'
            ];

            // Destroy existing charts if they exist
            if (barChart) barChart.destroy();
            if (pieChart) pieChart.destroy();

            // Bar Chart
            const barCtx = document.getElementById('barChart').getContext('2d');
            barChart = new Chart(barCtx, {
                type: 'bar',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'skor Siswa',
                        data: values,
                        backgroundColor: colors.slice(0, data.length).map(color => color + '80'),
                        borderColor: colors.slice(0, data.length),
                        borderWidth: 2,
                        borderRadius: 8,
                        borderSkipped: false,
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            display: false
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0,0,0,0.8)',
                            titleColor: 'white',
                            bodyColor: 'white',
                            borderColor: 'rgba(255,255,255,0.3)',
                            borderWidth: 1
                        }
                    },
                    scales: {
                        y: {
                            beginAtZero: true,
                            grid: {
                                color: 'rgba(0,0,0,0.1)'
                            },
                            ticks: {
                                color: '#666'
                            }
                        },
                        x: {
                            grid: {
                                display: false
                            },
                            ticks: {
                                color: '#666',
                                maxRotation: 45
                            }
                        }
                    },
                    animation: {
                        duration: 1500,
                        easing: 'easeOutQuart'
                    }
                }
            });

            // Pie Chart
            const pieCtx = document.getElementById('pieChart').getContext('2d');
            pieChart = new Chart(pieCtx, {
                type: 'doughnut',
                data: {
                    labels: labels,
                    datasets: [{
                        label: 'skor Siswa',
                        data: values,
                        backgroundColor: colors.slice(0, data.length),
                        borderColor: '#ffffff',
                        borderWidth: 3,
                        hoverOffset: 15
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false,
                    plugins: {
                        legend: {
                            position: 'bottom',
                            labels: {
                                padding: 20,
                                color: '#666',
                                font: {
                                    size: 12
                                }
                            }
                        },
                        tooltip: {
                            backgroundColor: 'rgba(0,0,0,0.8)',
                            titleColor: 'white',
                            bodyColor: 'white',
                            borderColor: 'rgba(255,255,255,0.3)',
                            borderWidth: 1,
                            callbacks: {
                                label: function(context) {
                                    const total = context.dataset.data.reduce((a, b) => a + b, 0);
                                    const percentage = ((context.parsed / total) * 100).toFixed(1);
                                    return `${context.label}: ${context.parsed} siswa (${percentage}%)`;
                                }
                            }
                        }
                    },
                    cutout: '50%',
                    animation: {
                        duration: 1500,
                        easing: 'easeOutQuart'
                    }
                }
            });
        }

        // Fungsi untuk refresh data (simulasi)
        function refreshData() {
            // Simulasi loading
            const btn = document.querySelector('.refresh-btn');
            btn.innerHTML = '⏳ Loading...';
            btn.disabled = true;

            setTimeout(() => {
                // Simulasi perubahan data
                studentData.forEach(item => {
                    item.skor += Math.floor(Math.random() * 21) - 10; // +/- 10
                    if (item.skor < 50) item.skor = 50; // minimum 50
                });

                initDashboard();
                
                btn.innerHTML = '🔄 Refresh Data';
                btn.disabled = false;
            }, 1500);
        }

        // Fungsi untuk inisialisasi dashboard
        function initDashboard() {
            createStatsCards(studentData);
            createDetailStats(studentData);
            createCharts(studentData);
        }

        // Simulasi fetch data (menggantikan fetch ke data.php)
        function loadData() {
            // Dalam implementasi nyata, ganti dengan:
            // fetch('data.php')
            //     .then(response => response.json())
            //     .then(data => {
            //         initDashboard(data);
            //     })
            //     .catch(error => console.error('Error:', error));
            
            initDashboard();
        }

        // Load data saat halaman dimuat
        document.addEventListener('DOMContentLoaded', loadData);
    </script>
</body>
</html>