CREATE FUNCTION dbo.GetDiscountedWarePrice (@AWarePrice MONEY, @AReferenceNumber INT, @AGuestNumber INT, @AWareNumber INT, @AAddressType SMALLINT) RETURNS MONEY AS
BEGIN
  /*
    Created by Kent Johansen, October 2023
    Calculate discount.
    Does not use splitbill to get correct addresstype.
    Changes:
  */
  DECLARE @LUserIDNumber INT
  DECLARE @LFolioNumber INT
  
  DECLARE @LDiscountRate SMALLMONEY
  DECLARE @LDiscountIsFixedAmount BIT
  DECLARE @LPrice MONEY

  DECLARE @LAllDiscount FLOAT
  DECLARE @LAllDiscountIsFixedAmount BIT
  DECLARE @LExtraDiscount FLOAT
  DECLARE @LExtraDiscountIsFixedAmount BIT
  DECLARE @LWareDiscount FLOAT
  DECLARE @LWareDiscountIsFixedAmount BIT

  SELECT 
    @LAllDiscount = Reservationaddress.DiscountRate,
    @LAllDiscountIsFixedAmount = Reservationaddress.AllDiscountIsFixedAmount,
    @LExtraDiscount = Reservationaddress.ExtrasDiscountRate,
    @LExtraDiscountIsFixedAmount = ReservationAddress.ExtraDicountIsFixedAmount,
    @LWareDiscount = ReservationAddressWareDiscountXtab.DiscountValue,
    @LWareDiscountIsFixedAmount = ReservationAddressWareDiscountXtab.IsFixedAmount
  FROM Reservationaddress WITH (NOLOCK) 
  INNER JOIN ReservationAddressXTab WITH (NOLOCK) ON ReservationAddressXTab.AddressNumber = ReservationAddress.AddressNumber
    AND ReservationAddressXTab.ReferenceNumber = @AReferenceNumber
    AND ReservationAddressXTab.GuestNumber = @AGuestNumber
    AND ReservationAddress.AddressType = @AAddressType
  LEFT OUTER JOIN ReservationAddressWareDiscountXtab WITH (NOLOCK) ON ReservationAddressWareDiscountXtab.FK_ReservationAddressNumber = ReservationAddress.AddressNumber
    AND ReservationAddressWareDiscountXtab.FK_WareNumber = @AWareNumber

  IF ISNULL(@LWareDiscount, 0) <> 0
  BEGIN
    SET @LDiscountRate = @LWareDiscount
    SET @LDiscountIsFixedAmount = @LWareDiscountIsFixedAmount
  END
  ELSE IF ISNULL(@LExtraDiscount, 0) <> 0
  BEGIN
    SET @LDiscountRate = @LExtraDiscount
    SET @LDiscountIsFixedAmount = @LExtraDiscountIsFixedAmount
  END
  ELSE IF ISNULL(@LAllDiscount, 0) <> 0
  BEGIN
    SET @LDiscountRate = @LAllDiscount
    SET @LDiscountIsFixedAmount = @LAllDiscountIsFixedAmount
  END
  ELSE
  BEGIN
    SET @LDiscountRate = 0
    SET @LDiscountIsFixedAmount = 0
  END

  IF ISNULL(@LDiscountRate, 0) <> 0
  BEGIN
    IF @LDiscountIsFixedAmount = 1
      SET @LPrice = @AWarePrice - @LDiscountRate
    ELSE
      SET @LPrice = @AWarePrice - ROUND(((@AWarePrice) * (@LDiscountRate/100)), 2)
  END
  ELSE
    SET @LPrice = @AWarePrice

  RETURN @LPrice
END