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

// Get POST data safely
$classID = intval($_POST['classID'] ?? 0);
$subID   = intval($_POST['sub'] ?? 0);
$coef    = floatval($_POST['coef'] ?? 0);
$cycle   = $_POST['cycle'] ?? '';

if (!$classID || !$subID || $coef <= 0) {
    echo json_encode(['status'=>'error','message'=>'Données manquantes ou invalides.']);
    exit;
}

// Check if already exists
$sqlCheck = "SELECT * FROM gradesSubjects WHERE classID=? AND subSubjectID=?";
$stmtCheck = mysqli_prepare($link, $sqlCheck);
mysqli_stmt_bind_param($stmtCheck, "ii", $classID, $subID);
mysqli_stmt_execute($stmtCheck);
$resultCheck = mysqli_stmt_get_result($stmtCheck);

if (mysqli_num_rows($resultCheck) > 0) {
    echo json_encode(['status'=>'error','message'=>'Cette matière existe déjà pour cette classe.']);
    exit;
}

// Get subject + subSubject name
$sqlName = "SELECT subjects.name AS subjectName, subSubjects.name AS subName 
            FROM subSubjects 
            JOIN subjects ON subSubjects.subjectID = subjects.id
            WHERE subSubjects.id=?";
$stmtName = mysqli_prepare($link, $sqlName);
mysqli_stmt_bind_param($stmtName, "i", $subID);
mysqli_stmt_execute($stmtName);
$resName = mysqli_stmt_get_result($stmtName);
$rowName = mysqli_fetch_assoc($resName);

if (!$rowName) {
    echo json_encode(['status'=>'error','message'=>'Matière introuvable.']);
    exit;
}

$subjectName = $rowName['subjectName'];
$subName = $rowName['subName'];

// Determine next ordering
$sqlOrder = "SELECT MAX(ordering) AS maxOrd FROM gradesSubjects WHERE classID=?";
$stmtOrder = mysqli_prepare($link, $sqlOrder);
mysqli_stmt_bind_param($stmtOrder, "i", $classID);
mysqli_stmt_execute($stmtOrder);
$resOrder = mysqli_stmt_get_result($stmtOrder);
$rowOrder = mysqli_fetch_assoc($resOrder);
$nextOrder = ($rowOrder['maxOrd'] ?? 0) + 1;

// Insert into DB
$sqlInsert = "INSERT INTO gradesSubjects (classID, subSubjectID, coeficient, ordering) VALUES (?, ?, ?, ?)";
$stmtInsert = mysqli_prepare($link, $sqlInsert);
mysqli_stmt_bind_param($stmtInsert, "iidi", $classID, $subID, $coef, $nextOrder);

if (mysqli_stmt_execute($stmtInsert)) {
    $newID = $subID; // subID remains the same
    echo json_encode([
        'status'=>'ok',
        'subID'=>$newID,
        'fullName'=>$subjectName.' - '.$subName
    ]);
} else {
    echo json_encode(['status'=>'error','message'=>'Erreur lors de l\'ajout : '.mysqli_error($link)]);
}

mysqli_stmt_close($stmtCheck);
mysqli_stmt_close($stmtName);
mysqli_stmt_close($stmtOrder);
mysqli_stmt_close($stmtInsert);
mysqli_close($link);
?>
