<?php
session_start();
//error_reporting('0');
include 'includes/database.php';
include 'includes/functions.php';
$conn= new Functions();
$base_url = $conn->base_url();
$output = '';
if(!empty($_POST['current_class']) && !empty($_POST['new_class'])){
    $current_class_id = (int) $_POST['current_class'];
    $new_class_id = (int) $_POST['new_class'];

    //check if the current class and new class are the same and throw an error
    if($current_class_id == $new_class_id){
        echo "<p class='alert alert-danger alert-dismissible fade show text-center' role='alert'>
              <i class='fas fa-ban'></i>
               Current and Promotion class cannot be the same.
                  <button type='button' class='close' data-dismiss='alert' aria-label='Close'>
                             <span aria-hidden='true'>&times;</span>
                  </button>
           </p>";
        return;
    }


    //fetch class names
    $sql = "SELECT name FROM classes WHERE id = :id";
    $conn->query($sql);
    $conn->bind(":id", $current_class_id);
    $current_class_name = $conn->fetchColumn();

    $sql = "SELECT name FROM classes WHERE id = :id";
    $conn->query($sql);
    $conn->bind(":id", $new_class_id);
    $new_class_name = $conn->fetchColumn();

// Fetch student names based on the selected class
    $sql = "SELECT * FROM student WHERE classesID =:class_id";
    $conn->query($sql);
    $conn->bind(":class_id", $current_class_id);
    $rowCount = $conn->rowCount();


    if ($rowCount > 0) {
        $result = $conn->fetchMultiple();
        $output = "<div class='card-body'>";
        $output .= "<div class='col-md-12 jumbotron'>
                    <h3 class='text-center'>Student Details</h3>
                    <div class='text-center'>
                    <span class='text-center' style='display: inline-block;'>Current Class: <span>$current_class_name</span></span><br>
                    <span class='text-center' style='display: inline-block;'>Promotion Class: <span>$new_class_name</span></span><br>
                   </div>
               </div>";
        $output .= "<form method='post' action='' id='add-students-promotion'>";

        // Add hidden fields for class IDs - these are the same for all students
        $output .= "<input type='hidden' name='current_class_id' value='$current_class_id' />";
        $output .= "<input type='hidden' name='new_class_id' value='$new_class_id' />";

        $output .= "<div class='table-responsive'>";
        $output .= "<table class='table table-bordered table-hover table-stripped' id='teacher'>
                    <thead>
                        <th><input type='checkbox' class='custom-checkbox' id='check-all'></th>
                        <th>Photo</th>
                        <th>Name</th>
                        <th>Reg No</th>
                        <th>Promoted Section</th>
                    </thead>";
        $output .= "<tbody>";

        foreach ($result as $student) {
            $student_id = $student->studentID;
            $student_image = !empty($student->photo) ? "<img src='{$base_url}upload/$student->photo' width='32' height='32'>" : "<img src='{$base_url}images/default.png' width='32' height='32'>";
            $reg_no = $student->registerNO;

            // Fetch sections for the promotional class
            $sql = "SELECT * FROM sections WHERE class =:class_id";
            $conn->query($sql);
            $conn->bind(":class_id", $new_class_id);
            $promoted_sessions = $conn->fetchMultiple();

            // CRITICAL FIX: Use student_id as the array key to maintain proper pairing
            $output .= "<tr>
                        <td>
                         <input type='checkbox' name='student_ids[]' value='$student_id' class='select-student-checkbox' data-student-id='$student_id' />
                        </td>
                       
                        <td>$student_image </td>
                        <td>$student->name</td>
                        <td>$reg_no</td>
                        <td>
                            <select name='section_$student_id' class='form-control promoted-section' data-student-id='$student_id'>
                                <option value=''>Select Section</option>";

            foreach ($promoted_sessions as $section) {
                $output .= "<option value='$section->id'>$section->name</option>";
            }

            $output .= "</select>
                        </td>
                    </tr>";
        }
        $output .= "</tbody>";
        $output .= "<tfoot>
                    <th>#</th>
                    <th>Photo</th>
                    <th>Name</th>
                    <th>Reg No</th>
                    <th>Action</th>
                </tfoot>";
        $output .= "</table>";
        $output .= "</div>";
        $output .= "<div><input type='submit' value='Promote Selected Students' id='submit-promotion' class='btn btn-dark'></div>";
        $output .= "</form>";
        $output .= "</div>";
        echo $output;
    } else {
        echo "<p style='padding: 30px; text-align: center;'>No Students found for the selected details.</p>";
    }


}else{
    echo "<p class='alert alert-danger alert-dismissible fade show text-center' role='alert'>
              <i class='fas fa-ban'></i>
               Fields marked (*) are required.
                  <button type='button' class='close' data-dismiss='alert' aria-label='Close'>
                             <span aria-hidden='true'>&times;</span>
                  </button>
           </p>";
}

