--SELECT * FROM RC_DEB_CLI_PDV_PEND
--SELECT TOP 1 * FROM RC_DEB_CLI_PDV ORDER BY CD_CTR DESC
--INSERT INTO RC_DEB_CLI_PDV_PEND (CD_EMP,CD_CLI) SELECT CD_EMP,CD_CLI FROM RC_DEB_CLI_PDV
--DROP PROCEDURE P_GERA_RC_DEB_CLI_PDV
IF OBJECT_ID('P_GERA_RC_DEB_CLI_PDV') IS NOT NULL
	BEGIN
			DROP PROCEDURE P_GERA_RC_DEB_CLI_PDV
	END

GO

CREATE PROCEDURE P_GERA_RC_DEB_CLI_PDV
AS
SET NOCOUNT ON
	BEGIN
			DECLARE @CD_CTR     BIGINT,
							@CD_EMP     INT,
							@CD_CLI     INT,
							@CD_CTR_XML BIGINT,
							@FAT_XML    XML
			DECLARE PENDENTES CURSOR FAST_FORWARD FOR
				SELECT
					P.CD_CTR
					,P.CD_EMP
					,P.CD_CLI
					,X.CD_CTR AS CD_CTR_XML
				FROM
					RC_DEB_CLI_PDV_PEND P
					LEFT JOIN RC_DEB_CLI_PDV X ON
						P.CD_EMP = X.CD_EMP AND
						P.CD_CLI = X.CD_CLI

			OPEN PENDENTES

			FETCH NEXT FROM PENDENTES INTO @CD_CTR, @CD_EMP, @CD_CLI, @CD_CTR_XML

			WHILE @@FETCH_STATUS = 0
				BEGIN
						EXECUTE P_GERA_RC_CREDIARIO_FECHA_CLIENTE @CD_CLI;

						SET @FAT_XML = ISNULL((SELECT * FROM dbo.UFD_RC_DEB_CLI_PDV(@CD_EMP, @CD_CLI, 0)
																	 FOR XML PATH('RC_DEB'), ROOT('FAT_XML')), '<FAT_XML><MSG>CLIENTE NAO POSSUI DEBITOS PENDENTES</MSG></FAT_XML>')

						IF @FAT_XML IS NULL --NAO EXISTE SALDO PENDENTE
							BEGIN
									IF @CD_CTR_XML > 0
										DELETE FROM RC_DEB_CLI_PDV
										WHERE  CD_CTR = @CD_CTR_XML
							END
						ELSE
							BEGIN
									IF @CD_CTR_XML > 0 --POSSUI XML
										UPDATE RC_DEB_CLI_PDV
										SET    FAT_XML = @FAT_XML,
													 DT_ALT = GETDATE()
										WHERE
											CD_CTR = @CD_CTR_XML
									ELSE
										INSERT INTO RC_DEB_CLI_PDV
																(CD_EMP,
																 CD_CLI,
																 FAT_XML)
										VALUES      (@CD_EMP,
																 @CD_CLI,
																 @FAT_XML)
							END

						--DELETA PENDENCIA
						DELETE FROM RC_DEB_CLI_PDV_PEND
						WHERE  CD_CTR = @CD_CTR

						FETCH NEXT FROM PENDENTES INTO @CD_CTR, @CD_EMP, @CD_CLI, @CD_CTR_XML
				END

			CLOSE PENDENTES

			DEALLOCATE PENDENTES
	END 
