USE [EXP_V4_ASP]
GO
/** Object:  Trigger [dbo].[LoyaltyMasters]    Script Date: 12/26/2024 12:31:25 PM **/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER TRIGGER [dbo].[LoyaltyMasters] 
ON [dbo].[LoyaltyCustomer] 
AFTER INSERT, UPDATE
AS
BEGIN
    BEGIN TRY
        DECLARE
            @CustomerID VARCHAR(20),
            @MobileNo VARCHAR(13),
            @Fname VARCHAR(20),
            @URL NVARCHAR(MAX) = 'http://172.105.61.92:3005/api/loyality_master',
            @Object INT,
            @Body VARCHAR(MAX),
            @loyalty_point  INT;

        -- Handle both INSERT and UPDATE operations
        SELECT 
            @MobileNo = inserted.Mobile, 
            @CustomerID = LTRIM(RTRIM(inserted.cust_Code)), 
            @Fname = inserted.first_name,
            @loyalty_point = 0
        FROM inserted;

        SET @Body = '{
            "mobile_no" :  "+974' + RIGHT(LTRIM(RTRIM(@MobileNo)), 9) + '",
            "user_id" : "' + @CustomerID + '",
            "name" : "' + @Fname + '",
            "total_points" : ' + CAST(@loyalty_point AS VARCHAR) + ',
            "loyality_group" : "GREEN"
        }';

        EXEC sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
        EXEC sp_OAMethod @Object, 'open', NULL, 'post', @URL, 'false';
        EXEC sp_OAMethod @Object, 'setRequestHeader', NULL, 'Content-Type', 'application/json';
        EXEC sp_OAMethod @Object, 'send', NULL, @Body;
        EXEC sp_OADestroy @Object;
    END TRY
    BEGIN CATCH
        -- Log or handle errors
        DECLARE @ErrorMessage NVARCHAR(4000) = ERROR_MESSAGE();
        RAISERROR(@ErrorMessage, 16, 1);
    END CATCH;
END