"error", "message" => "Invalid assignment ID."]));
}
// Begin a transaction to ensure both deletion and update succeed together.
$mysqli->begin_transaction();
try {
// 1. Retrieve the Schedule_ID for the assignment so we know which schedule to update.
$stmt = $mysqli->prepare("SELECT Schedule_ID FROM Teacher_Course_Assignments WHERE Assignment_ID = ?");
if (!$stmt) {
throw new Exception("Error preparing retrieval query: " . $mysqli->error);
}
$stmt->bind_param("i", $assignmentID);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows === 0) {
throw new Exception("No assignment found with the provided ID.");
}
$row = $result->fetch_assoc();
$scheduleID = $row['Schedule_ID'];
$stmt->close();
// 2. Delete the teacher's course assignment.
$stmt = $mysqli->prepare("DELETE FROM Teacher_Course_Assignments WHERE Assignment_ID = ?");
if (!$stmt) {
throw new Exception("Error preparing deletion query: " . $mysqli->error);
}
$stmt->bind_param("i", $assignmentID);
if (!$stmt->execute()) {
throw new Exception("Error executing deletion query: " . $stmt->error);
}
$stmt->close();
// 3. Update the Course_Group_Schedule table to mark the schedule as not assigned.
$stmt = $mysqli->prepare("UPDATE Course_Group_Schedule_Main SET Assigned = 0 WHERE Schedule_ID = ?");
if (!$stmt) {
throw new Exception("Error preparing update query: " . $mysqli->error);
}
$stmt->bind_param("i", $scheduleID);
if (!$stmt->execute()) {
throw new Exception("Error executing update query: " . $stmt->error);
}
$stmt->close();
// 3. Update the Course_Group_Schedule table to mark the schedule as not assigned.
$stmt = $mysqli->prepare("UPDATE Schedule_Course_for_Group SET Assigned = 0 WHERE Schedule_ID = ?");
if (!$stmt) {
throw new Exception("Error preparing update query: " . $mysqli->error);
}
$stmt->bind_param("i", $scheduleID);
if (!$stmt->execute()) {
throw new Exception("Error executing update query: " . $stmt->error);
}
$stmt->close();
// Commit the transaction if all queries succeeded.
$mysqli->commit();
echo json_encode(["status" => "success", "message" => "Course deleted successfully from teacher"]);
} catch (Exception $e) {
// Roll back the transaction on error.
$mysqli->rollback();
echo json_encode(["status" => "error", "message" => $e->getMessage()]);
}
}
?>