SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[cs_Moderate_DeletePost]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)
drop procedure [dbo].[cs_Moderate_DeletePost]
GO

CREATE PROCEDURE [dbo].cs_Moderate_DeletePost
(
	@PostID INT,
	@DeletedBy INT,
	@Reason NVARCHAR(1024) = '',
	@DeleteChildPosts BIT = 1,
	@SettingsID int
)
AS
-- Deletes the post

SET Transaction Isolation Level Read UNCOMMITTED

DECLARE @IsApproved bit
DECLARE @SectionID int

-- First, get information about the post that is about to be deleted.
SELECT
    @IsApproved = IsApproved,
    @SectionID = SectionID
FROM
    cs_Posts
WHERE
    PostID = @PostID and SettingsID = @SettingsID

-- If the post is not approved, permanently delete the post
IF (@IsApproved = 0)
BEGIN	
    	-- Delete the post.
	DELETE FROM cs_Posts WHERE PostID = @PostID AND SettingsID = @SettingsID

	-- Update moderation statistics
	UPDATE	cs_Sections
	SET		PostsToModerate = (SELECT Count(PostID) FROM cs_Posts WHERE SectionID = @SectionID AND IsApproved = 0 and SettingsID = @SettingsID)
	WHERE	SectionID = @SectionID AND SettingsID = @SettingsID

	-- Update Moderation Audit table
	IF (@Reason IS NULL OR @Reason = '')
		SET @Reason = 'Automatic generated reason: the post has been deleted on request.'

	EXEC cs_system_ModerationAction_AuditEntry 4, @DeletedBy, @PostID, null, null, @SettingsID, @Reason
END	
ELSE
BEGIN
	DECLARE @DeletedSectionID INT
	DECLARE @OldThreadID INT
	DECLARE @NewThreadID INT
	
	-- Init data	
	SELECT @DeletedSectionID = SectionID FROM cs_Sections WHERE SettingsID = @SettingsID and ForumType = 50
	SELECT @OldThreadID = ThreadID, @SectionID = SectionID FROM cs_Posts WHERE SettingsID = @SettingsID AND PostID = @PostID
	SET @NewThreadID = NULL
	
	-- Is this a private message post (@SectionID = 0)?
	IF (@SectionID = 0)
	BEGIN
		-- Permanently delete the post and its replies
		EXEC cs_Post_Delete @SectionID, @SettingsID, @PostID, 0, @DeletedBy, @Reason

		-- Statistics update
		EXEC cs_system_ResetThreadStatistics @OldThreadID
	END
	ELSE -- (@SectionID <> 0)
	BEGIN
		IF (@DeleteChildPosts = 1)
			-- Move the post and its replies to 'Deleted Posts' forum
			EXEC cs_system_DeletePostAndChildren @PostID, @DeleteChildPosts, @SettingsID, @DeletedBy, @Reason, @NewThreadID OUT, NULL

		ELSE -- (@DeleteChildPosts <> 1)
			-- Move the post to 'Deleted Posts' forum, reassign children to deleted post's parent
			EXEC cs_system_DeletePostAndAdoptChildren @PostID, @SettingsID, @DeletedBy, @Reason, @NewThreadID OUTPUT

		-- Statistics update
		EXEC cs_system_ResetThreadStatistics @OldThreadID
		EXEC cs_system_ResetThreadStatistics @NewThreadID
		EXEC cs_system_ResetForumStatistics @SectionID
		EXEC cs_system_ResetForumStatistics @DeletedSectionID
	END
END

GO

SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO


grant execute on [dbo].[cs_Moderate_DeletePost] to public
go