?>

<script>
    $(function () {
        $("#teacher").DataTable({
            "responsive": true,
            "lengthChange": true,
            "autoWidth": false,
            "pageLength": 100,  // Set initial load to 100 rows
            "buttons": ["copy", "csv", "pdf", "print"]
        }).buttons().container().appendTo('#teacher_wrapper .col-md-6:eq(0)');
    });

</script>

<script>
    // Select all checkboxes when "check-all" is clicked
    document.getElementById('check-all').addEventListener('click', function() {
        const checkboxes = document.querySelectorAll('.select-student-checkbox');
        checkboxes.forEach(checkbox => checkbox.checked = this.checked);
    });

    // Validate section selection for only selected students
    document.getElementById('submit-promotion').addEventListener('click', function(event) {
        const checkboxes = document.querySelectorAll('.select-student-checkbox:checked');

        if (checkboxes.length === 0) {
            event.preventDefault();
            toastr.error('Please select at least one student to promote.');
            return;
        }

        let valid = true;
        checkboxes.forEach(checkbox => {
            const studentId = checkbox.getAttribute('data-student-id');
            const select = document.querySelector(`select[name="section_${studentId}"]`);

            if (select.value === '') {
                valid = false;
                select.style.border = '2px solid red';
            } else {
                select.style.border = ''; // Reset border if valid
            }
        });

        if (!valid) {
            event.preventDefault();
            toastr.error('Please select a section for all selected students.');
        }
    });

    // Ajax submission for the form
    document.getElementById('add-students-promotion').addEventListener('submit', function(event) {
        event.preventDefault();

        // Create FormData and only include selected students with their sections
        const formData = new FormData();

        // Add class IDs
        formData.append('current_class_id', document.querySelector('input[name="current_class_id"]').value);
        formData.append('new_class_id', document.querySelector('input[name="new_class_id"]').value);

        // Get all checked students
        const checkedBoxes = document.querySelectorAll('.select-student-checkbox:checked');

        checkedBoxes.forEach(checkbox => {
            const studentId = checkbox.value;
            const sectionSelect = document.querySelector(`select[name="section_${studentId}"]`);
            const sectionId = sectionSelect.value;

            // Append as paired data
            formData.append('student_ids[]', studentId);
            formData.append('section_ids[]', sectionId);
        });

        const submitBtn = document.getElementById('submit-promotion');
        submitBtn.disabled = true;
        submitBtn.value = 'Promoting students, please wait...';

        const xhr = new XMLHttpRequest();
        xhr.open('POST', 'submit-promoted-students.php', true);

        xhr.onload = function() {
            submitBtn.disabled = false;
            submitBtn.value = 'Promote Selected Students';

            try {
                const response = JSON.parse(xhr.responseText);
                if (xhr.status === 200 && response.status === 'success') {
                    toastr.success(response.message);
                    // Optionally reload or clear the form after 2 seconds
                    setTimeout(() => {
                        location.reload();
                    }, 2000);
                } else {
                    toastr.error(response.message || 'An error occurred while promoting students.');
                }
            } catch(e) {
                toastr.error('Invalid response from server.');
                console.error('Response:', xhr.responseText);
            }
        };

        xhr.onerror = function() {
            submitBtn.disabled = false;
            submitBtn.value = 'Promote Selected Students';
            toastr.error('Network error occurred. Please try again.');
        };

        xhr.send(formData);
    });

</script>