<?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'; ?>

    <?php
    require_once 'Classes/Timetable.php';
    $timetable = new Timetable();
    ?>
    <style>
        .bulk-card {
            background: white;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 20px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
        }
        .step-indicator {
            display: flex;
            justify-content: space-between;
            margin-bottom: 30px;
            position: relative;
        }
        .step {
            flex: 1;
            text-align: center;
            position: relative;
        }
        .step-number {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            background: #dee2e6;
            color: #6c757d;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-weight: bold;
            margin-bottom: 10px;
        }
        .step.active .step-number {
            background: #007bff;
            color: white;
        }
        .step.completed .step-number {
            background: #28a745;
            color: white;
        }
        .step-label {
            font-size: 0.9rem;
            color: #6c757d;
        }
        .step.active .step-label {
            color: #007bff;
            font-weight: 600;
        }
        .preview-table {
            max-height: 400px;
            overflow-y: auto;
        }
        .preview-row {
            padding: 10px;
            border: 1px solid #dee2e6;
            margin-bottom: 5px;
            border-radius: 4px;
            background: #f8f9fa;
        }
        .preview-row.valid {
            border-left: 4px solid #28a745;
        }
        .preview-row.invalid {
            border-left: 4px solid #dc3545;
        }
        .error-message {
            color: #dc3545;
            font-size: 0.85rem;
            margin-top: 5px;
        }
        .quick-fill-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 15px;
            margin-top: 20px;
        }
        .quick-fill-card {
            border: 2px dashed #dee2e6;
            border-radius: 8px;
            padding: 15px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s;
        }
        .quick-fill-card:hover {
            border-color: #007bff;
            background: #f0f8ff;
        }
        .progress-section {
            margin-top: 20px;
        }
        .fa-eye{
            background-color: transparent;
        }
    </style>
    <title> Bulk Add Timetable |  <?php echo $school_name; ?> </title>
    <?php
    $module_name = 'Timetable';
    include "check-admin-privilege.php";
    ?>

</head>
<body class="hold-transition sidebar-mini layout-fixed">
<div class="wrapper">

  <!-- Navbar -->
    <?php include 'includes/notifications.php'; ?>
  <!-- /.navbar -->

  <!-- Main Sidebar Container -->
