<?php
// attendance_report.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 year 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);
?>

<!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 Report</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">
    <script src="js/modernizr/modernizr.min.js"></script>
    <script src="js/jquery/jquery-2.2.4.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        .report-card {
            background: #fff;
            border-radius: 10px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .select2-container {
            width: 100% !important;
        }
        .select2-selection--multiple {
            min-height: 38px !important;
        }
        .summary-box {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            margin-bottom: 20px;
        }
        .summary-box h3 {
            margin: 0;
            font-size: 2em;
        }
        .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; }
        .no-data {
            color: #999;
            font-style: italic;
            background-color: #f8f9fa;
        }
        .export-btn {
            margin-right: 10px;
        }
        .filter-section {
            background: #f8f9fa;
            padding: 20px;
            border-radius: 10px;
            margin-bottom: 20px;
        }
        .month-column {
            min-width: 100px;
            text-align: center;
        }
        .student-name {
            font-weight: 500;
        }
        .table-wrapper {
            overflow-x: auto;
            max-width: 100%;
        }
        .attendance-badge {
            display: inline-block;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: bold;
        }
        .attendance-badge.present {
            background-color: #d4edda;
            color: #155724;
        }
        .attendance-badge.absent {
            background-color: #f8d7da;
            color: #721c24;
        }
        .attendance-badge.partial {
            background-color: #fff3cd;
            color: #856404;
        }
        .refresh-btn {
            margin-left: 10px;
        }
        .month-header {
            background-color: #e3f2fd;
            text-align: center;
            vertical-align: middle;
        }
    </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 Report (Nepali Calendar) - Month Wise View</h5>
                                    </div>
                           
                                <!-- Add this where you want the attendance aggregate button to appear -->

            
          <a href="attendance_aggregate.php" class="btn btn-success">
    <i class="fa fa-bar-chart"></i> View Attendance Aggregate
