isLoggedIn()) { throw new Exception('Unauthorized'); } $connectionId = isset($_POST['connection_id']) ? (int)$_POST['connection_id'] : null; $redirect = isset($_POST['redirect']) ? $_POST['redirect'] : null; if (!$connectionId) { throw new Exception('Connection ID is required'); } $db = Database::getInstance(); // Check if the connection exists and user has access $stmt = $db->prepare(" SELECT ps.* FROM project_surveys ps JOIN projects p ON ps.project_id = p.id WHERE ps.id = ? AND p.created_by = ? "); $stmt->bind_param('ii', $connectionId, $_SESSION['user_id']); $stmt->execute(); if ($stmt->get_result()->num_rows == 0) { throw new Exception('Connection not found or access denied'); } // Disconnect (delete the connection) $stmt = $db->prepare("DELETE FROM project_surveys WHERE id = ?"); $stmt->bind_param('i', $connectionId); if (!$stmt->execute()) { throw new Exception('Failed to disconnect survey from project'); } // Handle redirect or JSON response if ($redirect) { // Set a success message in session $_SESSION['success_message'] = 'Survey disconnected successfully'; redirectTo($redirect); exit; } else { // Return JSON response header('Content-Type: application/json'); echo json_encode([ 'success' => true, 'message' => 'Survey disconnected successfully' ]); } } catch (Exception $e) { if (isset($_POST['redirect'])) { // Set error message in session $_SESSION['error_message'] = $e->getMessage(); redirectTo($_POST['redirect']); exit; } else { // Return JSON error header('Content-Type: application/json'); echo json_encode([ 'success' => false, 'message' => $e->getMessage() ]); } } ?>