isLoggedIn()) { $_SESSION['error_message'] = 'Unauthorized'; redirectTo('projects.php'); exit; } if ($_SERVER['REQUEST_METHOD'] !== 'POST') { $_SESSION['error_message'] = 'Invalid request method'; redirectTo('projects.php'); exit; } $db = Database::getInstance(); $selection_id = isset($_POST['selection_id']) ? (int)$_POST['selection_id'] : 0; $project_id = isset($_POST['project_id']) ? (int)$_POST['project_id'] : 0; if (!$selection_id || !$project_id) { $_SESSION['error_message'] = 'Required fields are missing'; redirectTo("manage_project.php?id=$project_id"); exit; } // Verify user has access to this selection and project $stmt = $db->prepare(" SELECT s.name FROM selections s JOIN projects p ON s.project_id = p.id WHERE s.id = ? AND p.id = ? AND p.created_by = ? "); $stmt->bind_param('iii', $selection_id, $project_id, $_SESSION['user_id']); $stmt->execute(); $result = $stmt->get_result(); if ($result->num_rows === 0) { $_SESSION['error_message'] = 'Selection not found or access denied'; redirectTo("manage_project.php?id=$project_id"); exit; } $selection_name = $result->fetch_assoc()['name']; // Begin transaction $db->query("START TRANSACTION"); try { // First delete selection members $stmt = $db->prepare("DELETE FROM selection_members WHERE selection_id = ?"); $stmt->bind_param('i', $selection_id); if (!$stmt->execute()) { throw new Exception("Failed to delete selection members: " . $db->getLastError()); } // Then delete the selection $stmt = $db->prepare("DELETE FROM selections WHERE id = ?"); $stmt->bind_param('i', $selection_id); if (!$stmt->execute()) { throw new Exception("Failed to delete selection: " . $db->getLastError()); } // Commit the transaction $db->query("COMMIT"); $_SESSION['success_message'] = "Selection '$selection_name' has been deleted successfully"; redirectTo("manage_project.php?id=$project_id"); } catch (Exception $e) { // Rollback on error $db->query("ROLLBACK"); $_SESSION['error_message'] = $e->getMessage(); redirectTo("manage_project.php?id=$project_id"); } ?>