<?php
include('includes/dbconnection.php');

if (isset($_POST['class_name']) && isset($_POST['section'])) {
    $class = $_POST['class_name'];
    $section = $_POST['section'];

    $result = mysqli_query($con, "SELECT id, Subject_name 
                                  FROM subjectcombination 
                                  WHERE Class='$class' AND section='$section'
                                  ORDER BY Subject_name ASC");

    if (mysqli_num_rows($result) > 0) {
        echo "<div class='mb-2'>";
        echo "<button type='button' id='toggleAll' class='btn btn-sm btn-secondary'>Select All</button>";
        echo "</div>";

        echo "<div class='row'>";
        while ($row = mysqli_fetch_assoc($result)) {
            echo "<div class='col-md-4 col-sm-6'>";
            echo "<div class='form-check'>";
            echo "<input class='form-check-input subject-checkbox' type='checkbox' name='subject_ids[]' value='{$row['id']}' id='sub_{$row['id']}'>";
            echo "<label class='form-check-label' for='sub_{$row['id']}'>{$row['Subject_name']}</label>";
            echo "</div>";
            echo "</div>";
        }
        echo "</div>";

        // Inline JS to handle Select All toggle
        echo "
        <script>
        let allSelected = false;
        document.getElementById('toggleAll').addEventListener('click', function() {
            allSelected = !allSelected;
            document.querySelectorAll('.subject-checkbox').forEach(cb => cb.checked = allSelected);
            this.textContent = allSelected ? 'Deselect All' : 'Select All';
        });
        </script>
        ";
    } else {
        echo '<p class="text-danger">No subjects found for selected class and arm.</p>';
    }
}
