<?php
session_start();
include 'includes/database.php';
include 'includes/functions.php';
$conn = new Functions();

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Check if students are selected
    if (!isset($_POST['select-student']) || !is_array($_POST['select-student']) || count($_POST['select-student']) === 0) {
        echo json_encode(array('status' => 'error', 'message' => 'No students selected.'));
        exit;
    }

    $students = $_POST['select-student'];
    $promoted_sections = $_POST['promoted_section'];
    $class_ids = $_POST['class_id'];
    $errors = array();
    $updatedCount = 0;

    foreach ($students as $index => $student_id) {
        // Only process if section is selected
        if (!empty($promoted_sections[$index])) {
            $section_id = $promoted_sections[$index];
            $class_id = $class_ids[$index];

            // Prepare the SQL to update student promotion
            $sql = "UPDATE student SET classesID = :class_id, sectionid = :section_id WHERE studentID = :student_id";
            $conn->query($sql);
            $conn->bind(':class_id', $class_id);
            $conn->bind(':section_id', $section_id);
            $conn->bind(':student_id', $student_id);

            if ($conn->execute()) {
                $updatedCount++;
            } else {
                $errors[] = "Failed to promote student ID: $student_id";
            }
        }
    }

    if ($updatedCount > 0) {
        echo json_encode(array('status' => 'success', 'message' => 'Students promoted successfully!'));
    } else {
        echo json_encode(array('status' => 'error', 'message' => 'No students were promoted. Please try again.'));
    }
} else {
    echo json_encode(array('status' => 'error', 'message' => 'Invalid request method.'));
}
