<?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'>×</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'>";
        $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();

            $output .= "<tr>
                        <td>
                         <input type='checkbox' name='select-student[]' value='$student_id' class='select-student-checkbox' />
                         <input type='hidden' name='class_id[]' value='$new_class_id' />
                        </td>
                       
                        <td>$student_image </td>
                        <td>$student->name</td>
                        <td>$reg_no</td>
                        <td>
                            <select name='promoted_section[]' class='form-control'>
                                <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'>×</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 rows = document.querySelectorAll('tbody tr');
        let valid = true;

        rows.forEach(row => {
            const checkbox = row.querySelector('.select-student-checkbox');
            if (checkbox.checked) { // Check only if student is selected
                const select = row.querySelector('select[name="promoted_section[]"]');
                if (select.value === '') {
                    valid = false;
                    select.style.border = '1px 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();
        const formData = new FormData(this);

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

        xhr.onload = function() {
            const response = JSON.parse(xhr.responseText);
            if (xhr.status === 200 && response.status === 'success') {
                toastr.success(response.message);
            } else {
                toastr.error(response.message || 'An error occurred while promoting students.');
            }
        };

        xhr.send(formData);
    });

</script>