</a>

     </div>
                                <div class="panel-body">
                                    
                                    <!-- Filter Section -->
                                    <div class="filter-section">
                                        <form id="reportFilterForm">
                                            <div class="row">
                                                <div class="form-group col-md-3">
                                                    <label for="academic_year">Academic Year</label>
                                                    <select id="academic_year" name="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 class="form-group col-md-3">
                                                    <label for="class_id">Select Class</label>
                                                    <select id="class_id" name="class_id" class="form-control">
                                                        <option value="">All Classes</option>
                                                        <?php
                                                        $stmt = $conn->query("SELECT class_id, class FROM classes WHERE status = 1 ORDER BY class_numeric");
                                                        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                                            echo "<option value='" . $row['class_id'] . "'>" . $row['class'] . "</option>";
                                                        }
                                                        ?>
                                                    </select>
                                                </div>

                                                <div class="form-group col-md-3">
                                                    <label for="section_ids">Select Sections</label>
                                                    <select id="section_ids" name="section_ids[]" class="form-control select2-multiple" multiple="multiple">
                                                        <?php
                                                        $stmt = $conn->query("SELECT section_id, section_name FROM sections WHERE status = 1 ORDER BY section_name");
                                                        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
                                                            echo "<option value='" . $row['section_id'] . "'>Section " . $row['section_name'] . "</option>";
                                                        }
                                                        ?>
                                                    </select>
                                                </div>

                                                <div class="form-group col-md-3">
                                                    <label for="nepali_months">Select Months</label>
                                                    <select id="nepali_months" name="nepali_months[]" class="form-control select2-multiple" multiple="multiple">
                                                        <?php
                                                        $nepali_months = [
                                                            'Baisakh', 'Jestha', 'Ashadh', 'Shrawan', 
                                                            'Bhadra', 'Ashwin', 'Kartik', 'Mangsir', 
                                                            'Poush', 'Magh', 'Falgun', 'Chaitra'
                                                        ];
                                                        
                                                        foreach ($nepali_months as $month) {
                                                            echo "<option value='$month'>$month</option>";
                                                        }
                                                        ?>
                                                    </select>
                                                </div>
                                            </div>

                                            <div class="row">
                                                <div class="form-group col-md-3">
                                                    <label for="view_type">View Type</label>
                                                    <select id="view_type" name="view_type" class="form-control">
                                                        <option value="monthly">Month-wise Columns</option>
                                                        <option value="summary">Summary View</option>
                                                    </select>
                                                </div>

                                                <div class="form-group col-md-3">
                                                    <label for="data_display">Display Format</label>
                                                    <select id="data_display" name="data_display" class="form-control">
                                                        <option value="percentage">Attendance %</option>
                                                        <option value="present">Days Present</option>
                                                        <option value="absent">Days Absent</option>
                                                        <option value="status">Status (P/A)</option>
                                                    </select>
                                                </div>

                                                <div class="form-group col-md-2">
                                                    <label for="min_attendance">Min Attendance %</label>
                                                    <input type="number" id="min_attendance" name="min_attendance" class="form-control" min="0" max="100" placeholder="Min %">
                                                </div>

                                                <div class="form-group col-md-2">
                                                    <label for="max_attendance">Max Attendance %</label>
                                                    <input type="number" id="max_attendance" name="max_attendance" class="form-control" min="0" max="100" placeholder="Max %">
                                                </div>

                                                <div class="form-group col-md-2">
                                                    <label>&nbsp;</label>
                                                    <div>
                                                        <button type="button" id="generateReport" class="btn btn-primary">
                                                            <i class="fa fa-search"></i> Generate Report
                                                        </button>
                                                        <button type="button" id="resetFilters" class="btn btn-secondary">
                                                            <i class="fa fa-refresh"></i> Reset
                                                        </button>
                                                    </div>
                                                </div>
                                            </div>
                                        </form>
                                    </div>

                                    <!-- Summary Cards -->
                                    <div class="row" id="summaryCards" style="display: none;">
                                        <div class="col-md-2">
                                            <div class="summary-box">
                                                <h5>Total Students</h5>
                                                <h3 id="totalStudents">0</h3>
                                            </div>
                                        </div>
                                        <div class="col-md-2">
                                            <div class="summary-box" style="background: linear-gradient(135deg, #28a745 0%, #20c997 100%);">
                                                <h5>Avg Attendance</h5>
                                                <h3 id="avgAttendance">0%</h3>
                                            </div>
                                        </div>
                                        <div class="col-md-2">
                                            <div class="summary-box" style="background: linear-gradient(135deg, #17a2b8 0%, #138496 100%);">
                                                <h5>Total Present</h5>
                                                <h3 id="totalPresent">0</h3>
                                            </div>
                                        </div>
                                        <div class="col-md-2">
                                            <div class="summary-box" style="background: linear-gradient(135deg, #ffc107 0%, #fd7e14 100%);">
                                                <h5>High Attendance</h5>
                                                <h3 id="highCount">0</h3>
                                            </div>
                                        </div>
                                        <div class="col-md-2">
                                            <div class="summary-box" style="background: linear-gradient(135deg, #dc3545 0%, #c82333 100%);">
                                                <h5>Low Attendance</h5>
                                                <h3 id="lowCount">0</h3>
                                            </div>
                                        </div>
                                        <div class="col-md-2">
                                            <div class="summary-box" style="background: linear-gradient(135deg, #6c757d 0%, #5a6268 100%);">
                                                <h5>Months Selected</h5>
                                                <h3 id="totalMonths">0</h3>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Export and Refresh Buttons -->
                                    <div class="row mb-3" id="exportButtons" style="display: none;">
                                        <div class="col-md-12">
                                            <div class="btn-group">
                                                <button class="btn btn-success export-btn" onclick="exportData('excel')">
                                                    <i class="fa fa-file-excel-o"></i> Export to Excel
                                                </button>
                                                <button class="btn btn-danger export-btn" onclick="exportData('pdf')">
                                                    <i class="fa fa-file-pdf-o"></i> Export to PDF
                                                </button>
                                                <button class="btn btn-primary export-btn" onclick="exportData('csv')">
                                                    <i class="fa fa-file-text-o"></i> Export to CSV
                                                </button>
                                                <button class="btn btn-info export-btn" onclick="exportData('print')">
                                                    <i class="fa fa-print"></i> Print
                                                </button>
                                                <button class="btn btn-warning refresh-btn" onclick="refreshReport()">
                                                    <i class="fa fa-refresh"></i> Refresh Report
                                                </button>
                                            </div>
                                        </div>
                                    </div>

                                    <!-- Report Table Container -->
                                    <div id="reportTableContainer" style="display: none;">
                                        <div class="table-wrapper">
                                            <table id="attendanceReportTable" class="table table-bordered table-striped" style="width:100%">
                                                <thead id="tableHeader">
                                                    <!-- Dynamic headers will be inserted here -->
                                                </thead>
                                                <tbody id="reportData">
                                                    <!-- Dynamic data will be inserted here -->
                                                </tbody>
                                                <tfoot id="tableFooter">
                                                    <!-- Dynamic footer will be inserted here -->
                                                </tfoot>
                                            </table>
                                        </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>

    <!-- Scripts -->
    <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>
        $(document).ready(function () {
            // Initialize Select2 for multi-select
            $('.select2-multiple').select2({
                placeholder: "Select options",
                allowClear: true
            });

            // Load sections when class is selected
            $('#class_id').change(function() {
                var classId = $(this).val();
                if (classId) {
                    $.ajax({
                        type: 'POST',
                        url: 'get_sections.php',
                        data: { class_id: classId },
                        dataType: 'json',
                        success: function(response) {
                            var options = '';
                            if (response.status === 'success' && response.sections.length > 0) {
                                $.each(response.sections, function(index, section) {
                                    options += '<option value="' + section.section_id + '">Section ' + 
                                             section.section_name + '</option>';
                                });
                            }
                            $('#section_ids').html(options).trigger('change');
                        }
                    });
                }
            });

            // Generate Report
            $('#generateReport').click(function() {
                generateReport();
            });

            // Reset Filters
            $('#resetFilters').click(function() {
                $('#reportFilterForm')[0].reset();
                $('#section_ids').val(null).trigger('change');
                $('#nepali_months').val(null).trigger('change');
                $('#reportTableContainer').hide();
                $('#summaryCards').hide();
                $('#exportButtons').hide();
            });

            function generateReport() {
                var formData = {
                    academic_year: $('#academic_year').val(),
                    class_id: $('#class_id').val(),
                    section_ids: $('#section_ids').val(),
                    nepali_months: $('#nepali_months').val(),
                    min_attendance: $('#min_attendance').val(),
                    max_attendance: $('#max_attendance').val(),
                    view_type: $('#view_type').val(),
                    data_display: $('#data_display').val()
                };

                // Validate at least one month selected
                if (!formData.nepali_months || formData.nepali_months.length === 0) {
                    Swal.fire({
                        icon: 'warning',
                        title: 'Select Months',
                        text: 'Please select at least one month'
                    });
                    return;
                }

                $('#loader').show();

                $.ajax({
                    type: 'POST',
                    url: 'get_attendance_report_data_advanced.php',
                    data: formData,
                    dataType: 'json',
                    success: function(response) {
                        $('#loader').hide();
                        
                        if (response.status === 'success') {
                            if (formData.view_type === 'monthly') {
                                displayMonthlyReport(response.data, response.summary, response.months, formData.data_display);
                            } else {
                                displaySummaryReport(response.data, response.summary);
                            }
                        } 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 displayMonthlyReport(data, summary, months, displayFormat) {
                // Update summary cards
                $('#totalStudents').text(summary.total_students);
                $('#avgAttendance').text(summary.avg_attendance + '%');
                $('#totalPresent').text(summary.total_present);
                $('#highCount').text(summary.high_attendance);
                $('#lowCount').text(summary.low_attendance);
                $('#totalMonths').text(months.length);
                
                $('#summaryCards').show();
                $('#exportButtons').show();

                // Build dynamic table header
                var headerHtml = '<tr>';
                headerHtml += '<th>S.No.</th>';
                headerHtml += '<th>Student ID</th>';
                headerHtml += '<th>Student Name</th>';
                headerHtml += '<th>Class</th>';
                headerHtml += '<th>Section</th>';
                headerHtml += '<th>Roll No.</th>';
                
                // Add month columns
                months.forEach(function(month) {
                    headerHtml += '<th class="month-header">' + month + '</th>';
                });
                
                headerHtml += '<th>Total Days</th>';
                headerHtml += '<th>Total Present</th>';
                headerHtml += '<th>Total Absent</th>';
                headerHtml += '<th>Avg %</th>';
                headerHtml += '<th>Status</th>';
                headerHtml += '</tr>';
                
                $('#tableHeader').html(headerHtml);

                // Build table body
                var tbody = '';
                var sno = 1;
                
                data.forEach(function(row) {
                    var statusClass = '';
                    var statusText = '';
                    
                    if (row.avg_percentage >= 75) {
                        statusClass = 'high-attendance';
                        statusText = 'Good';
                    } else if (row.avg_percentage >= 60) {
                        statusClass = 'medium-attendance';
                        statusText = 'Average';
                    } else {
                        statusClass = 'low-attendance';
                        statusText = 'Poor';
                    }
                    
                    tbody += '<tr>';
                    tbody += '<td>' + sno++ + '</td>';
                    tbody += '<td>' + row.student_id + '</td>';
                    tbody += '<td class="student-name">' + row.student_name + '</td>';
                    tbody += '<td>' + row.class_name + '</td>';
                    tbody += '<td>' + row.section_name + '</td>';
                    tbody += '<td>' + row.roll_no + '</td>';
                    
                    // Add month-wise data
                    months.forEach(function(month) {
                        var monthData = row.monthly_data[month] || { present: 0, total: 0, percentage: 0 };
                        
                        if (displayFormat === 'percentage') {
                            var displayValue = monthData.percentage > 0 ? monthData.percentage + '%' : '-';
                            var cellClass = monthData.percentage >= 75 ? 'high-attendance' : 
                                          (monthData.percentage >= 60 ? 'medium-attendance' : 
                                          (monthData.percentage > 0 ? 'low-attendance' : 'no-data'));
                            tbody += '<td class="' + cellClass + '">' + displayValue + '</td>';
                        } else if (displayFormat === 'present') {
                            var displayValue = monthData.present > 0 ? monthData.present : '-';
                            tbody += '<td>' + displayValue + '</td>';
                        } else if (displayFormat === 'absent') {
                            var displayValue = monthData.total > 0 ? (monthData.total - monthData.present) : '-';
                            tbody += '<td>' + displayValue + '</td>';
                        } else if (displayFormat === 'status') {
                            var status = '';
                            if (monthData.total > 0) {
                                if (monthData.present === monthData.total) {
                                    status = '<span class="attendance-badge present">Present</span>';
                                } else if (monthData.present === 0) {
                                    status = '<span class="attendance-badge absent">Absent</span>';
                                } else {
                                    status = '<span class="attendance-badge partial">' + monthData.present + '/' + monthData.total + '</span>';
                                }
                            } else {
                                status = '<span class="attendance-badge no-data">No Data</span>';
                            }
                            tbody += '<td>' + status + '</td>';
                        }
                    });
                    
                    tbody += '<td>' + row.total_days + '</td>';
                    tbody += '<td>' + row.days_present + '</td>';
                    tbody += '<td>' + row.days_absent + '</td>';
                    tbody += '<td class="' + statusClass + '">' + row.avg_percentage + '%</td>';
                    tbody += '<td><span class="badge ' + statusClass + '">' + statusText + '</span></td>';
                    tbody += '</tr>';
                });
                
                $('#reportData').html(tbody);

                // Build footer
                var footerHtml = '<tr>';
                footerHtml += '<th colspan="6" class="text-right">Total/Average:</th>';
                
                months.forEach(function(month) {
                    footerHtml += '<th id="month-total-' + month + '">-</th>';
                });
                
                footerHtml += '<th id="totalDays">' + summary.total_days + '</th>';
                footerHtml += '<th id="totalPresent">' + summary.total_present + '</th>';
                footerHtml += '<th id="totalAbsent">' + summary.total_absent + '</th>';
                footerHtml += '<th id="overallPercentage">' + summary.avg_attendance + '%</th>';
                footerHtml += '<th></th>';
                footerHtml += '</tr>';
                
                $('#tableFooter').html(footerHtml);
                
                $('#reportTableContainer').show();
                
                // Initialize DataTable with custom options for month-wise view
                if ($.fn.DataTable.isDataTable('#attendanceReportTable')) {
                    $('#attendanceReportTable').DataTable().destroy();
                }
                
                $('#attendanceReportTable').DataTable({
                    pageLength: 25,
                    order: [[2, 'asc']],
                    scrollX: true,
                    autoWidth: false,
                    dom: 'Bfrtip',
                    buttons: [
                        {
                            extend: 'excel',
                            text: '<i class="fa fa-file-excel-o"></i> Excel',
                            className: 'btn btn-success btn-sm'
                        },
                        {
                            extend: 'pdf',
                            text: '<i class="fa fa-file-pdf-o"></i> PDF',
                            className: 'btn btn-danger btn-sm',
                            orientation: 'landscape',
                            pageSize: 'A3'
                        },
                        {
                            extend: 'csv',
                            text: '<i class="fa fa-file-text-o"></i> CSV',
                            className: 'btn btn-primary btn-sm'
                        },
                        {
                            extend: 'print',
                            text: '<i class="fa fa-print"></i> Print',
                            className: 'btn btn-info btn-sm',
                            orientation: 'landscape'
                        }
                    ]
                });
            }

            function displaySummaryReport(data, summary) {
                // Similar to original summary view
                var tbody = '';
                var sno = 1;
                
                data.forEach(function(row) {
                    var statusClass = '';
                    var statusText = '';
                    
                    if (row.avg_percentage >= 75) {
                        statusClass = 'high-attendance';
                        statusText = 'Good';
                    } else if (row.avg_percentage >= 60) {
                        statusClass = 'medium-attendance';
                        statusText = 'Average';
                    } else {
                        statusClass = 'low-attendance';
                        statusText = 'Poor';
                    }
                    
                    tbody += '<tr>';
                    tbody += '<td>' + sno++ + '</td>';
                    tbody += '<td>' + row.student_id + '</td>';
                    tbody += '<td>' + row.student_name + '</td>';
                    tbody += '<td>' + row.class_name + '</td>';
                    tbody += '<td>' + row.section_name + '</td>';
                    tbody += '<td>' + row.roll_no + '</td>';
                    tbody += '<td>' + row.total_days + '</td>';
                    tbody += '<td>' + row.days_present + '</td>';
                    tbody += '<td>' + row.days_absent + '</td>';
                    tbody += '<td class="' + statusClass + '">' + row.avg_percentage + '%</td>';
                    tbody += '<td><span class="badge ' + statusClass + '">' + statusText + '</span></td>';
                    tbody += '</tr>';
                });
                
                $('#reportData').html(tbody);
                
                // Simple header for summary view
                var headerHtml = '<tr>' +
                    '<th>S.No.</th>' +
                    '<th>Student ID</th>' +
                    '<th>Student Name</th>' +
                    '<th>Class</th>' +
                    '<th>Section</th>' +
                    '<th>Roll No.</th>' +
                    '<th>Total Days</th>' +
                    '<th>Total Present</th>' +
                    '<th>Total Absent</th>' +
                    '<th>Attendance %</th>' +
                    '<th>Status</th>' +
                    '</tr>';
                
                $('#tableHeader').html(headerHtml);
                
                $('#reportTableContainer').show();
                
                // Initialize DataTable
                if ($.fn.DataTable.isDataTable('#attendanceReportTable')) {
                    $('#attendanceReportTable').DataTable().destroy();
                }
                
                $('#attendanceReportTable').DataTable({
                    pageLength: 25,
                    order: [[2, 'asc']],
                    dom: 'Bfrtip',
                    buttons: [
                        {
                            extend: 'excel',
                            text: '<i class="fa fa-file-excel-o"></i> Excel',
                            className: 'btn btn-success btn-sm'
                        },
                        {
                            extend: 'pdf',
                            text: '<i class="fa fa-file-pdf-o"></i> PDF',
                            className: 'btn btn-danger btn-sm'
                        },
                        {
                            extend: 'csv',
                            text: '<i class="fa fa-file-text-o"></i> CSV',
                            className: 'btn btn-primary btn-sm'
                        },
                        {
                            extend: 'print',
                            text: '<i class="fa fa-print"></i> Print',
                            className: 'btn btn-info btn-sm'
                        }
                    ]
                });
            }
        });

        // Refresh report function
        function refreshReport() {
            $('#generateReport').click();
        }

        // Export function
        function exportData(type) {
            var formData = {
                academic_year: $('#academic_year').val(),
                class_id: $('#class_id').val(),
                section_ids: $('#section_ids').val(),
                nepali_months: $('#nepali_months').val(),
                min_attendance: $('#min_attendance').val(),
                max_attendance: $('#max_attendance').val(),
                view_type: $('#view_type').val(),
                data_display: $('#data_display').val(),
                export_type: type
            };

            // Create a form and submit for file download
            var form = $('<form method="POST" action="export_attendance_advanced.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>