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

CREATE PROCEDURE [dbo].[PROC_CALLBACK_SYNC_STATUS](
	 @Flag			VARCHAR(20)
	,@GTN			VARCHAR(20) = NULL
	,@Provider		VARCHAR(20) = NULL
	,@PartnerPin	VARCHAR(20) = NULL
	,@PayoutStatus	VARCHAR(20) = NULL
	,@PayoutDateTime VARCHAR(20) = NULL
	,@TxnStatus		VARCHAR(20) = NULL
	,@TranId		VARCHAR(20) = NULL
)AS
BEGIN
	IF @Flag='callback-sync'
	BEGIN
		DECLARE @pAgent BIGINT

		SELECT @pAgent = CASE WHEN @Provider='truemoney' THEN 404522 ELSE 0 END

		DECLARE @ENCRYPTEDGTN VARCHAR(30) = DBO.FNAEncryptString(@GTN), @CONTROLNOFORCASH VARCHAR(30)
		,@tranStatus varchar(50)

		SELECT @TRANID = ID, @CONTROLNOFORCASH = controlNo,@tranStatus = tranStatus
		FROM remitTran (NOLOCK) 
		WHERE ContNo = @PartnerPin and controlNo2 = @ENCRYPTEDGTN AND pAgent = @pAgent

		IF @TRANID IS NULL
		BEGIN
			SELECT @TRANID = ID, @CONTROLNOFORCASH = controlNo,@tranStatus = tranStatus
			FROM remitTran (NOLOCK) 
			WHERE controlNo2 = @ENCRYPTEDGTN AND pAgent = @pAgent
		END

		SET @CONTROLNOFORCASH = DBO.FNADecryptString(@CONTROLNOFORCASH)

		--IF @TRANID IS NULL
		--BEGIN
		--	SELECT @TRANID = ID, @CONTROLNOFORCASH = DBO.FNADecryptString(controlNo),@tranStatus = tranStatus
		--	FROM remitTran (NOLOCK) 
		--	WHERE controlNo = DBO.FNAEncryptString(@GTN)
		--END

		--IF @TRANID IS NULL
		--BEGIN
		--	SELECT @TRANID = ID, @CONTROLNOFORCASH = DBO.FNADecryptString(controlNo),@tranStatus = tranStatus
		--	FROM remitTran (NOLOCK) 
		--	WHERE controlNo = DBO.FNAEncryptString(@GTN)
		--END

		--IF @TRANID IS NULL
		--BEGIN
		--	SELECT @TRANID = ID, @CONTROLNOFORCASH = DBO.FNADecryptString(controlNo), @tranStatus = tranStatus
		--	FROM remitTran (NOLOCK) WHERE controlNo2 = DBO.FNAEncryptString(@GTN)
		--END

		IF @TRANID IS NULL
		BEGIN
			EXEC proc_errorHandler 1, 'Transaction not found.', NULL
			RETURN
		END
		IF @tranStatus = 'Cancel'
		BEGIN
			EXEC proc_errorHandler 1, 'Transaction already been cancelled', NULL
			RETURN
		END
		IF @tranStatus = 'Paid'
		BEGIN
			EXEC proc_errorHandler 1, 'Transaction already been Paid', NULL
			RETURN
		END

		IF @PayoutStatus = 'Cancel'
		BEGIN
			EXEC proc_cancelTran @flag = 'cancel', @user = 'system', @controlNo = @CONTROLNOFORCASH, @cancelReason = 'Transaction Rejected from partner', @refund = 'D'	
			EXEC proc_errorHandler 1, 'Transaction cancelled successfully', NULL
			RETURN
		END
		ELSE IF @PayoutStatus = 'Paid'
		BEGIN
			UPDATE remitTran SET payStatus = 'Paid', tranStatus = 'Paid', paidBy = 'system', paidDate = GETDATE()
			WHERE id = @TRANID 
			EXEC proc_errorHandler 1, 'Transaction status synced as paid successfully', NULL
			RETURN
		END
	END    
END
GO
