<?php
// control_sheet.php
include('session_validator.php');
include('includes/db.php');
?>
<!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>Generate Control Sheet - SRMS</title>
    
    <!-- CSS Files -->
    <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">
    
    <!-- DataTables CSS -->
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/buttons/2.3.6/css/buttons.dataTables.min.css">
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/select/1.7.0/css/select.dataTables.min.css">
    
    <style>
        .control-sheet-container {
            margin-top: 20px;
            padding: 15px;
            background: #fff;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .control-sheet-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 15px;
            border-radius: 8px 8px 0 0;
            margin-bottom: 20px;
        }
        
        .info-card {
            background: #f8f9fa;
            border-left: 4px solid #007bff;
            padding: 10px 15px;
            margin-bottom: 15px;
            border-radius: 4px;
        }
        
        .info-card h5 {
            margin: 0;
            color: #495057;
            font-size: 14px;
            font-weight: 600;
        }
        
        .info-card p {
            margin: 5px 0 0;
            font-size: 16px;
            font-weight: 500;
            color: #007bff;
        }
        
        .table-wrapper {
            margin-top: 20px;
        }
        
        /* Symbol number styling - RED color */
        .symbol-number {
            color: #dc3545;
            font-weight: 700;
            font-size: 16px;
            font-family: 'Courier New', monospace;
        }
        
        .no-symbol {
            color: #6c757d;
            font-style: italic;
        }
        
        /* Action buttons styling */
        .action-buttons {
            position: fixed;
            bottom: 30px;
            right: 30px;
            z-index: 1000;
        }
        
        .action-buttons .btn {
            margin-left: 10px;
            box-shadow: 0 4px 8px rgba(0,0,0,0.2);
            padding: 10px 20px;
            font-weight: 600;
        }
        
        .action-buttons .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 6px 12px rgba(0,0,0,0.2);
        }
        
        .summary-stats {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
            flex-wrap: wrap;
        }
        
        .stat-box {
            flex: 1;
            background: white;
            padding: 15px;
            margin: 5px;
            border-radius: 8px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
            text-align: center;
            min-width: 150px;
        }
        
        .stat-box h3 {
            margin: 0;
            font-size: 24px;
            font-weight: 700;
            color: #007bff;
        }
        
        .stat-box p {
            margin: 5px 0 0;
            color: #6c757d;
            font-size: 14px;
        }
        
        .no-data-message {
            text-align: center;
            padding: 50px;
            background: #f8f9fa;
            border-radius: 8px;
            color: #6c757d;
        }
        
        .no-data-message i {
            font-size: 48px;
            margin-bottom: 15px;
            color: #dee2e6;
        }
        
        .btn-select-all {
            margin-top: 24px;
            margin-left: 10px;
        }
        
        /* DataTables Custom Styling */
        .dataTables_wrapper {
            padding: 20px 0;
        }
        
        .dataTables_filter input {
            border: 1px solid #ced4da;
            border-radius: 4px;
            padding: 6px 12px;
            margin-left: 10px;
        }
        
        .dataTables_length select {
            border: 1px solid #ced4da;
            border-radius: 4px;
            padding: 6px 12px;
            margin: 0 10px;
        }
        
        .dt-buttons {
            margin-bottom: 15px;
        }
        
        .dt-buttons .btn {
            margin-right: 5px;
            border-radius: 4px;
            padding: 6px 12px;
            font-size: 14px;
        }
        
        /* Column visibility dropdown */
        .dt-button-collection {
            background: white;
            border: 1px solid #dee2e6;
            border-radius: 4px;
            padding: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .dt-button-collection .dt-button {
            display: block;
            width: 100%;
            text-align: left;
            padding: 8px 12px;
            margin: 2px 0;
            border: none;
            background: none;
            cursor: pointer;
        }
        
        .dt-button-collection .dt-button:hover {
            background-color: #f8f9fa;
        }
        
        .dt-button-collection .dt-button.active {
            background-color: #007bff;
            color: white;
        }
        
        /* Column filter inputs */
        .column-filter {
            width: 100%;
            padding: 4px 8px;
            border: 1px solid #ced4da;
            border-radius: 3px;
            font-size: 12px;
            margin-top: 5px;
        }
        
        .column-filter:focus {
            outline: none;
            border-color: #80bdff;
            box-shadow: 0 0 0 0.2rem rgba(0,123,255,.25);
        }
        
        /* Print styles */
        @media print {
            body * {
                visibility: hidden;
            }
            #controlSheetTable, #controlSheetTable * {
                visibility: visible;
            }
            #controlSheetTable {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
            }
        }
    </style>
