USE [FastMoneyPro_Remit]
GO
/****** Object:  StoredProcedure [dbo].[Proc_paidToUnpaid]    Script Date: 7/4/2019 11:35:48 AM ******/
DROP PROCEDURE [dbo].[Proc_paidToUnpaid]
GO
/****** Object:  StoredProcedure [dbo].[Proc_paidToUnpaid]    Script Date: 7/4/2019 11:35:48 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROC [dbo].[Proc_paidToUnpaid] 
	@controlNo varchar(20) 
	,@user      varchar(50)
	,@flag		varchar(20)
 
AS 
SET NOCOUNT ON 
	DECLARE @controlNoEncrypted VARCHAR(25) ,@viewMsg varchar(200)
	DECLARE @tranIdNew VARCHAR(10)
	SET @controlNoEncrypted = dbo.FNAEncryptString(@controlNo)
	SELECT @tranIdNew = id FROM dbo.remitTran(NOLOCK) WHERE controlNo = @controlNoEncrypted

	IF @tranIdNew IS NULL
	BEGIN
	    EXEC proc_errorHandler 1,'INVALID TRANSACTION',null
		RETURN
	END

IF @flag = 'PaidToUnpaid'
BEGIN
	IF NOT EXISTS(SELECT 'X' FROM remitTran (NOLOCK) WHERE id = @tranIdNew AND tranStatus IN('Paid','Payment') and payStatus ='Paid')
	BEGIN
		EXEC proc_errorHandler 1,'ONLY PAID TRANSACTION ALLOW TO UPDATE',null
		RETURN
	END
	BEGIN TRY 
		BEGIN TRANSACTION
		SET @viewMsg = 'PAID TRANSACTION HAS CHANGED TO UNPAID BY : '+@user
		EXEC proc_tranViewHistory 'i', @user, @tranIdNew, @controlNo, NULL,'PaidToUnpaid',@viewMsg

		UPDATE remitTran SET
				 tranStatus					= 'Payment'
				,payStatus					= 'Post'
				,paidDate					= null
				,paidDateLocal				= null
				,paidBy						= null
			WHERE id = @tranIdNew

			IF @@TRANCOUNT > 0
			COMMIT TRANSACTION
			EXEC proc_errorHandler 0, 'PAID TRANSACTION HAS CHANGED TO UNPAID', NULL
        END TRY
		BEGIN CATCH
			ROLLBACK TRANSACTION
			EXEC proc_errorHandler 1, 'UNABLE TO PROCESS THE REQUEST THIS TIME', NULL
		END CATCH
RETURN
END
ELSE IF @flag = 'UnpaidToPaid'
BEGIN
	IF NOT EXISTS(SELECT 'X' FROM remitTran (NOLOCK) WHERE id = @tranIdNew AND tranStatus = 'Payment' and payStatus ='Post')
	BEGIN
		EXEC proc_errorHandler 1,'ONLY PAID TRANSACTION ALLOW TO UPDATE',null
		RETURN
	END
	BEGIN TRY 
		BEGIN TRANSACTION
		SET @viewMsg = 'UNPAID TRANSACTION HAS CHANGED TO PAID BY : '+@user
		EXEC proc_tranViewHistory 'i', @user, @tranIdNew, @controlNo, NULL,'UnpaidToPaid',@viewMsg

		UPDATE remitTran SET
				 tranStatus					= 'Paid'
				,payStatus					= 'Paid'
				,paidDate					= GETDATE()
				,paidDateLocal				= GETDATE()
				,paidBy						= @user
			WHERE id = @tranIdNew

			IF @@TRANCOUNT > 0
			COMMIT TRANSACTION
			EXEC proc_errorHandler 0, 'UNPAID TRANSACTION HAS CHANGED TO PAID', NULL
        END TRY
		BEGIN CATCH
			ROLLBACK TRANSACTION
			EXEC proc_errorHandler 1, 'UNABLE TO PROCESS THE REQUEST FOR THIS TRANSACTION', NULL
		END CATCH
RETURN
END
