﻿--SELECT 
--    name AS TriggerName,
--    OBJECT_NAME(parent_id) AS TableName,
--    type_desc AS TriggerType
--FROM 
--    sys.triggers
--WHERE 
--    parent_class_desc = 'OBJECT_OR_COLUMN';
--SELECT 
--    name AS TriggerName,
--    OBJECT_NAME(parent_id) AS TableName,
--    type_desc AS TriggerType
--FROM 
--    sys.triggers
--WHERE 
--    parent_class_desc = 'OBJECT_OR_COLUMN'
--    AND OBJECT_NAME(parent_id) = 'PO'; -- Replace 'PO' with your table name if different

--SELECT 
  --  OBJECT_DEFINITION(OBJECT_ID('TrgUpdatePRDetails')) AS TriggerDefinition; -- to View the Trigger

CREATE TRIGGER TrgUpdatePRDetails
ON [dbo].[PO]
AFTER UPDATE
AS
BEGIN
    DECLARE @PONo BIGINT;
    
    -- Check if the updated column is IsPOClosed and it has been set to TRUE (1)
    IF UPDATE(IsPOClosed)
    BEGIN
        -- Get the PONo from the updated row where IsPOClosed is set to TRUE (1)
        SELECT @PONo = PONo
        FROM inserted
        WHERE IsPOClosed = 1;

        -- If we have a PONo, update the PRDetails
        IF @PONo IS NOT NULL
        BEGIN
            UPDATE [dbo].[PRDetails]
            SET Status = 17
            WHERE PRDetailsId IN (
                SELECT CD.PRDetailsId 
                FROM [dbo].[PO] PO
                LEFT JOIN [dbo].[PODetails] POD ON PO.POId = POD.POId
                LEFT JOIN [dbo].[ApprovedSuppliers] ASS ON POD.PODetailId = ASS.PODetailId
                LEFT JOIN [dbo].[CanvassDetails] CD ON ASS.CanvassDetailId = CD.CanvassDetailId
                WHERE PO.PONo = @PONo
            );
        END
    END
END
GO

CREATE TRIGGER TrgInsertIventTransaction
ON [dbo].[RequestItems]
AFTER INSERT
AS
BEGIN

DECLARE @QtyRequested INT,@InventoryId INT,@UserId VARCHAR(450),
	@InventTransId BIGINT,@UserName VARCHAR(50),@FullName VARCHAR(100);	
	
DECLARE @InsertedInvIds TABLE (InvID BIGINT);	
    
        -- Get the PONo from the updated row where IsPOClosed is set to TRUE (1)
        SELECT @InventoryId = InventoryId,
		@UserId=UserId,
		@QtyRequested=QtyRequest
        FROM inserted
        WHERE IsActive = 1 AND Status=19;

			 SELECT @UserName=U.UserName
					FROM Users U
					LEFT JOIN [dbo].[UserRoles] UR ON U.Id=UR.UserId 
					LEFT JOIN Roles R ON UR.RoleId=R.Id 
					WHERE U.Id=@UserId;

        -- If we have a PONo, update the PRDetails
        IF @InventoryId IS NOT NULL
        BEGIN

			  INSERT INTO [dbo].[InventTrans]	    
			  ([InventoryId],[CreatedBy])
			  OUTPUT INSERTED.InventTransId INTO @InsertedInvIds(InvID)
				VALUES
			   (@InventoryId,@FullName);

				SELECT @InventTransId=InvID FROM @InsertedInvIds;

			   INSERT INTO [dbo].[InventTransDetail]	   
			  ([InventTransId] ,[TransTypeId] ,[QtyIn] ,[QtyOut],CreatedDate ,[IsActive])
			  VALUES
			  (@InventTransId,3,@QtyRequested,0,GETDATE(),1);
        END
END
GO