<?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 Symbol Numbers</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">
    <script src="js/jquery/jquery-2.2.4.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <style>
        .form-section {
            margin-bottom: 25px;
            padding: 15px;
            border: 1px solid #e3e3e3;
            border-radius: 5px;
            background-color: #f9f9f9;
        }
        .form-section h6 {
            color: #2c3e50;
            border-bottom: 2px solid #3498db;
            padding-bottom: 8px;
            margin-bottom: 15px;
        }
        .student-list {
            max-height: 400px;
            overflow-y: auto;
            border: 1px solid #ddd;
            border-radius: 5px;
            padding: 10px;
            margin-top: 10px;
        }
        .student-item {
            padding: 8px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .student-item:last-child {
            border-bottom: none;
        }
        .symbol-input {
            width: 120px;
            text-align: center;
            font-weight: bold;
        }
        .action-buttons {
            margin-top: 20px;
            display: flex;
            gap: 10px;
        }
        .table-responsive {
            margin-top: 20px;
        }
        .badge-info {
            background-color: #17a2b8;
        }
        .badge-warning {
            background-color: #ffc107;
            color: #212529;
        }
    </style>
</head>
<body class="top-navbar-fixed">

    <div class="main-wrapper">
        <?php include('includes/topbar.php'); ?>
        <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="">Symbol Numbers</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-hashtag"></i> Manage Symbol Numbers</h5>
                                            </div>
                                        </div>
                                        <div class="panel-body">
                                            <!-- Selection Form -->
                                            <div class="form-section">
                                                <h6><i class="fa fa-filter"></i> Selection Criteria</h6>
                                                <form id="selectionForm">
                                                    <div class="row">
                                                        <div class="form-group col-md-4">
                                                            <label for="exam_type"><i class="fa fa-calendar-check"></i> Exam Type *</label>
                                                            <select id="exam_type" name="exam_type" class="form-control" required>
                                                                <option value="">-- Select Exam --</option>
                                                                <?php
                                                                $examQuery = "SELECT id, exam_type, exm_year FROM examination_type ORDER BY exm_year DESC, exam_type ASC";
                                                                $result = $conn->query($examQuery);
                                                                while ($row = $result->fetch_assoc()) {
                                                                    echo '<option value="' . $row['id'] . '">' . $row['exam_type'] . ' (' . $row['exm_year'] . ')</option>';
                                                                }
                                                                ?>
                                                            </select>
                                                        </div>

                                                        <div class="form-group col-md-4">
                                                            <label for="class_id"><i class="fa fa-graduation-cap"></i> Class *</label>
                                                            <select id="class_id" name="class_id" class="form-control" required>
                                                                <option value="">-- Select Class --</option>
                                                                <?php
                                                                $classQuery = "SELECT class_id, class, class_numeric FROM classes WHERE status='1' ORDER BY class_numeric ASC";
                                                                $result = $conn->query($classQuery);
                                                                while ($row = $result->fetch_assoc()) {
                                                                    echo '<option value="' . $row['class_id'] . '">' . htmlspecialchars($row['class']) . '</option>';
                                                                }
                                                                ?>
                                                            </select>
                                                        </div>

                                                        <div class="form-group col-md-4">
                                                            <label for="section_id"><i class="fa fa-columns"></i> Section(s) *</label>
                                                            <select id="section_id" name="section_id[]" class="form-control select2" multiple required disabled>
                                                                <option value="">-- Select Section --</option>
                                                            </select>
                                                            <small class="form-text text-muted">You can select multiple sections</small>
                                                        </div>
                                                    </div>
                                                    <div class="row">
                                                        <div class="col-md-12">
                                                            <button type="submit" id="loadStudents" class="btn btn-primary">
                                                                <i class="fa fa-search"></i> Load Students
                                                            </button>
                                                            <button type="button" id="autoGenerate" class="btn btn-info" disabled>
                                                                <i class="fa fa-magic"></i> Auto Generate Symbols
                                                            </button>
                                                            <button type="button" id="clearSelection" class="btn btn-outline-secondary">
                                                                <i class="fa fa-refresh"></i> Clear
                                                            </button>
                                                        </div>
                                                    </div>
                                                </form>
                                            </div>

                                            <!-- Students List -->
                                            <div id="studentsSection" style="display: none;">
                                                <div class="form-section">
                                                    <h6><i class="fa fa-users"></i> Students List</h6>
                                                    <div class="alert alert-info">
                                                        <i class="fa fa-info-circle"></i> 
                                                        <span id="studentCount">0</span> students found. Assign symbol numbers below.
                                                    </div>
                                                    <form id="symbolForm">
                                                        <input type="hidden" id="form_exam_id" name="exam_id">
                                                        <input type="hidden" id="form_class_id" name="class_id">
                                                        <input type="hidden" id="form_section_ids" name="section_ids">
                                                        
                                                        <div id="studentsList" class="student-list">
                                                            <!-- Students will be loaded here -->
                                                        </div>
                                                        
                                                        <div class="action-buttons">
                                                            <button type="submit" id="saveSymbols" class="btn btn-success">
                                                                <i class="fa fa-save"></i> Save Symbol Numbers
                                                            </button>
                                                            <button type="button" id="downloadCSV" class="btn btn-warning">
                                                                <i class="fa fa-download"></i> Download CSV Template
                                                            </button>
                                                            <button type="button" id="resetSymbols" class="btn btn-outline-danger">
                                                                <i class="fa fa-times"></i> Reset All
                                                            </button>
                                                        </div>
                                                    </form>
                                                </div>
                                            </div>

                                            <!-- CSV Upload Section -->
                                            <div class="form-section">
                                                <h6><i class="fa fa-upload"></i> CSV Upload</h6>
                                                <div class="row">
                                                    <div class="col-md-6">
                                                        <div class="form-group">
                                                            <label for="csvUpload"><i class="fa fa-file-excel-o"></i> Upload CSV File</label>
                                                            <input type="file" id="csvUpload" class="form-control" accept=".csv">
                                                            <small class="form-text text-muted">CSV format: student_id,symbol_no</small>
                                                        </div>
                                                    </div>
                                                    <div class="col-md-6">
                                                        <div class="form-group">
                                                            <label>&nbsp;</label>
                                                            <button id="uploadCSV" class="btn btn-info btn-block">
                                                                <i class="fa fa-upload"></i> Upload & Update Symbols
                                                            </button>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </section>
                </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/select2/select2.min.js"></script>
    <script src="js/main.js"></script>

    <script>
    $(document).ready(function () {
        // Initialize Select2 for sections
        $('.select2').select2({
            placeholder: "Select sections",
            allowClear: true
        });

        // Load sections when class is selected
        $('#class_id').change(function () {
            var classId = $(this).val();
            $('#section_id').prop('disabled', !classId);
            
            if (classId) {
                $('#section_id').html('<option value="">Loading sections...</option>');
                $('#section_id').select2();
                
                $.ajax({
                    type: 'GET',
                    url: 'ajax/get_sections_by_class.php',
                    data: { class_id: classId },
                    dataType: 'json',
                    success: function (sections) {
                        var options = '<option value="">-- Select Section --</option>';
                        if (sections && sections.length > 0) {
                            sections.forEach(function (section) {
                                options += '<option value="' + section.section_id + '">' + section.section_name + '</option>';
                            });
                        }
                        $('#section_id').html(options).select2();
                        $('#autoGenerate').prop('disabled', true);
                    },
                    error: function () {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: 'Failed to load sections.',
                        });
                    }
                });
            } else {
                $('#section_id').prop('disabled', true).html('<option value="">-- Select Section --</option>');
                $('#section_id').select2();
                $('#autoGenerate').prop('disabled', true);
            }
        });

        // Enable auto generate button when sections are selected
        $('#section_id').change(function () {
            var hasSections = $(this).val() && $(this).val().length > 0;
            $('#autoGenerate').prop('disabled', !hasSections);
        });

        // Load students when form is submitted
        $('#selectionForm').submit(function (e) {
            e.preventDefault();
            
            var examId = $('#exam_type').val();
            var classId = $('#class_id').val();
            var sectionIds = $('#section_id').val();
            
            if (!examId || !classId || !sectionIds || sectionIds.length === 0) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Missing Information',
                    text: 'Please select exam, class, and at least one section.',
                });
                return;
            }
            
            loadStudents(examId, classId, sectionIds);
        });

        // Auto generate symbol numbers
        $('#autoGenerate').click(function () {
            var examId = $('#exam_type').val();
            var classId = $('#class_id').val();
            var sectionIds = $('#section_id').val();
            
            if (!examId || !classId || !sectionIds || sectionIds.length === 0) {
                return;
            }
            
            autoGenerateSymbols(examId, classId, sectionIds);
        });

        // Clear selection
        $('#clearSelection').click(function () {
            $('#selectionForm')[0].reset();
            $('#section_id').prop('disabled', true).html('<option value="">-- Select Section --</option>');
            $('#section_id').select2();
            $('#autoGenerate').prop('disabled', true);
            $('#studentsSection').hide();
            $('#studentsList').html('');
        });

        // Save symbol numbers
        $('#symbolForm').submit(function (e) {
            e.preventDefault();
            
            var symbolData = [];
            $('.symbol-input').each(function () {
                var studentId = $(this).data('student-id');
                var symbolNo = $(this).val().trim();
                
                if (symbolNo) {
                    symbolData.push({
                        student_id: studentId,
                        symbol_no: symbolNo
                    });
                }
            });
            
            if (symbolData.length === 0) {
                Swal.fire({
                    icon: 'warning',
                    title: 'No Symbols Entered',
                    text: 'Please enter at least one symbol number.',
                });
                return;
            }
            
            var formData = {
                exam_id: $('#form_exam_id').val(),
                class_id: $('#form_class_id').val(),
                section_ids: $('#form_section_ids').val(),
                symbols: symbolData
            };
            
            Swal.fire({
                title: 'Saving Symbol Numbers',
                text: 'Please wait...',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            $.ajax({
                type: 'POST',
                url: 'ajax/save_symbol_numbers.php',
                data: JSON.stringify(formData),
                contentType: 'application/json',
                dataType: 'json',
                success: function (response) {
                    Swal.close();
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success',
                            text: response.message,
                        }).then(() => {
                            // Reload students to show updated symbols
                            loadStudents(formData.exam_id, formData.class_id, formData.section_ids.split(','));
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: response.error,
                        });
                    }
                },
                error: function () {
                    Swal.close();
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to save symbol numbers.',
                    });
                }
            });
        });

        // Download CSV template
        $('#downloadCSV').click(function () {
            var examId = $('#form_exam_id').val();
            var classId = $('#form_class_id').val();
            var sectionIds = $('#form_section_ids').val();
            
            if (!examId || !classId || !sectionIds) {
                Swal.fire({
                    icon: 'warning',
                    title: 'Warning',
                    text: 'Please load students first.',
                });
                return;
            }
            
            window.location.href = 'ajax/export_symbol_template.php?exam_id=' + examId + 
                                  '&class_id=' + classId + '&section_ids=' + sectionIds;
        });

        // Reset all symbols
        $('#resetSymbols').click(function () {
            Swal.fire({
                title: 'Reset All Symbols?',
                text: 'This will clear all symbol numbers for the loaded students.',
                icon: 'warning',
                showCancelButton: true,
                confirmButtonColor: '#d33',
                cancelButtonColor: '#3085d6',
                confirmButtonText: 'Yes, reset',
                cancelButtonText: 'Cancel'
            }).then((result) => {
                if (result.isConfirmed) {
                    $('.symbol-input').val('');
                    $('.symbol-badge').removeClass('badge-info').addClass('badge-warning').text('Pending');
                }
            });
        });

        // Upload CSV
        $('#uploadCSV').click(function () {
            var file = $('#csvUpload')[0].files[0];
            
            if (!file) {
                Swal.fire({
                    icon: 'warning',
                    title: 'No File Selected',
                    text: 'Please select a CSV file to upload.',
                });
                return;
            }
            
            var formData = new FormData();
            formData.append('csv_file', file);
            
            Swal.fire({
                title: 'Uploading CSV',
                text: 'Please wait...',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            $.ajax({
                url: 'ajax/upload_symbol_csv.php',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                dataType: 'json',
                success: function (response) {
                    Swal.close();
                    if (response.success) {
                        Swal.fire({
                            icon: 'success',
                            title: 'Success',
                            html: response.message + '<br><br>' + 
                                  'Updated: ' + response.updated + ' records<br>' +
                                  'Failed: ' + response.failed + ' records',
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: response.error,
                        });
                    }
                },
                error: function () {
                    Swal.close();
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to upload CSV file.',
                    });
                }
            });
        });

        // Function to load students
        function loadStudents(examId, classId, sectionIds) {
            Swal.fire({
                title: 'Loading Students',
                text: 'Please wait...',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            $.ajax({
                type: 'POST',
                url: 'ajax/get_students_for_symbols.php',
                data: {
                    exam_id: examId,
                    class_id: classId,
                    section_ids: sectionIds
                },
                dataType: 'html',
                success: function (response) {
                    Swal.close();
                    $('#form_exam_id').val(examId);
                    $('#form_class_id').val(classId);
                    $('#form_section_ids').val(sectionIds.join(','));
                    $('#studentsList').html(response);
                    
                    // Update student count
                    var studentCount = $('.student-item').length;
                    $('#studentCount').text(studentCount);
                    
                    $('#studentsSection').show();
                    
                    // Scroll to students section
                    $('html, body').animate({
                        scrollTop: $('#studentsSection').offset().top - 100
                    }, 500);
                },
                error: function () {
                    Swal.close();
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to load students.',
                    });
                }
            });
        }

        // Function to auto generate symbols
        function autoGenerateSymbols(examId, classId, sectionIds) {
            Swal.fire({
                title: 'Auto Generating Symbols',
                text: 'Please wait...',
                allowOutsideClick: false,
                didOpen: () => {
                    Swal.showLoading();
                }
            });
            
            $.ajax({
                type: 'POST',
                url: 'ajax/auto_generate_symbols.php',
                data: {
                    exam_id: examId,
                    class_id: classId,
                    section_ids: sectionIds
                },
                dataType: 'json',
                success: function (response) {
                    Swal.close();
                    if (response.success) {
                        // Update the symbols in the form
                        response.symbols.forEach(function (item) {
                            var input = $('.symbol-input[data-student-id="' + item.student_id + '"]');
                            input.val(item.symbol_no);
                            
                            // Update badge
                            var badge = input.closest('.student-item').find('.symbol-badge');
                            badge.removeClass('badge-warning').addClass('badge-info').text('Auto Generated');
                        });
                        
                        Swal.fire({
                            icon: 'success',
                            title: 'Auto Generation Complete',
                            text: response.message,
                        });
                    } else {
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: response.error,
                        });
                    }
                },
                error: function () {
                    Swal.close();
                    Swal.fire({
                        icon: 'error',
                        title: 'Error',
                        text: 'Failed to auto generate symbols.',
                    });
                }
            });
        }

        // Add real-time validation for symbol numbers
        $(document).on('input', '.symbol-input', function () {
            var value = $(this).val().trim();
            var badge = $(this).closest('.student-item').find('.symbol-badge');
            
            if (value) {
                badge.removeClass('badge-warning').addClass('badge-info').text('Assigned');
            } else {
                badge.removeClass('badge-info').addClass('badge-warning').text('Pending');
            }
        });
    });
    </script>
</body>
</html>