<?php include "includes/sidebar.php";?>

  <!-- Content Wrapper. Contains page content -->
  <div class="content-wrapper">
    <!-- Content Header (Page header) -->
    <div class="content-header">
      <div class="container-fluid">
        <div class="row mb-2">
          <div class="col-sm-6">
            <h1 class="m-0">Bulk Add Timetable</h1>
          </div><!-- /.col -->
          <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"><a href="<?php echo $conn->base_url().'manage-timetable';?>">Timetable</a></li>
                  <li class="breadcrumb-item active">Bulk Add</li>
              </ol>
          </div><!-- /.col -->
        </div><!-- /.row -->
      </div><!-- /.container-fluid -->
    </div>
    <!-- /.content-header -->

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

              <!-- Step Indicator -->
              <div class="step-indicator">
                  <div class="step active" id="step-1">
                      <div class="step-number">1</div>
                      <div class="step-label">Select Class</div>
                  </div>
                  <div class="step" id="step-2">
                      <div class="step-number">2</div>
                      <div class="step-label">Add Entries</div>
                  </div>
                  <div class="step" id="step-3">
                      <div class="step-number">3</div>
                      <div class="step-label">Review & Save</div>
                  </div>
              </div>

              <!-- Step 1: Class Selection -->
              <div class="bulk-card" id="step1-content">
                  <h4><i class="fas fa-graduation-cap"></i> Step 1: Select Class & Details</h4>
                  <hr>
                  <form id="class-selection-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-3">
                              <div class="form-group">
                                  <label>Academic Year <span class="text-danger">*</span></label>
                                  <select name="academic_year" id="academic_year" class="form-control select2" required>
                                      <?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-3">
                              <div class="form-group">
                                  <label>Term <span class="text-danger">*</span></label>
                                  <select name="term" id="term" class="form-control select2" required>
                                      <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>
                      <button type="submit" class="btn btn-primary">
                          <i class="fas fa-arrow-right"></i> Continue to Add Entries
                      </button>
                  </form>
              </div>

              <!-- Step 2: Add Entries -->
              <div class="bulk-card" id="step2-content" style="display:none;">
                  <h4><i class="fas fa-plus-circle"></i> Step 2: Add Timetable Entries</h4>
                  <hr>

                  <!-- Entry Form -->
                  <form id="entry-add-form">
                      <div class="row">
                          <div class="col-md-3">
                              <div class="form-group">
                                  <label>Day <span class="text-danger">*</span></label>
                                  <select name="day_id" id="entry_day_id" class="form-control" required>
                                      <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-3">
                              <div class="form-group">
                                  <label>Period <span class="text-danger">*</span></label>
                                  <select name="period_id" id="entry_period_id" class="form-control" required>
                                      <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 class="col-md-2">
                              <div class="form-group">
                                  <label>Subject <span class="text-danger">*</span></label>
                                  <select name="subject_id" id="entry_subject_id" class="form-control" required>
                                      <option value="">Select Subject</option>
                                  </select>
                              </div>
                          </div>
                          <div class="col-md-2">
                              <div class="form-group">
                                  <label>Teacher <span class="text-danger">*</span></label>
                                  <select name="teacher_id" id="entry_teacher_id" class="form-control" required>
                                      <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 class="col-md-2">
                              <div class="form-group">
                                  <label>Room</label>
                                  <input type="text" class="form-control" name="room_number" id="entry_room_number" placeholder="e.g., 101">
                              </div>
                          </div>
                      </div>
                      <div class="row">
                          <div class="col-md-10">
                              <div class="form-group">
                                  <label>Notes (Optional)</label>
                                  <input type="text" class="form-control" name="notes" id="entry_notes" placeholder="Optional notes">
                              </div>
                          </div>
                          <div class="col-md-2">
                              <div class="form-group">
                                  <label>&nbsp;</label>
                                  <button type="submit" class="btn btn-success btn-block">
                                      <i class="fas fa-plus"></i> Add Entry
                                  </button>
                              </div>
                          </div>
                      </div>
                  </form>

                  <hr>

                  <!-- Quick Fill Options -->
                  <h5><i class="fas fa-magic"></i> Quick Fill Options</h5>
                  <div class="quick-fill-grid">
                      <div class="quick-fill-card" onclick="fillAllPeriodsOneDay()">
                          <i class="fas fa-calendar-day" style="font-size: 2rem; color: #007bff;"></i>
                          <h6 class="mt-2">Fill All Periods for One Day</h6>
                          <small class="text-muted">Same subject & teacher for all periods in a day</small>
                      </div>
                      <div class="quick-fill-card" onclick="fillSamePeriodAllDays()">
                          <i class="fas fa-calendar-week" style="font-size: 2rem; color: #28a745;"></i>
                          <h6 class="mt-2">Fill Same Period All Days</h6>
                          <small class="text-muted">Same time slot across the week</small>
                      </div>
                      <div class="quick-fill-card" onclick="importFromCSV()">
                          <i class="fas fa-file-csv" style="font-size: 2rem; color: #17a2b8;"></i>
                          <h6 class="mt-2">Import from CSV</h6>
                          <small class="text-muted">Upload CSV file with entries</small>
                      </div>
                  </div>

                  <hr>

                  <!-- Added Entries Preview -->
                  <div class="d-flex justify-content-between align-items-center mb-3">
                      <h5><i class="fas fa-list"></i> Added Entries (<span id="entry-count">0</span>)</h5>
                      <div>
                          <button class="btn btn-warning btn-sm" onclick="clearAllEntries()">
                              <i class="fas fa-trash"></i> Clear All
                          </button>
                          <button class="btn btn-primary" onclick="proceedToReview()">
                              <i class="fas fa-arrow-right"></i> Review & Save
                          </button>
                      </div>
                  </div>
                  <div class="preview-table" id="entries-preview">
                      <div class="text-center text-muted py-5">
                          <i class="fas fa-inbox" style="font-size: 3rem;"></i>
                          <p class="mt-3">No entries added yet. Use the form above to add entries.</p>
                      </div>
                  </div>
              </div>

              <!-- Step 3: Review & Save -->
              <div class="bulk-card" id="step3-content" style="display:none;">
                  <h4><i class="fas fa-check-circle"></i> Step 3: Review & Save</h4>
                  <hr>

                  <div class="alert alert-info">
                      <i class="fas fa-info-circle"></i> Review all entries below. Entries with conflicts will be highlighted in red.
                  </div>

                  <div id="review-summary" class="mb-3">
                      <!-- Summary will be populated here -->
                  </div>

                  <div id="review-entries">
                      <!-- Entries will be listed here -->
                  </div>

                  <div class="progress-section" id="progress-section" style="display:none;">
                      <h5>Saving Progress</h5>
                      <div class="progress">
                          <div class="progress-bar progress-bar-striped progress-bar-animated"
                               role="progressbar"
                               id="save-progress"
                               style="width: 0%"></div>
                      </div>
                      <p class="mt-2" id="progress-text">Preparing to save...</p>
                  </div>

                  <div class="mt-3">
                      <button class="btn btn-secondary" onclick="backToAddEntries()">
                          <i class="fas fa-arrow-left"></i> Back to Add Entries
                      </button>
                      <button class="btn btn-success btn-lg" id="save-all-btn" onclick="saveAllEntries()">
                          <i class="fas fa-save"></i> Save All Entries
                      </button>
                  </div>
              </div>

          </div>
      </section>
    <!-- /.content -->
  </div>
  <!-- /.content-wrapper -->
  <?php include "includes/footer.php";?>
    <!-- CSV Import Modal -->

    <div class="modal fade" id="csvImportModal" tabindex="-1">
        <div class="modal-dialog modal-lg">
            <div class="modal-content">
                <div class="modal-header bg-info text-white">
                    <h5 class="modal-title">Import from CSV</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">
                        <strong>CSV Format:</strong> day_id, period_id, subject_id, teacher_id, room_number, notes<br>
                        <small>Example: 1,2,5,3,101,Mathematics class</small>
                        <hr>
                        <strong>Column Details:</strong>
                        <ul class="mb-0">
                            <li>day_id: 1=Monday, 2=Tuesday, 3=Wednesday, 4=Thursday, 5=Friday</li>
                            <li>period_id: Use the period ID from your periods table</li>
                            <li>subject_id: Use the subject ID from your subjects table</li>
                            <li>teacher_id: Use the teacher ID from your teachers table</li>
                            <li>room_number: Optional room number</li>
                            <li>notes: Optional notes</li>
                        </ul>
                    </div>
                    <div class="form-group">
                        <label>Upload CSV File</label>
                        <input type="file" class="form-control-file" id="csv-file" accept=".csv">
                    </div>
                    <div class="form-group">
                        <a href="download-bulk-template" class="btn btn-sm btn-outline-primary">
                            <i class="fas fa-download"></i> Download CSV Template
                        </a>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Cancel</button>
                    <button type="button" class="btn btn-primary" onclick="processCSV()">
                        <i class="fas fa-upload"></i> Import
                    </button>
                </div>
            </div>
        </div>
    </div>

  <?php
  ?>
    <script>
