IF EXISTS (SELECT * FROM dbo.SysObjects WHERE id = object_id(N'dbo.TRIGGER_FolioAfterInsert') AND OBJECTPROPERTY(id, N'IsTrigger') = 1) DROP TRIGGER dbo.TRIGGER_FolioAfterInsert 
GO
CREATE TRIGGER dbo.TRIGGER_FolioAfterInsert ON dbo.Folios AFTER INSERT AS 
/*
  NB20191011 Created
  FolioBonuscardUpdate from Reservation Guest Address
*/
BEGIN
  SET NOCOUNT ON;
  DECLARE @HotelCustomerNumber INT, @AddressNumber INT, @ReferenceNumber INT, @GuestNumber INT
  --, @Msg VARCHAR(200)
  SELECT @HotelCustomerNumber = HotelCustomerNumber, @AddressNumber = ISNULL(ReservationAddressNumber, 0), @ReferenceNumber = ISNULL(ReferenceNumber, 0),
    @GuestNumber = ISNULL(GuestNumber, 0)
  FROM INSERTED
  IF (SELECT dbo.GetHotelSetupKeyValue('BonusSystemEnabled', @HotelCustomerNumber)) = 1 --bonuscard system enabled
    --on subreservations or single reservations 
    AND (@ReferenceNumber > 0 and (@GuestNumber > 0 or (SELECT COUNT(*) as ResCount FROM Reservations (NOLOCK) WHERE ReferenceNumber = @ReferenceNumber AND    
      ISNULL(ArrivalDate, '') <> '') = 1) --nb20080924 Exclude invalid records.  
	--or on invoices 
	OR (@ReferenceNumber = 0 and @AddressNumber > 0)) 
  BEGIN
    DECLARE @PkCardNew INT
    SELECT TOP 1 @PkCardNew = CCX.FK_Card FROM ReservationAddressXTab RAX (NOLOCK) 
      INNER JOIN ReservationAddress RA (NOLOCK) ON RAX.AddressNumber = RA.AddressNumber AND RA.AddressType = 1
      INNER JOIN dbo.Customer C (NOLOCK) ON RA.Link = C.CustomerNumber
      INNER JOIN dbo.CustomerCardXTab CCX (NOLOCK) ON CCX.CustomerNumber = C.CustomerNumber
    WHERE RAX.ReferenceNumber = @ReferenceNumber AND RAX.GuestNumber = @GuestNumber
	IF ISNULL(@PkCardNew, 0) > 0
	  EXEC dbo.FolioBonuscardUpdate @ReferenceNumber, @GuestNumber, NULL, @PkCardNew
  END
--  SET @Msg = CONVERT(VARCHAR, @PkCardNew)+', '+CONVERT(VARCHAR, @ReferenceNumber)+', '+CONVERT(VARCHAR, @GuestNumber)
--  RAISERROR (@Msg, 15, 1);   

END
