IF OBJECT_ID ('TRG_GLB_TRIB_PIS_COFINS_REGIME_PDV_PEND', 'TR') IS NOT NULL
BEGIN
	DROP TRIGGER TRG_GLB_TRIB_PIS_COFINS_REGIME_PDV_PEND
END
GO

CREATE TRIGGER [dbo].[TRG_GLB_TRIB_PIS_COFINS_REGIME_PDV_PEND] ON [dbo].[GLB_TRIB_PIS_COFINS_REGIME] FOR INSERT,UPDATE AS
BEGIN	

BEGIN TRY

	 INSERT INTO EST_PROD_PRC_REGIAO_FISCAL_TRIB_EST_PEND
	 SELECT DISTINCT A.CD_EMP, REG.CD_REGIAO_FISCAL, B.CD_PROD, 0 AS CD_CTR, GETDATE()
			FROM INSERTED A 
			INNER JOIN EST_PROD B on A.CD_EMP = B.CD_EMP
			AND A.TIPO_TRIBUTACAO = B.TIPO_TRIBUTACAO_PIS_COFINS
			AND A.CD_LISTA = B.LISTA_PROD
			CROSS APPLY (SELECT DISTINCT CD_REGIAO_FISCAL 
						 FROM EST_PROD_PRC_REGIAO_FISCAL_TRIB_EST) REG
			WHERE TP_TRANSA = 1
			AND B.STS_PROD <> 1
			AND NOT EXISTS (SELECT 1 
								FROM EST_PROD_PRC_REGIAO_FISCAL_TRIB_EST_PEND P
								WHERE P.CD_EMP = A.CD_EMP
										AND P.CD_REGIAO_FISCAL = REG.CD_REGIAO_FISCAL
										AND P.CD_PROD = B.CD_PROD
										AND P.CD_CTR  = 0)
END TRY
BEGIN CATCH
	PRINT 1
END CATCH

END



