<?php
session_start();
//header('Content-Type: application/json');

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

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

    // Validate that we have matching arrays
    if (!isset($_POST['section_ids']) || count($_POST['student_ids']) !== count($_POST['section_ids'])) {
        echo json_encode(array('status' => 'error', 'message' => 'Data mismatch error. Please try again.'));
        exit;
    }

    // Validate new_class_id exists
    if (empty($_POST['new_class_id'])) {
        echo json_encode(array('status' => 'error', 'message' => 'Promotion class not specified.'));
        exit;
    }

    $student_ids = $_POST['student_ids'];
    $section_ids = $_POST['section_ids'];
    $new_class_id = (int) $_POST['new_class_id'];
    $errors = array();
    $updatedCount = 0;

    // Process each student with their corresponding section
    for ($i = 0; $i < count($student_ids); $i++) {
        $student_id = (int) $student_ids[$i];
        $section_id = (int) $section_ids[$i];

        // Validate section is not empty
        if (empty($section_id)) {
            $errors[] = "Student ID $student_id: Section not selected";
            continue;
        }

        // Verify student exists before updating
        $check_sql = "SELECT studentID, name FROM student WHERE studentID = :student_id";
        $conn->query($check_sql);
        $conn->bind(':student_id', $student_id);
        $student_exists = $conn->fetchSingle();

        if (!$student_exists) {
            $errors[] = "Student ID $student_id not found in database";
            continue;
        }

        // Update student promotion (note: your table uses 'sectionid' not 'sectionID')
        $sql = "UPDATE student SET classesID = :class_id, sectionid = :section_id WHERE studentID = :student_id";
        $conn->query($sql);
        $conn->bind(':class_id', $new_class_id);
        $conn->bind(':section_id', $section_id);
        $conn->bind(':student_id', $student_id);

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

    // Prepare response
    if ($updatedCount > 0) {
        $message = "$updatedCount student(s) promoted successfully!";
        if (count($errors) > 0) {
            $message .= " " . count($errors) . " student(s) failed: " . implode(", ", $errors);
        }
        echo json_encode(array('status' => 'success', 'message' => $message, 'promoted_count' => $updatedCount));
    } else {
        $error_message = 'No students were promoted.';
        if (count($errors) > 0) {
            $error_message .= " Errors: " . implode(", ", $errors);
        }
        echo json_encode(array('status' => 'error', 'message' => $error_message));
    }
} else {
    echo json_encode(array('status' => 'error', 'message' => 'Invalid request method.'));
}
?>