let bulkEntries = [];
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);
                }
            });
            loadSubjectsForClass(classID);
        }
    });

    // Class selection form
    $('#class-selection-form').on('submit', function(e) {
        e.preventDefault();

        if(!$('#class_id').val() || !$('#section_id').val()) {
            alert('Please select both class and section');
            return;
        }

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

        // Move to step 2
        $('#step1-content').hide();
        $('#step2-content').show();
        updateStepIndicator(2);
    });

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

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

function addEntry() {
    const entry = {
        day_id: $('#entry_day_id').val(),
        day_name: $('#entry_day_id option:selected').text(),
        period_id: $('#entry_period_id').val(),
        period_name: $('#entry_period_id option:selected').text(),
        subject_id: $('#entry_subject_id').val(),
        subject_name: $('#entry_subject_id option:selected').text(),
        teacher_id: $('#entry_teacher_id').val(),
        teacher_name: $('#entry_teacher_id option:selected').text(),
        room_number: $('#entry_room_number').val(),
        notes: $('#entry_notes').val()
    };

    // Validate
    if(!entry.day_id || !entry.period_id || !entry.subject_id || !entry.teacher_id) {
        alert('Please fill all required fields');
        return;
    }

    // Check for duplicate
    const duplicate = bulkEntries.find(e =>
        e.day_id == entry.day_id && e.period_id == entry.period_id
    );

    if(duplicate) {
        if(!confirm('An entry already exists for this day and period. Replace it?')) {
            return;
        }
        // Remove duplicate
        bulkEntries = bulkEntries.filter(e =>
            !(e.day_id == entry.day_id && e.period_id == entry.period_id)
        );
    }

    bulkEntries.push(entry);
    updateEntriesPreview();

    // Reset form
    $('#entry-add-form')[0].reset();

    toastr.success('Entry added successfully');
}