</head>
<body class="top-navbar-fixed">
    <div class="main-wrapper">
        <!-- ========== TOP NAVBAR ========== -->
        <?php include('includes/topbar.php'); ?>
        
        <!-- ========== WRAPPER FOR BOTH SIDEBARS & MAIN CONTENT ========== -->
        <div class="content-wrapper">
            <div class="content-container">
                <?php include('includes/leftbar.php'); ?>
                
                <div class="main-page">
                    <div class="container-fluid">
                        <div class="row breadcrumb-div">
                            <div class="col-md-6">
                                <ul class="breadcrumb">
                                    <li><a href="dashboard.php"><i class="fa fa-home"></i> Home</a></li>
                                    <li> Exam</li>
                                    <li class="active">Control Sheet</li>
                                </ul>
                            </div>
                        </div>
                    </div>
                    
                    <section class="section">
                        <div class="container-fluid">
                            <div class="row">
                                <div class="col-md-12">
                                    <div class="panel">
                                        <div class="panel-heading">
                                            <div class="panel-title">
                                                <h5><i class="fa fa-file-text-o"></i> Generate Control Sheet</h5>
                                            </div>
                                        </div>
                                        
                                        <div class="panel-body">
                                            <form id="generateControlSheetForm">
                                                <div class="row">
                                                    <div class="form-group col-md-4">
                                                        <label for="exam_type">Select Exam Type:</label>
                                                        <select id="exam_type" name="exam_type" class="form-control" style="width: 100%;" required>
                                                            <option value="">-- Select Exam Type --</option>
                                                            <?php
                                                            $examQuery = "SELECT id, exam_type, exm_year FROM examination_type ORDER BY exm_year DESC";
                                                            $result = $conn->query($examQuery);
                                                            while ($row = $result->fetch_assoc()) {
                                                                echo '<option value="' . $row['id'] . '">' . 
                                                                     htmlspecialchars($row['exam_type']) . ' (' . 
                                                                     htmlspecialchars($row['exm_year']) . ')' . '</option>';
                                                            }
                                                            ?>
                                                        </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" style="width: 100%;" required>
                                                            <option value="">-- First Select Exam --</option>
                                                        </select>
                                                    </div>
                                                    
                                                    <div class="form-group col-md-3">
                                                        <label for="section_id">Select Section(s):</label>
                                                        <select id="section_id" name="section_id[]" class="form-control select2-multiple" multiple="multiple" style="width: 100%;" required>
                                                            <option value="">-- First Select Class --</option>
                                                        </select>
                                                        <small class="form-text text-muted">Hold Ctrl/Cmd to select multiple sections</small>
                                                    </div>
                                                    
                                                    <div class="form-group col-md-2">
                                                        <label>&nbsp;</label>
                                                        <div class="btn-group" style="display: flex;">
                                                            <button type="submit" id="generateBtn" class="btn btn-primary" style="flex: 1;">
                                                                <i class="fa fa-search"></i> Generate
                                                            </button>
                                                            <button type="button" id="selectAllSections" class="btn btn-info" style="margin-left: 5px;" title="Select All Sections">
                                                                <i class="fa fa-check-square-o"></i>
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </form>
                                            
                                            <!-- Control Sheet Display Area -->
                                            <div id="controlSheetContainer" style="display: none;">
                                                <!-- Content will be loaded here -->
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </section>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Action Buttons (Fixed at bottom right) -->
    <div class="action-buttons no-print" id="actionButtons" style="display: none;">
        <button type="button" class="btn btn-success" onclick="exportToExcel()">
            <i class="fa fa-file-excel-o"></i> Excel
        </button>
        <button type="button" class="btn btn-primary" onclick="printControlSheet()">
            <i class="fa fa-print"></i> Print
        </button>
    </div>
    
    <!-- JavaScript Files -->
    <script src="js/jquery/jquery-2.2.4.min.js"></script>
    <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/select2/select2.min.js"></script>
    <script src="js/main.js"></script>
    
    <!-- DataTables -->
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>
    
    <!-- DataTables Buttons -->
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/2.3.6/js/dataTables.buttons.min.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.html5.min.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.print.min.js"></script>
    <script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/buttons/2.3.6/js/buttons.colVis.min.js"></script>
    
    <!-- SweetAlert2 -->
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    
    <!-- SheetJS for Excel Export -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.18.5/xlsx.full.min.js"></script>
    
    <script>
    $(document).ready(function() {
        // Initialize Select2
        $('#exam_type, #class_id').select2();
        $('.select2-multiple').select2({
            placeholder: "Select sections...",
            allowClear: true
        });
        
        // DataTable instance
        var controlSheetTable = null;
        var currentData = null;
        
        // When exam is selected, load classes
        $('#exam_type').change(function() {
            var examId = $(this).val();
            
            if (!examId) {
                $('#class_id').html('<option value="">-- First Select Exam --</option>').trigger('change');
                $('#section_id').html('<option value="">-- First Select Class --</option>').trigger('change');
                return;
            }
            
            // Show loading
            $('#class_id').html('<option value="">Loading classes...</option>').trigger('change');
            
            // Fetch classes for this exam
            $.ajax({
                url: 'ajax/get_classes_for_exam.php',
                type: 'GET',
                data: { exam_id: examId },
                dataType: 'json',
                success: function(response) {
                    $('#class_id').empty().append('<option value="">-- Select Class --</option>');
                    
                    if (response && response.length > 0) {
                        $.each(response, function(index, cls) {
                            $('#class_id').append(
                                $('<option></option>')
                                    .val(cls.class_id)
                                    .text(cls.class_name)
                            );
                        });
                        
                        Swal.fire({
                            icon: 'success',
                            title: 'Classes Loaded',
                            text: 'Select a class to continue',
                            timer: 1500,
                            showConfirmButton: false
                        });
                    } else {
                        Swal.fire({
                            icon: 'warning',
                            title: 'No Classes',
                            text: 'No classes found for this exam.',
                        });
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error loading classes:', error);
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to load classes.',
                    });
                }
            });
        });
        
        // When class is selected, load sections
        $('#class_id').change(function() {
            var classId = $(this).val();
            var examId = $('#exam_type').val();
            
            if (!classId || !examId) {
                $('#section_id').html('<option value="">-- First Select Class --</option>').trigger('change');
                return;
            }
            
            // Show loading
            $('#section_id').html('<option value="">Loading sections...</option>').trigger('change');
            
            // Fetch sections for this class and exam
            $.ajax({
                url: 'ajax/get_sections_for_class.php',
                type: 'GET',
                data: { 
                    exam_id: examId,
                    class_id: classId
                },
                dataType: 'json',
                success: function(response) {
                    $('#section_id').empty();
                    
                    if (response && response.length > 0) {
                        $.each(response, function(index, section) {
                            $('#section_id').append(
                                $('<option></option>')
                                    .val(section.section_id)
                                    .text(section.section_name)
                            );
                        });
                        
                        Swal.fire({
                            icon: 'success',
                            title: 'Sections Loaded',
                            text: 'Select section(s) to generate control sheet',
                            timer: 1500,
                            showConfirmButton: false
                        });
                    } else {
                        Swal.fire({
                            icon: 'warning',
                            title: 'No Sections',
                            text: 'No sections found for this class.',
                        });
                    }
                },
                error: function(xhr, status, error) {
                    console.error('Error loading sections:', error);
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to load sections.',
                    });
                }
            });
        });
        
        // Select all sections button
        $('#selectAllSections').click(function() {
            var $sectionSelect = $('#section_id');
            var allOptions = $sectionSelect.find('option').map(function() {
                return $(this).val();
            }).get();
            
            $sectionSelect.val(allOptions).trigger('change');
            
            Swal.fire({
                icon: 'success',
                title: 'All Sections Selected',
                text: 'All available sections have been selected.',
                timer: 1500,
                showConfirmButton: false
            });
        });
        
        // Generate Control Sheet
        $('#generateControlSheetForm').submit(function(e) {
            e.preventDefault();
            
            var examId = $('#exam_type').val();
            var classId = $('#class_id').val();
            var sectionIds = $('#section_id').val();
            
            // Validation
            if (!examId) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Select Exam',
                    text: 'Please select an exam first.',
                });
                return;
            }
            
            if (!classId) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Select Class',
                    text: 'Please select a class.',
                });
                return;
            }
            
            if (!sectionIds || sectionIds.length === 0) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Select Sections',
                    text: 'Please select at least one section.',
                });
                return;
            }
            
            // Show loading
            Swal.fire({
                title: 'Generating Control Sheet',
                text: 'Please wait...',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            // Prepare data
            var formData = new FormData();
            formData.append('exam_id', examId);
            formData.append('class_id', classId);
            
            // Add each section_id
            $.each(sectionIds, function(index, sectionId) {
                formData.append('section_ids[]', sectionId);
            });
            
            // Fetch control sheet data
            $.ajax({
                url: 'ajax/get_control_sheet.php',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: 'json',
                success: function(response) {
                    Swal.close();
                    
                    if (response.error) {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: response.error,
                        });
                        return;
                    }
                    
                    if (!response.data || response.data.length === 0) {
                        Swal.fire({
                            icon: 'info',
                            title: 'No Data',
                            text: response.message || 'No students found for the selected criteria.',
                        });
                        $('#controlSheetContainer').hide();
                        $('#actionButtons').hide();
                        return;
                    }
                    
                    // Store data for later use
                    currentData = response;
                    
                    // Sort data by symbol number first (numeric order)
                    response.data.sort(function(a, b) {
                        // Put students with no symbol at the end
                        if (!a.symbol_no && !b.symbol_no) return 0;
                        if (!a.symbol_no) return 1;
                        if (!b.symbol_no) return -1;
                        
                        // Compare symbol numbers as numbers
                        var numA = parseInt(a.symbol_no) || 0;
                        var numB = parseInt(b.symbol_no) || 0;
                        return numA - numB;
                    });
                    
                    // Display control sheet (plain, no grouping)
                    displayPlainControlSheet(response);
                    
                    // Show action buttons
                    $('#actionButtons').show();
                    
                    Swal.fire({
                        icon: 'success',
                        title: 'Success!',
                        text: 'Control sheet generated successfully.',
                        timer: 2000,
                        showConfirmButton: false
                    });
                },
                error: function(xhr, status, error) {
                    Swal.close();
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to generate control sheet: ' + error,
                    });
                    console.error('AJAX Error:', error, xhr.responseText);
                }
            });
        });
        
        // Function to display plain control sheet (no grouping)
        function displayPlainControlSheet(data) {
            var container = $('#controlSheetContainer');
            container.empty().show();
            
            var html = '<div class="control-sheet-container">';
            
            // Header with exam info
            html += '<div class="control-sheet-header">';
            html += '<h3><i class="fa fa-file-text-o"></i> Control Sheet</h3>';
            html += '<p>Exam: ' + data.exam_name + ' | Class: ' + data.class_name + '</p>';
            html += '</div>';
            
            // Simple summary
            html += '<div class="row mb-3">';
            html += '<div class="col-md-4"><strong>Total Students:</strong> ' + data.summary.total_students + '</div>';
            html += '<div class="col-md-4"><strong>With Symbol Numbers:</strong> ' + data.summary.with_symbols + '</div>';
            html += '<div class="col-md-4"><strong>Generated On:</strong> ' + new Date().toLocaleDateString() + '</div>';
            html += '</div>';
            
            // Plain table (no grouping)
            html += '<div class="table-wrapper">';
            html += '<table id="controlSheetTable" class="table table-bordered table-striped" style="width:100%">';
            html += '<thead>';
            html += '<tr>';
            html += '<th>Sl No.</th>';
            html += '<th>Section</th>';
            html += '<th>Registration No</th>';
            html += '<th>Student Name</th>';
            html += '<th>DOB</th>';
            html += '<th>Father\'s Name</th>';
            html += '<th>Symbol Number</th>';
            html += '<th>Signature</th>';
            html += '</tr>';
            html += '</thead>';
            html += '<tbody>';
            
            // Table Body - plain list, sorted by symbol number
            $.each(data.data, function(index, student) {
                var symbolHtml = student.symbol_no ? 
                    '<span class="symbol-number">' + student.symbol_no + '</span>' : 
                    '<span class="no-symbol">Not Assigned</span>';
                
                html += '<tr>';
                html += '<td class="text-center">' + (index + 1) + '</td>';
                html += '<td>' + (student.section_name || 'N/A') + '</td>';
                html += '<td>' + (student.registration_no || 'N/A') + '</td>';
                html += '<td>' + student.name + '</td>';
                html += '<td>' + (student.dob || 'N/A') + '</td>';
                html += '<td>' + (student.father_name || 'N/A') + '</td>';
                html += '<td class="text-center">' + symbolHtml + '</td>';
                html += '<td style="width: 150px;"></td>'; // Empty column for signature
                html += '</tr>';
            });
            
            html += '</tbody>';
            html += '</table>';
            html += '</div>';
            
            // Footer (hidden in print)
            html += '<div class="row mt-4 signature-line no-print">';
            html += '<div class="col-md-4 text-center">';
            html += '<p>_________________________</p>';
            html += '<p>Class Teacher</p>';
            html += '</div>';
            html += '<div class="col-md-4 text-center">';
            html += '<p>_________________________</p>';
            html += '<p>Exam Controller</p>';
            html += '</div>';
            html += '<div class="col-md-4 text-center">';
            html += '<p>_________________________</p>';
            html += '<p>Principal</p>';
            html += '</div>';
            html += '</div>';
            
            html += '</div>';
            
            container.html(html);
            
            // Initialize DataTable with buttons and column visibility
            initializeDataTable();
        }
        
        // Initialize DataTable with all features
        function initializeDataTable() {
            // Destroy existing DataTable if exists
            if ($.fn.DataTable.isDataTable('#controlSheetTable')) {
                $('#controlSheetTable').DataTable().destroy();
            }
            
            // Initialize new DataTable
            controlSheetTable = $('#controlSheetTable').DataTable({
                paging: true,
                pageLength: 25,
                lengthMenu: [[10, 25, 50, 100, -1], [10, 25, 50, 100, "All"]],
                ordering: true,
                searching: true,
                info: true,
                order: [[6, 'asc']], // Sort by symbol number column (index 6)
                
                // Buttons for export and column visibility
                dom: 'Bfrtip',
                buttons: [
                    {
                        extend: 'excelHtml5',
                        text: '<i class="fa fa-file-excel-o"></i> Excel',
                        titleAttr: 'Export to Excel',
                        className: 'btn btn-success btn-sm',
                        exportOptions: {
                            columns: ':visible'
                        }
                    },
                    {
                        extend: 'csvHtml5',
                        text: '<i class="fa fa-file-text-o"></i> CSV',
                        titleAttr: 'Export to CSV',
                        className: 'btn btn-info btn-sm',
                        exportOptions: {
                            columns: ':visible'
                        }
                    },
                    {
                        extend: 'colvis',
                        text: '<i class="fa fa-columns"></i> Columns',
                        titleAttr: 'Column Visibility',
                        className: 'btn btn-default btn-sm',
                        columns: ':not(:last-child)' // Don't allow hiding signature column
                    }
                ],
                
                // Column definitions
                columnDefs: [
                    { orderable: false, targets: [7] }, // Disable ordering on signature column
                    { className: 'text-center', targets: [0, 6] }, // Center align sl no and symbol
                    { type: 'num', targets: [6] } // Treat symbol number as numeric
                ],
                
                // Language settings
                language: {
                    search: "Search:",
                    lengthMenu: "Show _MENU_ entries",
                    info: "Showing _START_ to _END_ of _TOTAL_ entries",
                    paginate: {
                        first: "First",
                        last: "Last",
                        next: "Next",
                        previous: "Previous"
                    }
                },
                
                // Initialization complete
                initComplete: function() {
                    // Add custom filter inputs for each column
                    this.api().columns().every(function() {
                        var column = this;
                        var header = $(column.header());
                        
                        // Add filter input to all columns except last (signature)
                        if (column.index() < 7) {
                            header.append('<br><input type="text" class="column-filter" placeholder="Filter ' + header.text() + '">');
                            
                            // Filter on keyup
                            $('input', header).on('keyup change', function() {
                                if (column.search() !== this.value) {
                                    column.search(this.value).draw();
                                }
                            });
                        }
                    });
                    
                    // Add reset filters button
                    $('#controlSheetTable_wrapper').find('.dt-buttons').prepend(
                        '<button class="btn btn-warning btn-sm" onclick="resetFilters()"><i class="fa fa-undo"></i> Reset Filters</button> '
                    );
                }
            });
        }
        
        // Reset filters function
        window.resetFilters = function() {
            if (controlSheetTable) {
                controlSheetTable.search('').columns().search('').draw();
                $('.column-filter').val('');
            }
        };
    });
    
    // Export to Excel function
    function exportToExcel() {
        if (controlSheetTable) {
            controlSheetTable.button('.buttons-excel').trigger();
        } else {
            Swal.fire({
                icon: 'warning',
                title: 'No Data',
                text: 'Please generate a control sheet first.',
            });
        }
    }
    
    // Print function
    function printControlSheet() {
        var table = document.getElementById('controlSheetTable');
        if (!table) {
            Swal.fire({
                icon: 'warning',
                title: 'No Data',
                text: 'Please generate a control sheet first.',
            });
            return;
        }
        
        // Get exam and class info
        var examName = $('#exam_type option:selected').text();
        var className = $('#class_id option:selected').text();
        
        // Clone the table to avoid modifying the original
        var tableClone = table.cloneNode(true);
        
        // Remove the last column (Signature) from the clone for printing
        $(tableClone).find('tr').each(function() {
            $(this).find('th:last-child, td:last-child').remove();
        });
        
        // Create print HTML
        var printHTML = `
            <div style="padding: 20px;">
                <h2 style="text-align:center; margin-bottom:20px;">Control Sheet</h2>
                <div style="margin-bottom:20px;">
                    <strong>Exam:</strong> ${examName}<br>
                    <strong>Class:</strong> ${className}<br>
                    <strong>Date:</strong> ${new Date().toLocaleDateString()}<br>
                    <strong>Total Students:</strong> ${$('#controlSheetTable tbody tr').length}
                </div>
                ${tableClone.outerHTML}
            </div>
        `;
        
        // Create a new window for printing
        var printWindow = window.open('', '_blank');
        printWindow.document.write(`
            <html>
                <head>
                    <title>Control Sheet</title>
                    <style>
                        body { font-family: Arial, sans-serif; }
                        table { width: 100%; border-collapse: collapse; margin-top: 20px; }
                        th { background-color: #f2f2f2; font-weight: bold; text-align: center; border: 1px solid #000; padding: 8px; }
                        td { border: 1px solid #000; padding: 6px; }
                        .symbol-number { color: #dc3545; font-weight: bold; }
                        .no-symbol { color: #6c757d; font-style: italic; }
                        @media print {
                            th { background-color: #f2f2f2 !important; }
                            .symbol-number { color: #dc3545 !important; }
                        }
                    </style>
                </head>
                <body>
                    ${printHTML}
                </body>
            </html>
        `);
        
        printWindow.document.close();
        
        // Wait for resources to load then print
        setTimeout(function() {
            printWindow.print();
            printWindow.onafterprint = function() {
                printWindow.close();
            };
        }, 500);
    }
    </script>
</body>
</html>