<?php
session_start();
if(isset($_SESSION['username'])){
    ?>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <?php include 'includes/styles.php'; ?>
        <title>Manage Timetable | <?php echo $school_name; ?></title>

        <?php
        require_once 'Classes/Timetable.php';
        $timetable = new Timetable();

        $module_name = 'Timetable';
        include "check-admin-privilege.php";

        ?>
        <style>
            .timetable-grid {
                background: white;
                border-radius: 8px;
                padding: 20px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
                overflow-x: auto;
            }
            .timetable-table {
                width: 100%;
                border-collapse: separate;
                border-spacing: 0;
                min-width: 800px;
            }
            .timetable-table th {
                background: linear-gradient(135deg, #007bff, #0056b3);
                color: white;
                padding: 12px;
                text-align: center;
                font-weight: 600;
                border: 1px solid #0056b3;
            }
            .timetable-table th:first-child {
                border-radius: 8px 0 0 0;
            }
            .timetable-table th:last-child {
                border-radius: 0 8px 0 0;
            }
            .timetable-table td {
                border: 1px solid #dee2e6;
                padding: 8px;
                min-height: 80px;
                vertical-align: top;
            }
            .period-cell {
                background: #f8f9fa;
                font-weight: 600;
                text-align: center;
                width: 100px;
            }
            .break-cell {
                background: #fff3cd;
                text-align: center;
                font-style: italic;
                color: #856404;
            }
            .class-slot {
                background: #e7f3ff;
                border-left: 4px solid #007bff;
                padding: 8px;
                margin: 2px 0;
                border-radius: 4px;
                cursor: pointer;
                transition: all 0.3s;
                position: relative;
            }
            .class-slot:hover {
                background: #cfe2ff;
                transform: translateY(-2px);
                box-shadow: 0 4px 8px rgba(0,123,255,0.3);
            }
            .class-slot .subject-name {
                font-weight: 600;
                color: #0056b3;
                font-size: 0.9rem;
            }
            .class-slot .teacher-name {
                font-size: 0.8rem;
                color: #666;
            }
            .class-slot .room-number {
                font-size: 0.75rem;
                color: #999;
            }
            .empty-slot {
                background: #f8f9fa;
                border: 2px dashed #dee2e6;
                padding: 20px;
                text-align: center;
                border-radius: 4px;
                cursor: pointer;
                transition: all 0.3s;
            }
            .empty-slot:hover {
                background: #e9ecef;
                border-color: #007bff;
            }
            .add-icon {
                color: #007bff;
                font-size: 1.5rem;
            }
            .filter-section {
                background: white;
                padding: 20px;
                border-radius: 8px;
                margin-bottom: 20px;
                box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            }
            .action-buttons {
                display: flex;
                gap: 5px;
                margin-top: 8px;
            }
            .action-buttons button {
                padding: 2px 8px;
                font-size: 0.75rem;
            }
            .slot-actions {
                position: absolute;
                top: 5px;
                right: 5px;
                display: none;
            }
            .class-slot:hover .slot-actions {
                display: block;
            }
            .conflict-indicator {
                position: absolute;
                top: 5px;
                left: 5px;
                color: #dc3545;
                font-size: 0.9rem;
            }

            .fa-eye{
                background-color: transparent;
            }
        </style>
    </head>
    <body class="hold-transition sidebar-mini layout-fixed">
    <div class="wrapper">
        <?php include 'includes/notifications.php'; ?>
        <?php include "includes/sidebar.php"; ?>

        <div class="content-wrapper">
            <div class="content-header">
                <div class="container-fluid">
                    <div class="row mb-2">
                        <div class="col-sm-6">
                            <h1 class="m-0">Manage Timetable</h1>
                        </div>
                        <div class="col-sm-6">
                            <ol class="breadcrumb float-sm-right">
                                <li class="breadcrumb-item"><a href="<?php echo $conn->base_url();?>">Home</a></li>
                                <li class="breadcrumb-item active">Timetable </li>
                            </ol>
                        </div>
                    </div>
                </div>
            </div>

            <section class="content">
                <div class="container-fluid">

                    <!-- Filter Section -->
                    <div class="filter-section">
                        <form id="filter-form">
                            <div class="row">
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label>Class <span class="text-danger">*</span></label>
                                        <select name="class_id" id="class_id" class="form-control select2" required>
                                            <option value="">Select Class</option>
                                            <?php
                                            $sql = "SELECT * FROM classes ORDER BY name";
                                            $conn->query($sql);
                                            $classes = $conn->fetchMultiple();
                                            foreach($classes as $class) {
                                                echo "<option value='{$class->id}'>{$class->name}</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-3">
                                    <div class="form-group">
                                        <label>Section <span class="text-danger">*</span></label>
                                        <select name="section_id" id="section_id" class="form-control select2" required>
                                            <option value="">Select Section</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label>Academic Year</label>
                                        <select name="academic_year" id="academic_year" class="form-control select2">
                                            <option value="">Select Year</option>
                                            <?php
                                            $currentYear = date('Y');
                                            for($i = $currentYear - 2; $i <= $currentYear + 2; $i++) {
                                                $selected = ($i == $currentYear) ? 'selected' : '';
                                                echo "<option value='{$i}' {$selected}>{$i}</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label>Term</label>
                                        <select name="term" id="term" class="form-control select2">
                                            <option value="">Select Term</option>
                                            <option value="1st Term">1st Term</option>
                                            <option value="2nd Term">2nd Term</option>
                                            <option value="3rd Term">3rd Term</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-2">
                                    <div class="form-group">
                                        <label>&nbsp;</label>
                                        <button type="submit" class="btn btn-primary btn-block">
                                            <i class="fas fa-search"></i> Load Timetable
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </form>

                        <div class="row mt-2">
                            <div class="col-md-12">
                                <button class="btn btn-success btn-sm" id="add-entry-btn">
                                    <i class="fas fa-plus"></i> Add Entry
                                </button>
                                <a class="btn btn-info btn-sm" href="<?php echo $conn->base_url().'bulk-add-timetable'; ?>">
                                    <i class="fas fa-layer-group"></i> Bulk Add
                                </a>
                                <button class="btn btn-warning btn-sm" id="load-template-btn">
                                    <i class="fas fa-copy"></i> Load Template
                                </button>
                                <a class="btn btn-secondary btn-sm" href="<?php echo $conn->base_url().'view-timetable-conflicts'; ?>">
                                    <i class="fas fa-exclamation-triangle"></i> Check Conflicts
                                </a>
                                <button class="btn btn-primary btn-sm" id="print-timetable-btn">
                                    <i class="fas fa-print"></i> Print
                                </button>
                                <button class="btn btn-danger btn-sm" id="clear-timetable-btn">
                                    <i class="fas fa-trash"></i> Clear All
                                </button>

                                <button class="btn btn-success" id="export-excel-btn">
                                    <i class="fas fa-file-excel"></i> Export Excel
                                </button>
                                <button class="btn btn-danger" id="export-pdf-btn">
                                    <i class="fas fa-file-pdf"></i> Export PDF
                                </button>
                            </div>
                        </div>
                    </div>

                    <!-- Timetable Display -->
                    <div id="timetable-container" style="display:none;">
                        <div class="timetable-grid">
                            <div class="d-flex justify-content-between align-items-center mb-3">
                                <h4 id="timetable-title">Class Timetable</h4>
                                <span class="badge badge-info" id="entry-count">0 entries</span>
                            </div>
                            <table class="timetable-table" id="timetable-table">
                                <thead>
                                <tr>
                                    <th>Period / Day</th>
                                    <!-- Days will be populated here -->
                                </tr>
                                </thead>
                                <tbody>
                                <!-- Timetable content will be loaded here -->
                                </tbody>
                            </table>
                        </div>
                    </div>

                    <!-- Empty State -->
                    <div id="empty-state" class="text-center" style="padding: 100px 0;">
                        <i class="fas fa-calendar-week" style="font-size: 5rem; color: #dee2e6;"></i>
                        <h4 class="mt-3 text-muted">Select Class and Section to View Timetable</h4>
                        <p class="text-muted">Use the filters above to load the timetable</p>
                    </div>

                </div>
            </section>

        </div>

        <?php include "includes/footer.php"; ?>

        <!-- Add/Edit Entry Modal -->
        <div class="modal fade" id="entryModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header bg-primary text-white">
                        <h5 class="modal-title" id="entryModalTitle">Add Timetable Entry</h5>
                        <button type="button" class="close text-white" data-dismiss="modal">
                            <span>&times;</span>
                        </button>
                    </div>
                    <form id="entry-form">
                        <input type="hidden" id="entry-id" name="entry_id">
                        <input type="hidden" id="entry-class-id" name="class_id">
                        <input type="hidden" id="entry-section-id" name="section_id">
                        <input type="hidden" id="entry-academic-year" name="academic_year">
                        <input type="hidden" id="entry-term" name="term">

                        <div class="modal-body">
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Day <span class="text-danger">*</span></label>
                                        <select name="day_id" id="day_id" class="form-control select2" required data-placeholder="Select Day">
                                            <option value="">Select Day</option>
                                            <?php
                                            $days = $timetable->getActiveDays();
                                            foreach($days as $day) {
                                                echo "<option value='{$day->id}'>{$day->day_name}</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Period <span class="text-danger">*</span></label>
                                        <select name="period_id" id="period_id" class="form-control select2" required data-placeholder="Select Period">
                                            <option value="">Select Period</option>
                                            <?php
                                            $periods = $timetable->getAllPeriods();
                                            foreach($periods as $period) {
                                                if($period->is_break == 0) {
                                                    echo "<option value='{$period->id}'>{$period->period_name} ({$period->start_time} - {$period->end_time})</option>";
                                                }
                                            }
                                            ?>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Subject <span class="text-danger">*</span></label>
                                        <select name="subject_id" id="subject_id" class="form-control select2" required data-placeholder="Select Subject">
                                            <option value="">Select Subject</option>
                                        </select>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Teacher <span class="text-danger">*</span></label>
                                        <select name="teacher_id" id="teacher_id" class="form-control select2" required data-placeholder="Select Teacher">
                                            <option value="">Select Teacher</option>
                                            <?php
                                            $sql = "SELECT id, name FROM teachers ORDER BY name";
                                            $conn->query($sql);
                                            $teachers = $conn->fetchMultiple();
                                            foreach($teachers as $teacher) {
                                                echo "<option value='{$teacher->id}'>{$teacher->name}</option>";
                                            }
                                            ?>
                                        </select>
                                    </div>
                                </div>
                            </div>

                            <div class="row">
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Room Number</label>
                                        <input type="text" class="form-control" name="room_number" id="room_number" placeholder="e.g., Room 101">
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="form-group">
                                        <label>Notes</label>
                                        <input type="text" class="form-control" name="notes" id="notes" placeholder="Optional notes">
                                    </div>
                                </div>
                            </div>

                            <div id="conflict-alert" class="alert alert-warning" style="display:none;">
                                <i class="fas fa-exclamation-triangle"></i>
                                <strong>Conflict Detected:</strong>
                                <ul id="conflict-list"></ul>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                            <button type="submit" class="btn btn-primary" id="save-entry-btn">
                                <i class="fas fa-save"></i> Save Entry
                            </button>
                        </div>
                    </form>
                </div>
            </div>
        </div>

        <script>
            let currentFilters = {};
            $('.select2').select2();

            $(document).ready(function() {
                // Load sections when class is selected
                $('#class_id').on('change', function() {
                    const classID = $(this).val();
                    if(classID) {
                        $.ajax({
                            url: 'fetch_section.php',
                            type: 'POST',
                            data: {classesID: classID},
                            success: function(html) {
                                $('#section_id').html(html);
                            }
                        });

                        // Load subjects for this class
                        loadSubjectsForClass(classID);
                    }
                });

                // Filter form submission
                $('#filter-form').on('submit', function(e) {
                    e.preventDefault();

                    const classId = $('#class_id').val();
                    const sectionId = $('#section_id').val();

                    if(!classId || !sectionId) {
                        alert('Please select both class and section');
                        return;
                    }

                    currentFilters = {
                        class_id: classId,
                        section_id: sectionId,
                        academic_year: $('#academic_year').val(),
                        term: $('#term').val()
                    };

                    loadTimetable();
                });

                // Add entry button
                $('#add-entry-btn').on('click', function() {
                    if(!currentFilters.class_id) {
                        alert('Please load a timetable first');
                        return;
                    }
                    openEntryModal();
                });

                // Entry form submission
                $('#entry-form').on('submit', function(e) {
                    e.preventDefault();
                    saveTimetableEntry();
                });

                // Print timetable
                $('#print-timetable-btn').on('click', function() {
                    if(!currentFilters.class_id) {
                        alert('Please load a timetable first');
                        return;
                    }
                    window.open('print-timetable.php?' + $.param(currentFilters), '_blank');
                });

                // Export to Excel
                $('#export-excel-btn').on('click', function() {
                    if(!currentFilters.class_id) {
                        alert('Please load a timetable first');
                        return;
                    }

                    // Merge current filters with the required backend tags
                    const exportParams = {
                        ...currentFilters,
                        type: 'class',
                        format: 'excel'
                    };

                    // Construct URL and open
                    window.open('export-timetable.php?' + $.param(exportParams), '_blank');
                });

                // Export to PDF
                $('#export-pdf-btn').on('click', function() {
                    if(!currentFilters.class_id) {
                        alert('Please load a timetable first');
                        return;
                    }

                    // Merge current filters with the required backend tags
                    const exportParams = {
                        ...currentFilters,
                        type: 'class',
                        format: 'pdf'
                    };

                    // Construct URL and open
                    window.open('export-timetable.php?' + $.param(exportParams), '_blank');
                });

                // Clear timetable
                $('#clear-timetable-btn').on('click', function() {
                    if(!currentFilters.class_id) {
                        alert('Please load a timetable first');
                        return;
                    }

                    if(confirm('Are you sure you want to delete all timetable entries for this class? This action cannot be undone.')) {
                        clearTimetable();
                    }
                });

                // Load Template button handler
                $('#load-template-btn').on('click', function() {
                    if(!currentFilters.class_id) {
                        alert('Please load a timetable first (select class and section)');
                        return;
                    }
                    showTemplateSelectionModal();
                });

                function showTemplateSelectionModal() {
                    // Fetch available templates for this class
                    $.ajax({
                        url: 'get-available-templates.php',
                        type: 'POST',
                        data: {
                            class_id: currentFilters.class_id,
                            section_id: currentFilters.section_id
                        },
                        dataType: 'json',
                        success: function(response) {
                            if(response.success) {
                                displayTemplateModal(response.templates);
                            } else {
                                alert('No templates found for this class');
                            }
                        },
                        error: function() {
                            alert('Error loading templates');
                        }
                    });
                }

                function displayTemplateModal(templates) {
                    let modalHtml = `
        <div class="modal fade" id="loadTemplateModal" tabindex="-1">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header bg-warning text-white">
                        <h5 class="modal-title"><i class="fas fa-copy"></i> Load Template</h5>
                        <button type="button" class="close text-white" data-dismiss="modal">
                            <span>&times;</span>
                        </button>
                    </div>
                    <div class="modal-body">
                        <div class="alert alert-info">
                            <i class="fas fa-info-circle"></i> Select a template to load into the current timetable.
                            You can choose to merge with existing entries or replace them.
                        </div>
    `;

                    if(templates.length > 0) {
                        modalHtml += '<div class="row">';
                        templates.forEach(template => {
                            modalHtml += `
                <div class="col-md-6 mb-3">
                    <div class="card template-select-card" style="cursor: pointer; border: 2px solid #dee2e6;" onclick="selectTemplate(${template.id})">
                        <div class="card-body">
                            <h5 class="card-title">${template.template_name}</h5>
                            <p class="card-text text-muted">${template.description || 'No description'}</p>
                            <div class="d-flex justify-content-between">
                                <small><i class="fas fa-calendar"></i> ${template.entry_count} entries</small>
                                <small><i class="fas fa-clock"></i> ${template.created_date}</small>
                            </div>
                        </div>
                    </div>
                </div>
            `;
                        });
                        modalHtml += '</div>';
                    } else {
                        modalHtml += `
            <div class="alert alert-warning text-center">
                <i class="fas fa-exclamation-triangle"></i> No templates available for this class.
                <br><br>
                <a href="manage-templates.php" class="btn btn-primary btn-sm">
                    <i class="fas fa-plus"></i> Create Template
                </a>
            </div>
        `;
                    }

                    modalHtml += `
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    </div>
                </div>
            </div>
        </div>
    `;

                    // Remove existing modal if any
                    $('#loadTemplateModal').remove();

                    // Add modal to body
                    $('body').append(modalHtml);

                    // Show modal
                    $('#loadTemplateModal').modal('show');
                }





                //CSS for template cards
                $('<style>')
                    .prop('type', 'text/css')
                    .html(`
                        .template-select-card:hover {
                            border-color: #f39c12 !important;
                            box-shadow: 0 4px 8px rgba(243, 156, 18, 0.3);
                            transform: translateY(-2px);
                            transition: all 0.3s;
                        }
                    `)
                    .appendTo('head');
            });

            function selectTemplate(templateId) {
                // Close selection modal
                $('#loadTemplateModal').modal('hide');

                // Show confirmation modal with options
                Swal.fire({
                    title: 'Load Template',
                    html: `
            <p>How would you like to load this template?</p>
            <div class="form-check text-left mb-2">
                <input class="form-check-input" type="radio" name="loadOption" id="mergeOption" value="merge" checked>
                <label class="form-check-label" for="mergeOption">
                    <strong>Merge with existing</strong><br>
                    <small>Add template entries to current timetable (skip duplicates)</small>
                </label>
            </div>
            <div class="form-check text-left">
                <input class="form-check-input" type="radio" name="loadOption" id="replaceOption" value="replace">
                <label class="form-check-label" for="replaceOption">
                    <strong>Replace existing</strong><br>
                    <small>Clear current timetable and load template</small>
                </label>
            </div>
        `,
                    icon: 'question',
                    showCancelButton: true,
                    confirmButtonText: 'Load Template',
                    cancelButtonText: 'Cancel',
                    confirmButtonColor: '#f39c12',
                    preConfirm: () => {
                        return document.querySelector('input[name="loadOption"]:checked').value;
                    }
                }).then((result) => {
                    if (result.isConfirmed) {
                        loadTemplateData(templateId, result.value);
                    }
                });
            }

            function loadTemplateData(templateId, loadOption) {
                // Show loading
                Swal.fire({
                    title: 'Loading Template...',
                    html: 'Please wait while we load the template',
                    allowOutsideClick: false,
                    didOpen: () => {
                        Swal.showLoading();
                    }
                });

                $.ajax({
                    url: 'load-template-to-timetable.php',
                    type: 'POST',
                    data: {
                        template_id: templateId,
                        class_id: currentFilters.class_id,
                        section_id: currentFilters.section_id,
                        academic_year: currentFilters.academic_year,
                        term: currentFilters.term,
                        load_option: loadOption,
                        created_by: '<?php echo $_SESSION['username']; ?>'
                    },
                    dataType: 'json',
                    success: function(response) {
                        Swal.close();

                        if(response.success) {
                            Swal.fire({
                                icon: 'success',
                                title: 'Template Loaded!',
                                html: `
                        <p><strong>${response.created}</strong> entries added successfully</p>
                        ${response.skipped > 0 ? `<p class="text-warning">${response.skipped} entries skipped (duplicates or conflicts)</p>` : ''}
                    `,
                                confirmButtonText: 'OK'
                            }).then(() => {
                                // Reload timetable
                                loadTimetable();
                            });
                        } else {
                            Swal.fire({
                                icon: 'error',
                                title: 'Error',
                                text: response.message || 'Failed to load template'
                            });
                        }
                    },
                    error: function() {
                        Swal.close();
                        Swal.fire({
                            icon: 'error',
                            title: 'Error',
                            text: 'Failed to connect to server'
                        });
                    }
                });
            }

            // Initialize Select2 for modal dropdowns
            $('#day_id, #period_id, #subject_id, #teacher_id').select2({
                dropdownParent: $('#entryModal'),
                placeholder: function() {
                    return $(this).data('placeholder');
                },
                allowClear: true
            });

            function loadTimetable() {
                $.ajax({
                    url: 'get-timetable-data.php',
                    type: 'POST',
                    data: currentFilters,
                    dataType: 'json',
                    success: function(response) {
                        if(response.success) {
                            renderTimetable(response.data, response.days, response.periods);
                            $('#empty-state').hide();
                            $('#timetable-container').show();
                        } else {
                            alert('Error loading timetable');
                        }
                    },
                    error: function() {
                        alert('Error connecting to server');
                    }
                });
            }

            function renderTimetable(data, days, periods) {
                // Update title
                $('#timetable-title').text(data.class_name + ' - ' + data.section_name + ' Timetable');
                $('#entry-count').text(data.entries.length + ' entries');

                // Build table header
                let headerHtml = '<tr><th>Period / Day</th>';
                days.forEach(day => {
                    headerHtml += `<th>${day.day_name}</th>`;
                });
                headerHtml += '</tr>';
                $('#timetable-table thead').html(headerHtml);

                // Build table body
                let bodyHtml = '';
                periods.forEach(period => {
                    if(period.is_break == 1) {
                        bodyHtml += `<tr>
                <td class="period-cell break-cell" colspan="${days.length + 1}">
                    ${period.period_name} (${period.start_time} - ${period.end_time})
                </td>
            </tr>`;
                    } else {
                        bodyHtml += `<tr>
                <td class="period-cell">
                    <strong>${period.period_name}</strong><br>
                    <small>${period.start_time} - ${period.end_time}</small>
                </td>`;

                        days.forEach(day => {
                            const entry = data.entries.find(e => e.day_id == day.id && e.period_id == period.id);

                            if(entry) {
                                bodyHtml += `<td>
                        <div class="class-slot" data-id="${entry.id}">
                            <div class="slot-actions">
                                <button class="btn btn-xs btn-primary edit-slot" data-id="${entry.id}" title="Edit">
                                    <i class="fas fa-edit"></i>
                                </button>
                                <button class="btn btn-xs btn-danger delete-slot" data-id="${entry.id}" title="Delete">
                                    <i class="fas fa-trash"></i>
                                </button>
                            </div>
                            <div class="subject-name">${entry.subject_name}</div>
                            <div class="teacher-name"><i class="fas fa-user"></i> ${entry.teacher_name}</div>
                            ${entry.room_number ? `<div class="room-number"><i class="fas fa-door-open"></i> ${entry.room_number}</div>` : ''}
                        </div>
                    </td>`;
                            } else {
                                bodyHtml += `<td>
                        <div class="empty-slot" data-day="${day.id}" data-period="${period.id}">
                            <i class="fas fa-plus add-icon"></i>
                        </div>
                    </td>`;
                            }
                        });

                        bodyHtml += '</tr>';
                    }
                });

                $('#timetable-table tbody').html(bodyHtml);

                // Attach event handlers
                $('.empty-slot').on('click', function() {
                    const dayId = $(this).data('day');
                    const periodId = $(this).data('period');
                    openEntryModal(null, dayId, periodId);
                });

                $('.edit-slot').on('click', function(e) {
                    e.stopPropagation();
                    const entryId = $(this).data('id');
                    editEntry(entryId);
                });

                $('.delete-slot').on('click', function(e) {
                    e.stopPropagation();
                    const entryId = $(this).data('id');
                    deleteEntry(entryId);
                });
            }

            function openEntryModal(entryId = null, dayId = null, periodId = null) {
                // Reset the form
                $('#entry-form')[0].reset();

                // Clear all hidden fields
                $('#entry-id').val('');
                $('#entry-class-id').val(currentFilters.class_id);
                $('#entry-section-id').val(currentFilters.section_id);
                $('#entry-academic-year').val(currentFilters.academic_year);
                $('#entry-term').val(currentFilters.term);

                // Reset all select dropdowns to default
                $('#day_id').val('').trigger('change');
                $('#period_id').val('').trigger('change');
                $('#subject_id').val('').trigger('change');
                $('#teacher_id').val('').trigger('change');

                // Reset text inputs
                $('#room_number').val('');
                $('#notes').val('');

                // Set values only if provided (for specific day/period clicks)
                if(dayId) {
                    $('#day_id').val(dayId).trigger('change');
                }
                if(periodId) {
                    $('#period_id').val(periodId).trigger('change');
                }

                // Set entry ID only for edit mode
                if(entryId) {
                    $('#entry-id').val(entryId);
                }

                $('#entryModalTitle').text(entryId ? 'Edit Timetable Entry' : 'Add Timetable Entry');
                $('#conflict-alert').hide();
                $('#entryModal').modal('show');
            }

            // Reset modal when closed
            $('#entryModal').on('hidden.bs.modal', function () {
                $('#entry-form')[0].reset();
                $('#day_id').val('').trigger('change');
                $('#period_id').val('').trigger('change');
                $('#subject_id').val('').trigger('change');
                $('#teacher_id').val('').trigger('change');
                $('#conflict-alert').hide();
            });

            function loadSubjectsForClass(classId) {
                $.ajax({
                    url: 'get-class-subjects.php',
                    type: 'POST',
                    data: {class_id: classId},
                    success: function(html) {
                        $('#subject_id').html(html);
                    }
                });
            }

            function saveTimetableEntry() {
                const formData = $('#entry-form').serialize();
                const url = $('#entry-id').val() ? 'update-timetable-entry.php' : 'create-timetable-entry.php';

                $('#save-entry-btn').prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i> Saving...');

                $.ajax({
                    url: url,
                    type: 'POST',
                    data: formData,
                    dataType: 'json',
                    success: function(response) {
                        if(response.success) {
                            $('#entryModal').modal('hide');
                            loadTimetable();
                            alert('Timetable entry saved successfully');
                        } else if(response.conflicts) {
                            displayConflicts(response.conflicts);
                        } else {
                            alert('Error: ' + response.message);
                        }
                    },
                    error: function() {
                        alert('Error saving entry');
                    },
                    complete: function() {
                        $('#save-entry-btn').prop('disabled', false).html('<i class="fas fa-save"></i> Save Entry');
                    }
                });
            }

            function displayConflicts(conflicts) {
                let html = '';
                conflicts.forEach(conflict => {
                    html += `<li>${conflict.message}</li>`;
                });
                $('#conflict-list').html(html);
                $('#conflict-alert').slideDown();
            }

            function editEntry(entryId) {
                $.ajax({
                    url: 'get-timetable-data.php',
                    type: 'POST',
                    data: currentFilters,
                    dataType: 'json',
                    success: function(response) {
                        if(response.success) {
                            const entry = response.data.entries.find(e => e.id == entryId);
                            if(entry) {
                                // Populate the modal form with entry data
                                $('#entry-id').val(entry.id);
                                $('#day_id').val(entry.day_id).trigger('change');
                                $('#period_id').val(entry.period_id).trigger('change');
                                $('#subject_id').val(entry.subject_id).trigger('change');
                                $('#teacher_id').val(entry.teacher_id).trigger('change');
                                $('#room_number').val(entry.room_number);
                                $('#notes').val(entry.notes);

                                // Set hidden fields
                                $('#entry-class-id').val(currentFilters.class_id);
                                $('#entry-section-id').val(currentFilters.section_id);
                                $('#entry-academic-year').val(currentFilters.academic_year);
                                $('#entry-term').val(currentFilters.term);

                                $('#entryModalTitle').text('Edit Timetable Entry');
                                $('#conflict-alert').hide();
                                $('#entryModal').modal('show');
                            }
                        } else {
                            alert('Error loading entry data');
                        }
                    },
                    error: function() {
                        alert('Error connecting to server');
                    }
                });
            }

            function deleteEntry(entryId) {
                if(confirm('Are you sure you want to delete this entry?')) {
                    $.ajax({
                        url: 'delete-timetable-entry.php',
                        type: 'POST',
                        data: {entry_id: entryId},
                        dataType: 'json',
                        success: function(response) {
                            if(response.success) {
                                loadTimetable();
                            } else {
                                alert('Error deleting entry');
                            }
                        }
                    });
                }
            }

            function clearTimetable() {
                $.ajax({
                    url: 'clear-timetable.php',
                    type: 'POST',
                    data: currentFilters,
                    dataType: 'json',
                    success: function(response) {
                        if(response.success) {
                            loadTimetable();
                            alert('Timetable cleared successfully');
                        } else {
                            alert('Error clearing timetable');
                        }
                    }
                });
            }
        </script>

    </body>
    </html>
    <?php
} else {
    ?>
    <!DOCTYPEhtml>
    <html lang="en">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>Login to continue | <?php echo $school_name; ?></title>
        <?php include 'includes/styles.php'; ?>
    </head>
    <body>
    <div class="container" style="margin-top: 20%;">
        <div class="row">
            <div class="col-lg-12 col-md-12">
                <div class="section-title text-center">
                    <h6>You need to login to continue</h6>
                    <div class="spinner-border text-info" role="status">
                        <span class="sr-only">Loading...</span>
                        <meta http-equiv='refresh' content='3; <?php echo $link; ?>'>
                    </div>
                    <p>Redirecting to the login page...</p>
                </div>
            </div>
        </div>
    </div>
    </body>
    </html>
    <?php
}
?>