<?php
header("Content-Type: application/json");
require("../../includes/config.php");

// 1. Get and Decode Data
$student_ids   = json_decode($_POST['student_ids'] ?? '[]', true);
$to_class      = $_POST['to_class'] ?? '';
$to_section_id = $_POST['to_section'] ?? ''; 
$next_year_id  = $_POST['next_year_id'] ?? '';

if (empty($student_ids) || !is_array($student_ids)) {
    echo json_encode(["status" => false, "msg" => "No students selected or invalid data format."]);
    exit;
}

try {
    $pdo->beginTransaction();

    // Prepare: Check if student is already enrolled in the next year to prevent duplicates
    $checkStmt = $pdo->prepare("SELECT id FROM enrollments WHERE student_id = ? AND academic_year_id = ?");
    
    // Prepare: Update status for the CURRENT year
    $updateOld = $pdo->prepare("UPDATE enrollments SET promotion_status = 'promoted' WHERE student_id = ? AND academic_year_id = ?");

    // Prepare: Insert student into the NEXT year (REMOVED: stream_id)
    $insertStmt = $pdo->prepare("INSERT INTO enrollments (student_id, class_id, section_id, academic_year_id, roll_no, promotion_status) 
                                 VALUES (?, ?, ?, ?, ?, 'active')");

    // Get Old Roll Number to carry it forward (or reset as per your policy)
    $getRoll = $pdo->prepare("SELECT roll_no FROM enrollments WHERE student_id = ? AND academic_year_id = ? LIMIT 1");

    $count = 0;
    foreach ($student_ids as $sid) {
        // Skip if already promoted to prevent primary key/unique constraint violations
        $checkStmt->execute([$sid, $next_year_id]);
        if ($checkStmt->rowCount() > 0) continue;

        // Fetch current roll number
        $getRoll->execute([$sid, APP_YEAR_ID]);
        $roll = $getRoll->fetchColumn() ?: 0;

        // Mark current enrollment as 'promoted'
        $updateOld->execute([$sid, APP_YEAR_ID]);
        
        // Handle Nullable Section: if "Select Section" was left empty, it stores NULL
        $sec_val = (!empty($to_section_id)) ? $to_section_id : null;
        
        // Execute the new enrollment
        $insertStmt->execute([
            $sid, 
            $to_class, 
            $sec_val, 
            $next_year_id, 
            $roll
        ]);
        
        $count++;
    }

    $pdo->commit();
    echo json_encode(["status" => true, "msg" => "Successfully promoted $count students!"]);

} catch (Exception $e) {
    if ($pdo->inTransaction()) $pdo->rollBack();
    echo json_encode(["status" => false, "msg" => "Database Error: " . $e->getMessage()]);
}
?>