<?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(DISTINCT 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(DISTINCT 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 lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="Responsive Admin &amp; Dashboard Template based on Bootstrap 5">
    <meta name="author" content="AdminKit">
    <meta name="keywords" content="adminkit, bootstrap, bootstrap 5, admin, dashboard, template, responsive, css, sass, html, theme, front-end, ui kit, web">

    <link rel="preconnect" href="https://fonts.gstatic.com">
    <link rel="shortcut icon" href="img/icons/icon-48x48.png" />

    <link rel="canonical" href="https://demo-basic.adminkit.io/" />
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">

    <title>kijani quizes</title>

    <link href="css/app.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600&display=swap" rel="stylesheet">

    <style>
        .chart-container {
            max-width: 600px;
            margin: auto;
            margin-bottom: 50px;
            height: 400px;
        }
    </style>
</head>

<body>
    <div class="wrapper">
        <nav id="sidebar" class="sidebar js-sidebar">
            <div class="sidebar-content js-simplebar">
                <a class="sidebar-brand" href="index.php">
                    <span class="align-middle">Kijani Admin</span>
                </a>
                <ul class="sidebar-nav">
                    <li class="sidebar-header">Pages</li>
                    <li class="sidebar-item active">
                        <a class="sidebar-link" href="index.php">
                            <i class="align-middle" data-feather="sliders"></i>
                            <span class="align-middle">Dashboard</span>
                        </a>
                    </li>
                    <li class="sidebar-item">
                        <a class="sidebar-link" href="create_questions.php">
                            <i class="align-middle" data-feather="book"></i>
                            <span class="align-middle">create questions</span>
                        </a>
                    </li>
                    <li class="sidebar-item">
                        <a class="sidebar-link" href="view_results.php">
                            <i class="align-middle" data-feather="book"></i>
                            <span class="align-middle">view quiz Results</span>
                        </a>
                    </li>
                    <li class="sidebar-item">
                        <a class="sidebar-link" href="edit_questions.php">
                            <i class="align-middle" data-feather="book"></i>
                            <span class="align-middle">Edit Quiz</span>
                        </a>
                    </li>
                    <li class="sidebar-item">
                        <a class="sidebar-link" href="users.php">
                            <i class="align-middle" data-feather="user"></i>
                            <span class="align-middle">Users</span>
                        </a>
                    </li>
                    <li class="sidebar-item">
                        <a class="sidebar-link" href="bulk_upload.php">
                            <i class="align-middle" data-feather="book"></i>
                            <span class="align-middle">Bulk upload</span>
                        </a>
                    </li>
                </ul>
            </div>
        </nav>

        <div class="main">
            <nav class="navbar navbar-expand navbar-light navbar-bg">
                <a class="sidebar-toggle js-sidebar-toggle">
                    <i class="hamburger align-self-center"></i>
                </a>
                <div class="navbar-collapse collapse">
                    <ul class="navbar-nav navbar-align">
                        <li class="nav-item dropdown">
                            <!-- <a class="nav-icon dropdown-toggle" href="#" id="alertsDropdown" data-bs-toggle="dropdown">
                                 <div class="position-relative">
                                    <i class="align-middle" data-feather="bell"></i>
                                    <span class="indicator">4</span>
                                </div> -->
                            </a>
                            <div class="dropdown-menu dropdown-menu-lg dropdown-menu-end py-0" aria-labelledby="alertsDropdown">
                                 
                                <div class="list-group">
                                    <a href="#" class="list-group-item">
                                        <div class="row g-0 align-items-center">
                                            <div class="col-2">
                                                <i class="text-danger" data-feather="alert-circle"></i>
                                            </div>
                                            <!-- <div class="col-10">
                                                <div class="text-dark">Update completed</div>
                                                <div class="text-muted small mt-1">Restart server 12 to complete the update.</div>
                                                <div class="text-muted small mt-1">30m ago</div>
                                            </div> -->
                                        </div>
                                    </a>
                                    <a href="#" class="list-group-item">
                                        <div class="row g-0 align-items-center">
                                            <div class="col-2">
                                                <i class="text-warning" data-feather="bell"></i>
                                            </div>
                                            <!-- <div class="col-10">
                                                <div class="text-dark">Lorem ipsum</div>
                                                <div class="text-muted small mt-1">Aliquam ex eros, imperdiet vulputate hendrerit et.</div>
                                                <div class="text-muted small mt-1">2h ago</div>
                                            </div> -->
                                        </div>
                                    </a>
                                    <a href="#" class="list-group-item">
                                        <div class="row g-0 align-items-center">
                                            <div class="col-2">
                                                <i class="text-primary" data-feather="home"></i>
                                            </div>
                                            <!-- <div class="col-10">
                                                <div class="text-dark">Login from 192.186.1.1</div>
                                                <div class="text-muted small mt-1">5h ago</div>
                                            </div> -->
                                        </div>
                                    </a>
                                    <a href="#" class="list-group-item">
                                        <div class="row g-0 align-items-center">
                                            <div class="col-2">
                                                <i class="text-success" data-feather="user-plus"></i>
                                            </div>
                                            <!-- <div class="col-10">
                                                <div class="text-dark">New connection</div>
                                                <div class="text-muted small mt-1">Christina accepted your request.</div>
                                                <div class="text-muted small mt-1">14h ago</div>
                                            </div> -->
                                        </div>
                                    </a>
                                </div>
                            </div>
                        </li>
                        <li class="nav-item dropdown">
                            <a class="nav-icon dropdown-toggle d-inline-block d-sm-none" href="#" data-bs-toggle="dropdown">
                                <i class="align-middle" data-feather="settings"></i>
                            </a>
                            <a class="nav-link dropdown-toggle d-none d-sm-inline-block" href="#" data-bs-toggle="dropdown">
                                <img src="img/avatars/avatar.jpg" class="avatar img-fluid rounded me-1" alt="Charles Hall" />
                                <span class="text-dark">Charles Hall</span>
                            </a>
                            <div class="dropdown-menu dropdown-menu-end">
                                <a class="dropdown-item" href="profile.php">
                                    <i class="align-middle me-1" data-feather="user"></i>
                                    Profile
                                </a>
                                <a class="dropdown-item" href="#"><i class="align-middle me-1" data-feather="pie-chart"></i> Analytics</a>
                                <div class="dropdown-divider"></div>
                                <a class="dropdown-item" href="settings.php"><i class="align-middle me-1" data-feather="settings"></i> Settings & Privacy</a>
                                <a class="dropdown-item" href="#"><i class="align-middle me-1" data-feather="help-circle"></i> Help Center</a>
                                <div class="dropdown-divider"></div>
                                <a class="dropdown-item" href="#">Log out</a>
                            </div>
                        </li>
                    </ul>
                </div>
            </nav>

            <main class="content">
                <div class="container-fluid p-0">
                    <h1 class="h3 mb-3">Dashboard</h1>
                    <div class="row">
                        <div class="col-xl-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title">Total Quizzes Taken</h5>
                                    <h6 class="card-subtitle text-muted">This is the total number of quizzes taken.</h6>
                                </div>
                                <div class="card-body">
                                    <h1 id="total-quizzes"><?php echo $totalQuizzes; ?></h1>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title">Responses per Department</h5>
                                    <h6 class="card-subtitle text-muted">This is the total number of responses per department.</h6>
                                </div>
                                <div class="card-body">
                                    <canvas id="responses-department-chart"></canvas>
                                </div>
                            </div>
                        </div>
                        <div class="col-xl-12">
                            <div class="card">
                                <div class="card-header">
                                    <h5 class="card-title">Responses per Department and Topic</h5>
                                    <h6 class="card-subtitle text-muted">This is the total number of responses per department and topic.</h6>
                                </div>
                                <div class="card-body">
                                    <canvas id="responses-department-topic-chart"></canvas>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </main>
        </div>
    </div>

    <script src="js/app.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            // Total Quizzes Taken
            document.getElementById('total-quizzes').innerText = totalQuizzes;

            // Responses per Department Chart
            var ctx1 = document.getElementById('responses-department-chart').getContext('2d');
            var departmentsLabels = departmentsData.map(function(row) {
                return row.category_name;
            });
            var departmentsResponses = departmentsData.map(function(row) {
                return row.total_responses;
            });

            new Chart(ctx1, {
                type: 'bar',
                data: {
                    labels: departmentsLabels,
                    datasets: [{
                        label: 'Responses',
                        data: departmentsResponses,
                        backgroundColor: 'rgba(75, 192, 192, 0.2)',
                        borderColor: 'rgba(75, 192, 192, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });

            // Responses per Department and Topic Chart
            var ctx2 = document.getElementById('responses-department-topic-chart').getContext('2d');
            var datasets = [];
            Object.keys(departmentsTopicsData).forEach(function(department) {
                var topics = departmentsTopicsData[department];
                var topicLabels = topics.map(function(topic) {
                    return topic.question_text;
                });
                var topicResponses = topics.map(function(topic) {
                    return topic.total_responses;
                });

                datasets.push({
                    label: department,
                    data: topicResponses,
                    backgroundColor: getRandomColor(),
                    borderColor: getRandomColor(),
                    borderWidth: 1
                });
            });

            new Chart(ctx2, {
                type: 'bar',
                data: {
                    labels: Object.keys(departmentsTopicsData).reduce(function(acc, department) {
                        return acc.concat(departmentsTopicsData[department].map(function(topic) {
                            return topic.question_text;
                        }));
                    }, []),
                    datasets: datasets
                },
                options: {
                    scales: {
                        y: {
                            beginAtZero: true
                        }
                    }
                }
            });

            function getRandomColor() {
                var letters = '0123456789ABCDEF';
                var color = '#';
                for (var i = 0; i < 6; i++) {
                    color += letters[Math.floor(Math.random() * 16)];
                }
                return color;
            }
        });
    </script>
</body>
</html>
