IF EXISTS ( SELECT 1 FROM SYS.TRIGGERS WHERE NAME = 'TRG_PRC_FILIAL_INTEGRA_PROPZ_EVENTOS' )
BEGIN
	DROP TRIGGER TRG_PRC_FILIAL_INTEGRA_PROPZ_EVENTOS
END
GO

CREATE TRIGGER TRG_PRC_FILIAL_INTEGRA_PROPZ_EVENTOS ON PRC_FILIAL
FOR INSERT, UPDATE 
AS  

	IF EXISTS (SELECT 1 FROM prc_filial_config WHERE CD_CHAVE  = 'PROPZ_HABILITADO' AND VALOR = 1)
	BEGIN
		  UPDATE A SET 
			A.ST_EVENTO = 4 
		  FROM INSERTED I 
		  JOIN INTEGRA_PROPZ_EVENTOS A ON(I.CD_FILIAL = A.CD_REGISTRO)
		  WHERE A.ST_EVENTO = 3
		  AND A.TABELA = 'PRC_FILIAL'

		  INSERT INTO INTEGRA_PROPZ_EVENTOS(TABELA, CD_EMP, CD_FILIAL, CD_REGISTRO, TP_EVENTO, DT_ULT_ALT, CD_USU, DT_DOCUMENTO)
		  SELECT	
			'PRC_FILIAL'                           AS TABELA,
			PRC_FILIAL.CD_EMP                      AS CD_EMP,
			PRC_FILIAL.CD_FILIAL                   AS CD_FILIAL,
			PRC_FILIAL.CD_FILIAL                   AS CD_REGISTRO,
			1                                      AS TP_EVENTO,
			PRC_FILIAL.DT_ULT_ALT                  AS DT_ULT_ALT,
			PRC_FILIAL.CD_USU                      AS CD_USU,
			GETDATE()                              AS DT_DOCUMENTO
		  FROM INSERTED PRC_FILIAL
		  WHERE PRC_FILIAL.CD_EMP = 1;
	END