<?php
// attendance_aggregate.php

// Include session validation and database connection
include('session_validator.php');
include('includes/db_pdo.php');

// Get current academic year
$current_year = date('Y');
$next_year = $current_year + 1;
$academic_year = $current_year . '-' . $next_year;

// Get academic years from database
$stmt = $conn->query("SELECT DISTINCT academic_year FROM student_class_section_data ORDER BY academic_year DESC");
$academic_years = $stmt->fetchAll(PDO::FETCH_COLUMN);

// Nepali months array
$nepali_months = [
    'Baisakh', 'Jestha', 'Ashadh', 'Shrawan', 
    'Bhadra', 'Ashwin', 'Kartik', 'Mangsir', 
    'Poush', 'Magh', 'Falgun', 'Chaitra'
];
?>

<!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">
    <title>SRMS Admin - Attendance Aggregate</title>
    <link rel="stylesheet" href="css/bootstrap.min.css" media="screen">
    <link rel="stylesheet" href="css/font-awesome.min.css" media="screen">
    <link rel="stylesheet" href="css/animate-css/animate.min.css" media="screen">
    <link rel="stylesheet" href="css/lobipanel/lobipanel.min.css" media="screen">
    <link rel="stylesheet" href="css/prism/prism.css" media="screen">
    <link rel="stylesheet" href="css/select2/select2.min.css">
    <link rel="stylesheet" href="css/main.css" media="screen">
    <link rel="stylesheet" href="https://cdn.datatables.net/1.11.5/css/dataTables.bootstrap4.min.css">
    <link rel="stylesheet" href="https://cdn.datatables.net/buttons/2.2.2/css/buttons.bootstrap4.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css">
    <script src="js/modernizr/modernizr.min.js"></script>
    <script src="js/jquery/jquery-2.2.4.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <style>
        .summary-card {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
            text-align: center;
            box-shadow: 0 4px 6px rgba(0,0,0,0.1);
        }
        .summary-card h3 {
            margin: 0;
            font-size: 2.5em;
            font-weight: bold;
        }
        .summary-card .label {
            font-size: 1.1em;
            opacity: 0.9;
        }
        .class-card {
            background: #fff;
            border: 1px solid #dee2e6;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            transition: all 0.3s;
            cursor: pointer;
            box-shadow: 0 2px 4px rgba(0,0,0,0.05);
        }
        .class-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            border-color: #007bff;
        }
        .class-card.selected {
            border: 2px solid #007bff;
            background: #f0f7ff;
        }
        .class-card .class-name {
            font-size: 1.3em;
            font-weight: bold;
            color: #333;
        }
        .class-card .stats {
            margin-top: 10px;
            font-size: 0.9em;
            color: #666;
        }
        .class-card .progress {
            height: 8px;
            margin-top: 10px;
        }
        .monthly-table th {
            background-color: #f8f9fa;
            text-align: center;
            vertical-align: middle;
        }
        .monthly-table td {
            text-align: center;
            vertical-align: middle;
        }
        .attendance-percentage {
            font-weight: bold;
        }
        .high-attendance {
            color: #28a745;
            font-weight: bold;
        }
        .medium-attendance {
            color: #ffc107;
            font-weight: bold;
        }
        .low-attendance {
            color: #dc3545;
            font-weight: bold;
        }
        .trend-up {
            color: #28a745;
        }
        .trend-down {
            color: #dc3545;
        }
        .filter-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        .chart-container {
            margin-top: 30px;
            margin-bottom: 30px;
            padding: 20px;
            background: #fff;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .stat-badge {
            padding: 5px 10px;
            border-radius: 20px;
            font-size: 0.9em;
            margin-right: 5px;
        }
        .stat-badge.total {
            background: #e3f2fd;
            color: #0d47a1;
        }
        .stat-badge.present {
            background: #e8f5e9;
            color: #1b5e20;
        }
        .stat-badge.absent {
            background: #ffebee;
            color: #b71c1c;
        }
        .stat-badge.percentage {
            background: #fff3e0;
            color: #e65100;
        }
    </style>
