CREATE OR REPLACE PROCEDURE DELETE_RETROFAT
(
	P_NRRETROFAT IN NUMBER,
	P_CDOPERADOR IN VARCHAR2,
	P_NRORG IN NUMBER,
	P_ERRO OUT VARCHAR2
)
AS
	V_CDFILIAL VARCHAR2(4);
	V_CDCLIENTE VARCHAR2(21);
	V_DTINICIAL DATE;
	V_DTFINAL DATE;
	V_NRAPURACFAT VARCHAR2(10);
	V_IDBLOQUEADO VARCHAR2(1);
	V_IDSTATUS VARCHAR2(1);
	V_IDSTATUSNFE VARCHAR2(1);
BEGIN
	SELECT MAX(CDFILIAL), MAX(NRAPURACFAT), MAX(CDCLIENTE), MAX(DTINICIAL), MAX(DTFINAL)
	  INTO V_CDFILIAL, V_NRAPURACFAT, V_CDCLIENTE, V_DTINICIAL, V_DTFINAL
	  FROM RETROFAT
	 WHERE NRRETROFAT = P_NRRETROFAT;

	IF V_CDFILIAL IS NULL THEN
		RETURN;
	END IF;

	-- Verifica o status das notas fiscais
	FOR CURS_NF IN (SELECT CDFILIAL, NRLANCTONF, IDBLOQUEADO, IDSTATUS, IDSTATUSNFE
                     FROM NOTAFISCAL
                    WHERE CDFILIAL = V_CDFILIAL AND
                          NRAPURACFAT = V_NRAPURACFAT) LOOP

		IF CURS_NF.IDBLOQUEADO = 'S' THEN
			P_ERRO := 'NF_BLOQUEADA';
		END IF;
		-- 
		IF CURS_NF.IDSTATUS IN ('E', 'A') THEN
			P_ERRO := 'NF_EMITIDA_APROVADA';
		END IF;

		-- Nota fiscal denegada
		IF CURS_NF.IDSTATUS IN ('C') THEN
			P_ERRO := 'NF_CANCELADA';
		END IF;

		-- Nota fiscal transmitida
		IF CURS_NF.IDSTATUSNFE IN ('A','T','D') THEN
			P_ERRO := 'NF_TRANSMITIDA';
		END IF;

		IF P_ERRO IS NULL THEN
      	DELETA_NF(CURS_NF.CDFILIAL, CURS_NF.NRLANCTONF);
      ELSE
      	RETURN;
      END IF;

      
   END LOOP;	

	IF P_ERRO IS NULL THEN
		
		UPDATE HISTCTRLAPURFAT
		   SET NRRETROFAT = NULL
		 WHERE CDFILIAPUR = V_CDFILIAL
         AND CDCLIENTE = V_CDCLIENTE
         AND DTAPURACAO BETWEEN V_DTINICIAL AND V_DTFINAL
         AND NRRETROFAT = P_NRRETROFAT;

		DELETE FROM CTRLAPURRETROFAT
		 WHERE NRRETROFAT = P_NRRETROFAT;

		DELETE FROM RETROFAT
		 WHERE NRRETROFAT = P_NRRETROFAT;

		DELETE FROM CTRLAPURFAT
		 WHERE CDFILIAL = V_CDFILIAL
		   AND NRAPURACFAT = V_NRAPURACFAT;
	END IF;
END;