function updateEntriesPreview() {
    $('#entry-count').text(bulkEntries.length);

    if(bulkEntries.length === 0) {
        $('#entries-preview').html(`
                    <div class="text-center text-muted py-5">
                        <i class="fas fa-inbox" style="font-size: 3rem;"></i>
                        <p class="mt-3">No entries added yet. Use the form above to add entries.</p>
                    </div>
                `);
        return;
    }

    let html = '';
    bulkEntries.forEach((entry, index) => {
        html += `
                    <div class="preview-row valid">
                        <div class="d-flex justify-content-between align-items-center">
                            <div>
                                <strong>${entry.day_name}</strong> - ${entry.period_name}
                                <br>
                                <small>
                                    <i class="fas fa-book"></i> ${entry.subject_name} |
                                    <i class="fas fa-chalkboard-teacher"></i> ${entry.teacher_name}
                                    ${entry.room_number ? `| <i class="fas fa-door-open"></i> ${entry.room_number}` : ''}
                                </small>
                            </div>
                            <button class="btn btn-sm btn-danger" onclick="removeEntry(${index})">
                                <i class="fas fa-trash"></i>
                            </button>
                        </div>
                    </div>
                `;
    });

    $('#entries-preview').html(html);
}

function removeEntry(index) {
    bulkEntries.splice(index, 1);
    updateEntriesPreview();
}

function clearAllEntries() {
    if(confirm('Are you sure you want to clear all entries?')) {
        bulkEntries = [];
        updateEntriesPreview();
    }
}

function proceedToReview() {
    if(bulkEntries.length === 0) {
        alert('Please add at least one entry');
        return;
    }

    $('#step2-content').hide();
    $('#step3-content').show();
    updateStepIndicator(3);
    generateReview();
}

function backToAddEntries() {
    $('#step3-content').hide();
    $('#step2-content').show();
    updateStepIndicator(2);
}

function updateStepIndicator(currentStep) {
    $('.step').removeClass('active completed');

    for(let i = 1; i <= 3; i++) {
        if(i < currentStep) {
            $(`#step-${i}`).addClass('completed');
        } else if(i === currentStep) {
            $(`#step-${i}`).addClass('active');
        }
    }
}

