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

// Get POST data safely
$classID = intval($_POST['classID'] ?? 0);
$subID   = intval($_POST['subSubjectID'] ?? 0);

if (!$classID || !$subID) {
    echo "Données manquantes ou invalides.";
    exit;
}

// Check if the record 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 "Cette matière n'existe pas pour cette classe.";
    exit;
}

// Delete the record
$sqlDelete = "DELETE FROM gradesSubjects WHERE classID=? AND subSubjectID=?";
$stmtDelete = mysqli_prepare($link, $sqlDelete);
mysqli_stmt_bind_param($stmtDelete, "ii", $classID, $subID);

if (mysqli_stmt_execute($stmtDelete)) {
    echo "Matière supprimée avec succès.";
} else {
    echo "Erreur lors de la suppression : " . mysqli_error($link);
}

// Close statements
mysqli_stmt_close($stmtCheck);
mysqli_stmt_close($stmtDelete);
mysqli_close($link);
?>
