
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER TRIGGER [zapisz_do_reklamy] ON [dbo].[PlatnosciEcard] 
FOR UPDATE
AS
DECLARE @Status bit
DECLARE @dataWplaty datetime
DECLARE @idFaktury int
DECLARE @ORDERNUMBER int
DECLARE @currency INT
DECLARE @amountINT INT

select @ORDERNUMBER = ORDERNUMBER, @Status = Status, @dataWplaty = Status_data, @idFaktury = IDFaktury, @currency=CURRENCY, @amountINT=AMOUNT from inserted
IF @Status = 1
BEGIN

DECLARE @amount DECIMAL(9,2)
SET @amount = CAST(@amountINT AS DECIMAL(9,2))/100
--PRINT CAST(@amount AS NVARCHAR(100))
DECLARE @waluta_miano VARCHAR(3)
DECLARE @amountPLN decimal(9,2)
DECLARE @kurs decimal(9,4)

SELECT @kurs=waluta_kurs FROM Faktury WHERE [id_Faktury]=@idFaktury

SET @waluta_miano= CASE WHEN @currency=978 THEN 'EUR' WHEN  @currency=826 THEN 'GBP' ELSE 'PLN' END

IF(@waluta_miano='PLN')
 SET @amountPLN=@amount
ELSE 
 SET @amountPLN = ROUND(@amount * @kurs, 2)

IF (SELECT COUNT(*) FROM dbo.Wplaty WHERE [idFaktury]=@idFaktury)>0
	BEGIN
	UPDATE dbo.Wplaty 
	SET 
	 [rodzajPotwierdzenia] = 'ECARD', 
	 [symbolPotwierdzenia] = @ordernumber, 
	 [dataWplaty] = @dataWplaty,
	 brutto = @amountPLN,
	 waluta_brutto=@amount,
	 waluta_miano=@waluta_miano
		
	 WHERE [idFaktury] = @idFaktury
	END
ELSE
BEGIN
INSERT INTO dbo.Wplaty([idFaktury], [rodzajPotwierdzenia], [symbolPotwierdzenia], [dataWplaty], [brutto], waluta_brutto, waluta_miano) 
VALUES (@idFaktury, 'ECARD', @ordernumber, @dataWplaty, @amountPLN, @amount, @waluta_miano)
END 

END
GO

SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER OFF
GO