function generateReview() {
    // Summary
    const summary = `
                <div class="row">
                    <div class="col-md-3">
                        <div class="info-box">
                            <span class="info-box-icon bg-info"><i class="fas fa-list"></i></span>
                            <div class="info-box-content">
                                <span class="info-box-text">Total Entries</span>
                                <span class="info-box-number">${bulkEntries.length}</span>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="info-box">
                            <span class="info-box-icon bg-success"><i class="fas fa-book"></i></span>
                            <div class="info-box-content">
                                <span class="info-box-text">Subjects</span>
                                <span class="info-box-number">${new Set(bulkEntries.map(e => e.subject_id)).size}</span>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="info-box">
                            <span class="info-box-icon bg-warning"><i class="fas fa-chalkboard-teacher"></i></span>
                            <div class="info-box-content">
                                <span class="info-box-text">Teachers</span>
                                <span class="info-box-number">${new Set(bulkEntries.map(e => e.teacher_id)).size}</span>
                            </div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="info-box">
                            <span class="info-box-icon bg-danger"><i class="fas fa-calendar"></i></span>
                            <div class="info-box-content">
                                <span class="info-box-text">Days</span>
                                <span class="info-box-number">${new Set(bulkEntries.map(e => e.day_id)).size}</span>
                            </div>
                        </div>
                    </div>
                </div>
            `;
    $('#review-summary').html(summary);

    // Entries list
    let entriesHtml = '<div class="table-responsive"><table class="table table-bordered table-striped"><thead><tr><th>#</th><th>Day</th><th>Period</th><th>Subject</th><th>Teacher</th><th>Room</th></tr></thead><tbody>';

    bulkEntries.forEach((entry, index) => {
        entriesHtml += `
                    <tr>
                        <td>${index + 1}</td>
                        <td>${entry.day_name}</td>
                        <td>${entry.period_name}</td>
                        <td>${entry.subject_name}</td>
                        <td>${entry.teacher_name}</td>
                        <td>${entry.room_number || '-'}</td>
                    </tr>
                `;
    });

    entriesHtml += '</tbody></table></div>';
    $('#review-entries').html(entriesHtml);
}

function saveAllEntries() {
    $('#save-all-btn').prop('disabled', true);
    $('#progress-section').show();

    let saved = 0;
    let failed = 0;
    const total = bulkEntries.length;

    function saveNext(index) {
        if(index >= total) {
            // All done
            $('#progress-section').hide();

            if(failed === 0) {
                toastr.success(`All ${saved} entries saved successfully!`);
                setTimeout(() => {
                    window.location.href = 'manage-timetable.php';
                }, 2000);
            } else {
                alert(`Saved ${saved} entries. ${failed} entries failed due to conflicts.`);
                $('#save-all-btn').prop('disabled', false);
            }
            return;
        }

        const entry = bulkEntries[index];
        const progress = ((index + 1) / total * 100).toFixed(0);

        $('#save-progress').css('width', progress + '%');
        $('#progress-text').text(`Saving entry ${index + 1} of ${total}...`);

        const data = {
            ...currentFilters,
            ...entry,
            created_by: '<?php echo $_SESSION['username']; ?>'
        };

        $.ajax({
            url: 'create-timetable-entry.php',
            type: 'POST',
            data: data,
            dataType: 'json',
            success: function(response) {
                if(response.success) {
                    saved++;
                } else {
                    failed++;
                }
                saveNext(index + 1);
            },
            error: function() {
                failed++;
                saveNext(index + 1);
            }
        });
    }

    saveNext(0);
}

