<?php
include 'config.php';

// Fetch total quizzes taken
$totalQuizzesResult = $conn->query("SELECT COUNT(DISTINCT question_id) as total_quizzes FROM responses");
$totalQuizzes = $totalQuizzesResult->fetch_assoc()['total_quizzes'];

// Fetch responses per department
$departmentsResult = $conn->query("
    SELECT c.category_name, COUNT(r.response_id) as total_responses 
    FROM responses r
    JOIN users u ON r.user_id = u.user_id
    JOIN categories c ON u.category_id = c.category_id
    GROUP BY c.category_name
");

$departmentsData = [];
while ($row = $departmentsResult->fetch_assoc()) {
    $departmentsData[] = $row;
}

// Fetch responses per department and their topics
$departmentsTopicsResult = $conn->query("
    SELECT c.category_name, q.question_text, COUNT(r.response_id) as total_responses 
    FROM responses r
    JOIN users u ON r.user_id = u.user_id
    JOIN categories c ON u.category_id = c.category_id
    JOIN questions q ON r.question_id = q.question_id
    GROUP BY c.category_name, q.question_text
");

$departmentsTopicsData = [];
while ($row = $departmentsTopicsResult->fetch_assoc()) {
    $departmentsTopicsData[$row['category_name']][] = [
        'question_text' => $row['question_text'],
        'total_responses' => $row['total_responses']
    ];
}

$conn->close();
?>

<script>
    var totalQuizzes = <?php echo json_encode($totalQuizzes); ?>;
    var departmentsData = <?php echo json_encode($departmentsData); ?>;
    var departmentsTopicsData = <?php echo json_encode($departmentsTopicsData); ?>;
</script>

<!DOCTYPE html>
<html>
<head>
    <title>Quiz Analysis</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        .chart-container {
            max-width: 600px;
            margin: auto;
            margin-bottom: 50px;
            height: 400px;
        }
    </style>
</head>
<body>
    <div class="container mt-5">
        <div class="text-center">
            <h1>Quiz Analysis</h1>
            <p>Total Quizzes: <span id="total-quizzes"></span></p>
        </div>

        <div class="chart-container my-4">
            <h2 class="text-center">Responses per Department</h2>
            <canvas id="departmentsChart"></canvas>
        </div>

        <div id="departmentsTopicsCharts" class="mt-4">
            <h2 class="text-center">Responses per Department Topics</h2>
        </div>
    </div>

    <script>
        document.getElementById('total-quizzes').innerText = totalQuizzes;

        console.log(departmentsData); // Debugging: Check departmentsData
        console.log(departmentsTopicsData); // Debugging: Check departmentsTopicsData

        // Departments Pie Chart
        var ctx1 = document.getElementById('departmentsChart').getContext('2d');
        var departmentsChart = new Chart(ctx1, {
            type: 'pie',
            data: {
                labels: departmentsData.map(d => d.category_name),
                datasets: [{
                    data: departmentsData.map(d => d.total_responses),
                    backgroundColor: ['#FF6384', '#36A2EB', '#FFCE56', '#4BC0C0', '#9966FF']
                }]
            }
        });

        // Department Topics Bar Charts
        var chartsContainer = document.getElementById('departmentsTopicsCharts');
        for (var department in departmentsTopicsData) {
            var departmentDiv = document.createElement('div');
            departmentDiv.className = 'chart-container';

            var departmentTitle = document.createElement('h3');
            departmentTitle.className = 'text-center';
            departmentTitle.innerText = department;
            departmentDiv.appendChild(departmentTitle);

            var canvas = document.createElement('canvas');
            canvas.id = department + 'Chart';
            departmentDiv.appendChild(canvas);

            chartsContainer.appendChild(departmentDiv);

            console.log('Creating chart for:', department); // Debugging: Check department name

            var ctx = canvas.getContext('2d');
            new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: departmentsTopicsData[department].map(d => d.question_text),
                    datasets: [{
                        label: 'Responses',
                        data: departmentsTopicsData[department].map(d => d.total_responses),
                        backgroundColor: '#36A2EB'
                    }]
                },
                options: {
                    responsive: true,
                    maintainAspectRatio: false
                }
            });
        }
    </script>
</body>
</html>