</head>

<body class="top-navbar-fixed">
    <div class="main-wrapper">
        <?php include('includes/topbar.php'); ?>
        <div class="content-wrapper">
            <?php include('includes/leftbar.php'); ?>
            <div class="main-page">
                <div class="container-fluid">
                    <div class="row">
                        <div class="col-md-12">
                            <div class="panel">
                                <div class="panel-heading">
                                    <div class="panel-title">
                                        <h5>Attendance Aggregate Report</h5>
                                    </div>
                                </div>
                                <div class="panel-body">
                                    
                                    <!-- Filter Section -->
                                    <div class="filter-section">
                                        <div class="row">
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label for="academic_year">Academic Year</label>
                                                    <select id="academic_year" class="form-control">
                                                        <?php foreach ($academic_years as $year): ?>
                                                            <option value="<?php echo $year; ?>" <?php echo ($year == $academic_year) ? 'selected' : ''; ?>>
                                                                <?php echo $year; ?>
                                                            </option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label for="view_type">View Type</label>
                                                    <select id="view_type" class="form-control">
                                                        <option value="class">Class-wise Summary</option>
                                                        <option value="month">Month-wise Summary</option>
                                                        <option value="student">Student-wise Detail</option>
                                                        <option value="trend">Trend Analysis</option>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label for="month_range">Month Range</label>
                                                    <select id="month_range" class="form-control" multiple="multiple" style="height: 100px;">
                                                        <?php foreach ($nepali_months as $month): ?>
                                                            <option value="<?php echo $month; ?>" selected><?php echo $month; ?></option>
                                                        <?php endforeach; ?>
                                                    </select>
                                                </div>
                                            </div>
                                            <div class="col-md-3">
                                                <div class="form-group">
                                                    <label>&nbsp;</label>
                                                    <div>
                                                        <button id="generateAggregate" class="btn btn-primary">
                                                            <i class="fa fa-bar-chart"></i> Generate Report
                                                        </button>
                                                        <button id="exportAggregate" class="btn btn-success">
                                                            <i class="fa fa-download"></i> Export
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Overall Summary Cards -->
                                    <div class="row" id="overallSummary" style="display: none;">
                                        <div class="col-md-3">
                                            <div class="summary-card" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
                                                <div class="label">Total Students</div>
                                                <h3 id="totalStudents">0</h3>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="summary-card" style="background: linear-gradient(135deg, #28a745 0%, #20c997 100%);">
                                                <div class="label">Average Attendance</div>
                                                <h3 id="avgAttendance">0%</h3>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="summary-card" style="background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);">
                                                <div class="label">Total Present Days</div>
                                                <h3 id="totalPresent">0</h3>
                                            </div>
                                        </div>
                                        <div class="col-md-3">
                                            <div class="summary-card" style="background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);">
                                                <div class="label">Total Absent Days</div>
                                                <h3 id="totalAbsent">0</h3>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Class-wise Cards View -->
                                    <div id="classCardsView" style="display: none;">
                                        <h4>Class-wise Attendance Summary</h4>
                                        <div class="row" id="classCardsContainer">
                                            <!-- Class cards will be loaded here -->
                                        </div>
                                    </div>

                                    <!-- Monthly Summary Table -->
                                    <div id="monthlyTableView" style="display: none;">
                                        <h4>Monthly Attendance Summary</h4>
                                        <div class="table-responsive">
                                            <table id="monthlySummaryTable" class="table table-bordered monthly-table">
                                                <thead>
                                                    <tr>
                                                        <th>Month</th>
                                                        <th>Total Students</th>
                                                        <th>Total Days</th>
                                                        <th>Present Days</th>
                                                        <th>Absent Days</th>
                                                        <th>Attendance %</th>
                                                        <th>High (≥75%)</th>
                                                        <th>Medium (60-74%)</th>
                                                        <th>Low (<60%)</th>
                                                        <th>Trend</th>
                                                    </tr>
                                                </thead>
                                                <tbody id="monthlySummaryData">
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>

                                    <!-- Student-wise Detail Table -->
                                    <div id="studentDetailView" style="display: none;">
                                        <h4>Student-wise Attendance Detail</h4>
                                        <div class="table-responsive">
                                            <table id="studentDetailTable" class="table table-bordered">
                                                <thead>
                                                    <tr>
                                                        <th>S.No.</th>
                                                        <th>Student ID</th>
                                                        <th>Student Name</th>
                                                        <th>Class</th>
                                                        <th>Section</th>
                                                        <th>Roll No.</th>
                                                        <?php foreach ($nepali_months as $month): ?>
                                                        <th><?php echo $month; ?></th>
                                                        <?php endforeach; ?>
                                                        <th>Total Present</th>
                                                        <th>Total Days</th>
                                                        <th>Overall %</th>
                                                        <th>Status</th>
                                                    </tr>
                                                </thead>
                                                <tbody id="studentDetailData">
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>

                                    <!-- Trend Analysis Chart -->
                                    <div id="trendView" style="display: none;">
                                        <h4>Attendance Trend Analysis</h4>
                                        <div class="chart-container">
                                            <canvas id="trendChart"></canvas>
                                        </div>
                                        <div id="trendStats" class="row">
                                            <!-- Trend stats will be loaded here -->
                                        </div>
                                    </div>

                                    <div id="loader" style="display:none;" class="text-center">
                                        <img src="images/loader.gif" alt="Loading..." width="50">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <script src="js/bootstrap/bootstrap.min.js"></script>
    <script src="js/pace/pace.min.js"></script>
    <script src="js/lobipanel/lobipanel.min.js"></script>
    <script src="js/iscroll/iscroll.js"></script>
    <script src="js/prism/prism.js"></script>
    <script src="js/main.js"></script>
    <script src="js/select2/select2.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/jquery.dataTables.min.js"></script>
    <script src="https://cdn.datatables.net/1.11.5/js/dataTables.bootstrap4.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.2.2/js/dataTables.buttons.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.2.2/js/buttons.bootstrap4.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jszip/3.1.3/jszip.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/pdfmake.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.53/vfs_fonts.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.2.2/js/buttons.html5.min.js"></script>
    <script src="https://cdn.datatables.net/buttons/2.2.2/js/buttons.print.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>

    <script>
    $(document).ready(function() {
        // Initialize Select2 for multi-select
        $('#month_range').select2({
            placeholder: "Select months",
            allowClear: true
        });

        // Generate aggregate report
        $('#generateAggregate').click(function() {
            generateAggregate();
        });

        // Export report
        $('#exportAggregate').click(function() {
            exportAggregate();
        });

        function generateAggregate() {
            var formData = {
                academic_year: $('#academic_year').val(),
                view_type: $('#view_type').val(),
                months: $('#month_range').val()
            };

            $('#loader').show();
            
            $.ajax({
                type: 'POST',
                url: 'get_attendance_aggregate.php',
                data: formData,
                dataType: 'json',
                success: function(response) {
                    $('#loader').hide();
                    
                    if (response.status === 'success') {
                        displayAggregate(response);
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: response.message
                        });
                    }
                },
                error: function(xhr, status, error) {
                    $('#loader').hide();
                    console.error("AJAX Error:", error);
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to generate report'
                    });
                }
            });
        }

        function displayAggregate(response) {
            // Hide all views first
            $('#classCardsView').hide();
            $('#monthlyTableView').hide();
            $('#studentDetailView').hide();
            $('#trendView').hide();
            
            // Show overall summary
            $('#overallSummary').show();
            $('#totalStudents').text(response.overall.total_students);
            $('#avgAttendance').text(response.overall.avg_attendance + '%');
            $('#totalPresent').text(response.overall.total_present);
            $('#totalAbsent').text(response.overall.total_absent);

            // Display based on view type
            var viewType = $('#view_type').val();
            
            switch(viewType) {
                case 'class':
                    displayClassView(response.class_data);
                    break;
                case 'month':
                    displayMonthlyView(response.monthly_data);
                    break;
                case 'student':
                    displayStudentView(response.student_data);
                    break;
                case 'trend':
                    displayTrendView(response.trend_data);
                    break;
            }
        }

        function displayClassView(classData) {
            var container = $('#classCardsContainer');
            container.empty();
            
            $.each(classData, function(index, classInfo) {
                var cardClass = classInfo.percentage >= 75 ? 'high-attendance' : 
                               (classInfo.percentage >= 60 ? 'medium-attendance' : 'low-attendance');
                
                var card = '<div class="col-md-4">' +
                    '<div class="class-card" data-class-id="' + classInfo.class_id + '">' +
                    '<div class="class-name">Class ' + classInfo.class_name + '</div>' +
                    '<div class="stats">' +
                    '<span class="stat-badge total">Total: ' + classInfo.student_count + '</span>' +
                    '<span class="stat-badge present">Present: ' + classInfo.present_days + '</span>' +
                    '<span class="stat-badge absent">Absent: ' + classInfo.absent_days + '</span>' +
                    '<span class="stat-badge percentage ' + cardClass + '">' + classInfo.percentage + '%</span>' +
                    '</div>' +
                    '<div class="progress">' +
                    '<div class="progress-bar bg-success" role="progressbar" style="width: ' + classInfo.percentage + '%" ' +
                    'aria-valuenow="' + classInfo.percentage + '" aria-valuemin="0" aria-valuemax="100"></div>' +
                    '</div>' +
                    '<div class="mt-2">' +
                    '<small class="text-muted">High: ' + classInfo.high_count + ' | Medium: ' + classInfo.medium_count + ' | Low: ' + classInfo.low_count + '</small>' +
                    '</div>' +
                    '</div>' +
                    '</div>';
                
                container.append(card);
            });
            
            $('#classCardsView').show();
            
            // Add click handler for class cards
            $('.class-card').click(function() {
                var classId = $(this).data('class-id');
                showClassDetail(classId);
            });
        }

        function displayMonthlyView(monthlyData) {
            var tbody = $('#monthlySummaryData');
            tbody.empty();
            
            var totalPresent = 0;
            var totalDays = 0;
            
            $.each(monthlyData, function(index, month) {
                var trendIcon = month.trend > 0 ? '<i class="fa fa-arrow-up trend-up"></i>' : 
                               (month.trend < 0 ? '<i class="fa fa-arrow-down trend-down"></i>' : '-');
                
                var row = '<tr>' +
                    '<td><strong>' + month.name + '</strong></td>' +
                    '<td>' + month.student_count + '</td>' +
                    '<td>' + month.total_days + '</td>' +
                    '<td>' + month.present_days + '</td>' +
                    '<td>' + month.absent_days + '</td>' +
                    '<td class="' + (month.percentage >= 75 ? 'high-attendance' : 
                                    (month.percentage >= 60 ? 'medium-attendance' : 'low-attendance')) + '">' +
                    month.percentage + '%</td>' +
                    '<td>' + month.high_count + '</td>' +
                    '<td>' + month.medium_count + '</td>' +
                    '<td>' + month.low_count + '</td>' +
                    '<td>' + trendIcon + ' ' + Math.abs(month.trend) + '%</td>' +
                    '</tr>';
                
                tbody.append(row);
                
                totalPresent += month.present_days;
                totalDays += month.total_days;
            });
            
            $('#monthlyTableView').show();
            
            // Initialize DataTable
            if ($.fn.DataTable.isDataTable('#monthlySummaryTable')) {
                $('#monthlySummaryTable').DataTable().destroy();
            }
            
            $('#monthlySummaryTable').DataTable({
                pageLength: 12,
                order: [[0, 'asc']],
                dom: 'Bfrtip',
                buttons: ['copy', 'excel', 'pdf', 'print']
            });
        }

        function displayStudentView(studentData) {
            var tbody = $('#studentDetailData');
            tbody.empty();
            
            var sno = 1;
            $.each(studentData, function(index, student) {
                var row = '<tr>' +
                    '<td>' + (sno++) + '</td>' +
                    '<td>' + student.student_id + '</td>' +
                    '<td>' + student.name + '</td>' +
                    '<td>' + student.class_name + '</td>' +
                    '<td>' + student.section_name + '</td>' +
                    '<td>' + student.roll_no + '</td>';
                
                // Add monthly attendance
                var totalPresent = 0;
                var totalDays = 0;
                
                $.each(student.monthly, function(month, attendance) {
                    row += '<td class="' + (attendance.percentage >= 75 ? 'high-attendance' : 
                                          (attendance.percentage >= 60 ? 'medium-attendance' : 'low-attendance')) + '">' +
                          attendance.present + '/' + attendance.total + '<br>' +
                          '<small>' + attendance.percentage + '%</small></td>';
                    
                    totalPresent += attendance.present;
                    totalDays += attendance.total;
                });
                
                var overallPercentage = totalDays > 0 ? ((totalPresent / totalDays) * 100).toFixed(2) : 0;
                var status = overallPercentage >= 75 ? 'Good' : (overallPercentage >= 60 ? 'Average' : 'Poor');
                var statusClass = overallPercentage >= 75 ? 'high-attendance' : 
                                 (overallPercentage >= 60 ? 'medium-attendance' : 'low-attendance');
                
                row += '<td><strong>' + totalPresent + '</strong></td>' +
                    '<td>' + totalDays + '</td>' +
                    '<td class="' + statusClass + '"><strong>' + overallPercentage + '%</strong></td>' +
                    '<td><span class="badge ' + statusClass + '">' + status + '</span></td>' +
                    '</tr>';
                
                tbody.append(row);
            });
            
            $('#studentDetailView').show();
            
            // Initialize DataTable
            if ($.fn.DataTable.isDataTable('#studentDetailTable')) {
                $('#studentDetailTable').DataTable().destroy();
            }
            
            $('#studentDetailTable').DataTable({
                pageLength: 25,
                order: [[2, 'asc']],
                dom: 'Bfrtip',
                buttons: ['copy', 'excel', 'pdf', 'print']
            });
        }

        function displayTrendView(trendData) {
            var ctx = document.getElementById('trendChart').getContext('2d');
            
            // Destroy existing chart if any
            if (window.trendChart) {
                window.trendChart.destroy();
            }
            
            // Prepare data
            var months = [];
            var percentages = [];
            var highCounts = [];
            var mediumCounts = [];
            var lowCounts = [];
            
            $.each(trendData, function(index, month) {
                months.push(month.name);
                percentages.push(month.percentage);
                highCounts.push(month.high_count);
                mediumCounts.push(month.medium_count);
                lowCounts.push(month.low_count);
            });
            
            // Create chart
            window.trendChart = new Chart(ctx, {
                type: 'line',
                data: {
                    labels: months,
                    datasets: [{
                        label: 'Attendance Percentage',
                        data: percentages,
                        borderColor: 'rgb(75, 192, 192)',
                        backgroundColor: 'rgba(75, 192, 192, 0.2)',
                        tension: 0.1,
                        yAxisID: 'y-percentage'
                    }, {
                        label: 'High Attendance',
                        data: highCounts,
                        borderColor: 'rgb(40, 167, 69)',
                        backgroundColor: 'rgba(40, 167, 69, 0.1)',
                        type: 'bar',
                        yAxisID: 'y-count'
                    }, {
                        label: 'Medium Attendance',
                        data: mediumCounts,
                        borderColor: 'rgb(255, 193, 7)',
                        backgroundColor: 'rgba(255, 193, 7, 0.1)',
                        type: 'bar',
                        yAxisID: 'y-count'
                    }, {
                        label: 'Low Attendance',
                        data: lowCounts,
                        borderColor: 'rgb(220, 53, 69)',
                        backgroundColor: 'rgba(220, 53, 69, 0.1)',
                        type: 'bar',
                        yAxisID: 'y-count'
                    }]
                },
                options: {
                    responsive: true,
                    interaction: {
                        mode: 'index',
                        intersect: false,
                    },
                    scales: {
                        'y-percentage': {
                            type: 'linear',
                            display: true,
                            position: 'left',
                            title: {
                                display: true,
                                text: 'Attendance %'
                            },
                            min: 0,
                            max: 100
                        },
                        'y-count': {
                            type: 'linear',
                            display: true,
                            position: 'right',
                            title: {
                                display: true,
                                text: 'Student Count'
                            },
                            grid: {
                                drawOnChartArea: false
                            }
                        }
                    }
                }
            });
            
            // Display trend stats
            var statsHtml = '';
            var bestMonth = trendData.reduce((max, month) => month.percentage > max.percentage ? month : max, trendData[0]);
            var worstMonth = trendData.reduce((min, month) => month.percentage < min.percentage ? month : min, trendData[0]);
            
            statsHtml += '<div class="col-md-4">' +
                '<div class="summary-card" style="background: linear-gradient(135deg, #28a745 0%, #20c997 100%);">' +
                '<div class="label">Best Month</div>' +
                '<h3>' + bestMonth.name + '</h3>' +
                '<div>' + bestMonth.percentage + '%</div>' +
                '</div></div>';
            
            statsHtml += '<div class="col-md-4">' +
                '<div class="summary-card" style="background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);">' +
                '<div class="label">Worst Month</div>' +
                '<h3>' + worstMonth.name + '</h3>' +
                '<div>' + worstMonth.percentage + '%</div>' +
                '</div></div>';
            
            statsHtml += '<div class="col-md-4">' +
                '<div class="summary-card" style="background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);">' +
                '<div class="label">Average Trend</div>' +
                '<h3>' + calculateAverageTrend(trendData) + '%</h3>' +
                '<div>Month over Month</div>' +
                '</div></div>';
            
            $('#trendStats').html(statsHtml);
            $('#trendView').show();
        }

        function calculateAverageTrend(trendData) {
            var totalTrend = 0;
            var count = 0;
            
            for (var i = 1; i < trendData.length; i++) {
                totalTrend += trendData[i].trend;
                count++;
            }
            
            return count > 0 ? (totalTrend / count).toFixed(2) : 0;
        }

        function showClassDetail(classId) {
            // Implement drill-down to class detail view
            Swal.fire({
                title: 'Class Detail',
                text: 'Detailed view for selected class will be shown here',
                icon: 'info'
            });
        }

        function exportAggregate() {
            var formData = {
                academic_year: $('#academic_year').val(),
                view_type: $('#view_type').val(),
                months: $('#month_range').val(),
                export: true
            };

            // Create a form and submit for file download
            var form = $('<form method="POST" action="export_attendance_aggregate.php">');
            $.each(formData, function(key, value) {
                if (Array.isArray(value)) {
                    $.each(value, function(i, v) {
                        form.append($('<input type="hidden" name="' + key + '[]">').val(v));
                    });
                } else {
                    form.append($('<input type="hidden" name="' + key + '">').val(value));
                }
            });
            $('body').append(form);
            form.submit();
            form.remove();
        }
    });
    </script>
</body>
</html>