SET QUOTED_IDENTIFIER ON 
GO
SET ANSI_NULLS ON 
GO

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


CREATE         procedure [dbo].cs_Moderate_ApprovePost
(
	@PostID		int,
	@ApprovedBy	int,
	@SettingsID 	int
)
AS
SET Transaction Isolation Level Read UNCOMMITTED
DECLARE @SectionID 	int
DECLARE @ThreadID 	int
DECLARE @PostLevel 	int
DECLARE @UserID		int
DECLARE @IsLocked	bit

-- first make sure that the post is ALREADY non-approved
IF (SELECT IsApproved FROM cs_Posts (nolock) WHERE PostID = @PostID and SettingsID = @SettingsID) = 1
BEGIN
	print 'Post is already approved'
	SELECT 0
	RETURN
END
ELSE
BEGIN

	print 'Post is not approved'

	-- Get details about the thread and forum this post belongs in
	SELECT
		@SectionID = SectionID,
		@ThreadID = ThreadID,
		@PostLevel = PostLevel,
		@UserID	= UserID,
		@IsLocked = IsLocked
	FROM
		cs_Posts
	WHERE
		PostID = @PostID and SettingsID = @SettingsID

	-- Approve the post
	UPDATE 
		cs_Posts
	SET 
		IsApproved = 1
	WHERE 
		PostID = @PostID and SettingsID = @SettingsID

	-- Approved the thread if necessary
	IF @PostLevel = 1
		UPDATE
			cs_Threads
		SET
			IsApproved = 1
		WHERE
			ThreadID = @ThreadID and SettingsID = @SettingsID

	-- Update the user's post count
	exec cs_system_UpdateUserPostCount @SectionID, @UserID, @SettingsID

	-- Update the forum statistics
	exec cs_system_UpdateForum @SectionID, @ThreadID, @PostID, @SettingsID

	-- Clean up unnecessary columns in forumsread
	exec cs_system_CleanForumsRead @SectionID, @SettingsID

	-- update the thread stats
	exec cs_system_UpdateThread @ThreadID, @PostID, @SettingsID

	-- Update Moderation audit table
	-- Update the ModerationAudit table
	exec cs_system_ModerationAction_AuditEntry 1, @ApprovedBy, @PostID, null, @SectionID, @SettingsID, null

	-- Send back a success code
	SELECT 1
	
END


GO
SET QUOTED_IDENTIFIER OFF 
GO
SET ANSI_NULLS ON 
GO

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