<?php
include '_serveur.php';
mysqli_set_charset($link,"utf8");

// Check if it's drag-and-drop (JSON) or single move (POST)
$input = file_get_contents('php://input');
$data = json_decode($input, true);

if($data && isset($data['classID'], $data['order'])){
    // Drag-and-drop reordering
    $classID = intval($data['classID']);
    $orderList = $data['order'];

    if(!$classID || !is_array($orderList)){
        echo 'Paramètres invalides';
        exit;
    }

    mysqli_begin_transaction($link);
    try {
        foreach($orderList as $item){
            $subID = intval($item['subSubjectID'] ?? 0);
            $ordering = intval($item['ordering'] ?? 0);
            if($subID && $ordering){
                mysqli_query($link,"UPDATE gradesSubjects 
                                    SET ordering='$ordering' 
                                    WHERE classID='$classID' AND subSubjectID='$subID'");
            }
        }
        mysqli_commit($link);
        echo 'Ordre mis à jour';
    } catch(Exception $e){
        mysqli_rollback($link);
        echo 'Erreur mise à jour';
    }
    exit;
}

// Otherwise, single move (up/down)
$classID = intval($_POST['classID'] ?? 0);
$subID   = intval($_POST['subSubjectID'] ?? 0);
$direction = $_POST['direction'] ?? '';

if(!$classID || !$subID || !in_array($direction,['up','down'])){
    echo 'Paramètres invalides';
    exit;
}

// Get current ordering
$res = mysqli_query($link,"SELECT ordering FROM gradesSubjects WHERE classID='$classID' AND subSubjectID='$subID'");
if(!$row = mysqli_fetch_assoc($res)){
    echo 'Ligne introuvable';
    exit;
}
$currentOrder = intval($row['ordering']);

// Find neighbor
if($direction==='up'){
    $res2 = mysqli_query($link,"SELECT subSubjectID, ordering FROM gradesSubjects 
                                WHERE classID='$classID' AND ordering < $currentOrder 
                                ORDER BY ordering DESC LIMIT 1");
}else{
    $res2 = mysqli_query($link,"SELECT subSubjectID, ordering FROM gradesSubjects 
                                WHERE classID='$classID' AND ordering > $currentOrder 
                                ORDER BY ordering ASC LIMIT 1");
}

if(!$neighbor = mysqli_fetch_assoc($res2)){
    echo 'Déjà en limite';
    exit;
}

// Swap ordering
$neighborID = $neighbor['subSubjectID'];
$neighborOrder = intval($neighbor['ordering']);

mysqli_query($link,"UPDATE gradesSubjects SET ordering='$neighborOrder' WHERE classID='$classID' AND subSubjectID='$subID'");
mysqli_query($link,"UPDATE gradesSubjects SET ordering='$currentOrder' WHERE classID='$classID' AND subSubjectID='$neighborID'");

echo 'Réorganisation réussie';
?>