// Quick fill functions
function fillAllPeriodsOneDay() {
    // Get available periods and days data from PHP
    <?php
    $periods = $timetable->getAllPeriods();
    $periodsData = array_values(array_filter(array_map(function($p) {
        return $p->is_break == 0 ? [
            'id' => $p->id,
            'name' => $p->period_name
        ] : null;
    }, $periods)));
    echo "const periods = " . json_encode($periodsData) . ";";

    $days = $timetable->getActiveDays();
    $daysData = array_map(function($d) {
        return ['id' => $d->id, 'name' => $d->day_name];
    }, $days);
    echo "const days = " . json_encode($daysData) . ";";
    ?>

    // Build day selection
    let dayOptions = '<option value="">Select Day</option>';
    days.forEach(day => {
        dayOptions += `<option value="${day.id}">${day.name}</option>`;
    });

    Swal.fire({
        title: 'Fill All Periods for One Day',
        html: `
            <div class="form-group text-left">
                <label>Select Day:</label>
                <select id="bulk_day" class="form-control">${dayOptions}</select>
            </div>
            <div class="form-group text-left">
                <label>Select Subject:</label>
                <select id="bulk_subject" class="form-control">
                    ${$('#entry_subject_id').html()}
                </select>
            </div>
            <div class="form-group text-left">
                <label>Select Teacher:</label>
                <select id="bulk_teacher" class="form-control">
                    ${$('#entry_teacher_id').html()}
                </select>
            </div>
            <div class="form-group text-left">
                <label>Room Number (Optional):</label>
                <input type="text" id="bulk_room" class="form-control" placeholder="e.g., 101">
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Fill All Periods',
        cancelButtonText: 'Cancel',
        preConfirm: () => {
            const dayId = document.getElementById('bulk_day').value;
            const subjectId = document.getElementById('bulk_subject').value;
            const teacherId = document.getElementById('bulk_teacher').value;
            const room = document.getElementById('bulk_room').value;

            if (!dayId || !subjectId || !teacherId) {
                Swal.showValidationMessage('Please fill all required fields');
                return false;
            }

            return { dayId, subjectId, teacherId, room };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const { dayId, subjectId, teacherId, room } = result.value;

            const dayName = days.find(d => d.id == dayId).name;
            const subjectName = $('#entry_subject_id option[value="' + subjectId + '"]').text();
            const teacherName = $('#entry_teacher_id option[value="' + teacherId + '"]').text();

            let added = 0;
            periods.forEach(period => {
                // Check if entry already exists
                const exists = bulkEntries.find(e => e.day_id == dayId && e.period_id == period.id);

                if (!exists) {
                    bulkEntries.push({
                        day_id: dayId,
                        day_name: dayName,
                        period_id: period.id,
                        period_name: period.name,
                        subject_id: subjectId,
                        subject_name: subjectName,
                        teacher_id: teacherId,
                        teacher_name: teacherName,
                        room_number: room,
                        notes: ''
                    });
                    added++;
                }
            });

            updateEntriesPreview();
            toastr.success(`Added ${added} entries for ${dayName}`);
        }
    });
}

function fillSamePeriodAllDays() {
    <?php
    $periods = $timetable->getAllPeriods();
    $periodsData = array_values(array_filter(array_map(function($p) {
        return $p->is_break == 0 ? [
            'id' => $p->id,
            'name' => $p->period_name
        ] : null;
    }, $periods)));
    echo "const periods = " . json_encode($periodsData) . ";";

    $days = $timetable->getActiveDays();
    $daysData = array_map(function($d) {
        return ['id' => $d->id, 'name' => $d->day_name];
    }, $days);
    echo "const days = " . json_encode($daysData) . ";";
    ?>

    // Build period selection
    let periodOptions = '<option value="">Select Period</option>';
    periods.forEach(period => {
        periodOptions += `<option value="${period.id}">${period.name}</option>`;
    });

    Swal.fire({
        title: 'Fill Same Period for All Days',
        html: `
            <div class="form-group text-left">
                <label>Select Period:</label>
                <select id="bulk_period" class="form-control">${periodOptions}</select>
            </div>
            <div class="form-group text-left">
                <label>Select Subject:</label>
                <select id="bulk_subject" class="form-control">
                    ${$('#entry_subject_id').html()}
                </select>
            </div>
            <div class="form-group text-left">
                <label>Select Teacher:</label>
                <select id="bulk_teacher" class="form-control">
                    ${$('#entry_teacher_id').html()}
                </select>
            </div>
            <div class="form-group text-left">
                <label>Room Number (Optional):</label>
                <input type="text" id="bulk_room" class="form-control" placeholder="e.g., 101">
            </div>
        `,
        showCancelButton: true,
        confirmButtonText: 'Fill All Days',
        cancelButtonText: 'Cancel',
        preConfirm: () => {
            const periodId = document.getElementById('bulk_period').value;
            const subjectId = document.getElementById('bulk_subject').value;
            const teacherId = document.getElementById('bulk_teacher').value;
            const room = document.getElementById('bulk_room').value;

            if (!periodId || !subjectId || !teacherId) {
                Swal.showValidationMessage('Please fill all required fields');
                return false;
            }

            return { periodId, subjectId, teacherId, room };
        }
    }).then((result) => {
        if (result.isConfirmed) {
            const { periodId, subjectId, teacherId, room } = result.value;

            const periodName = periods.find(p => p.id == periodId).name;
            const subjectName = $('#entry_subject_id option[value="' + subjectId + '"]').text();
            const teacherName = $('#entry_teacher_id option[value="' + teacherId + '"]').text();

            let added = 0;
            days.forEach(day => {
                // Check if entry already exists
                const exists = bulkEntries.find(e => e.day_id == day.id && e.period_id == periodId);

                if (!exists) {
                    bulkEntries.push({
                        day_id: day.id,
                        day_name: day.name,
                        period_id: periodId,
                        period_name: periodName,
                        subject_id: subjectId,
                        subject_name: subjectName,
                        teacher_id: teacherId,
                        teacher_name: teacherName,
                        room_number: room,
                        notes: ''
                    });
                    added++;
                }
            });

            updateEntriesPreview();
            toastr.success(`Added ${added} entries for ${periodName}`);
        }
    });
}

function importFromCSV() {
    $('#csvImportModal').modal('show');
}

function processCSV() {
    const fileInput = document.getElementById('csv-file');
    const file = fileInput.files[0];

    if (!file) {
        toastr.error('Please select a CSV file');
        return;
    }

    const reader = new FileReader();
    reader.onload = function(e) {
        const text = e.target.result;
        const lines = text.split('\n');

        let imported = 0;
        let errors = 0;

        // Skip header row
        for (let i = 1; i < lines.length; i++) {
            const line = lines[i].trim();
            if (!line) continue;

            const parts = line.split(',');

            if (parts.length < 4) {
                errors++;
                continue;
            }

            const dayId = parts[0].trim();
            const periodId = parts[1].trim();
            const subjectId = parts[2].trim();
            const teacherId = parts[3].trim();
            const room = parts[4] ? parts[4].trim() : '';
            const notes = parts[5] ? parts[5].trim() : '';

            // Get names
            const dayName = $('#entry_day_id option[value="' + dayId + '"]').text();
            const periodName = $('#entry_period_id option[value="' + periodId + '"]').text();
            const subjectName = $('#entry_subject_id option[value="' + subjectId + '"]').text();
            const teacherName = $('#entry_teacher_id option[value="' + teacherId + '"]').text();

            if (!dayName || !periodName || !subjectName || !teacherName) {
                errors++;
                continue;
            }

            // Check for duplicate
            const exists = bulkEntries.find(e => e.day_id == dayId && e.period_id == periodId);

            if (!exists) {
                bulkEntries.push({
                    day_id: dayId,
                    day_name: dayName,
                    period_id: periodId,
                    period_name: periodName,
                    subject_id: subjectId,
                    subject_name: subjectName,
                    teacher_id: teacherId,
                    teacher_name: teacherName,
                    room_number: room,
                    notes: notes
                });
                imported++;
            }
        }

        updateEntriesPreview();
        $('#csvImportModal').modal('hide');

        if (imported > 0) {
            toastr.success(`Imported ${imported} entries`);
        }
        if (errors > 0) {
            toastr.warning(`${errors} entries had errors and were skipped`);
        }
    };

    reader.readAsText(file);
}

            </script>
    <?php
  }else{
      ?>
    <!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, maximum-scale=1, shrink-to-fit=no">
        <title>Login to continue |  <?php echo $school_name; ?> </title>

        <?php include 'includes/styles.php'; ?>

        <!-- END PAGE LEVEL PLUGINS/CUSTOM STYLES -->

    </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>

    <?php
    }

  ?>
