CREATE PROCEDURE DBO.GetDiscountRateWare @AReferenceNumber INT, @AGuestNumber SMALLINT, @AWareNumber INT, @AAddressTypeNumber TINYINT, @ADiscountRate FLOAT OUTPUT, @ADiscountIsFixedAmount BIT OUTPUT AS
SET NOCOUNT ON
/*
  Create by Kent Johansen, July 2023
  Changes:

*/

DECLARE @WareDiscount FLOAT
DECLARE @WareDiscountIsFixedAmount BIT
DECLARE @AllDiscount FLOAT
DECLARE @AllDiscountIsFixedAmount BIT
DECLARE @ExtraDiscount FLOAT
DECLARE @ExtraDiscountIsFixedAmount BIT
DECLARE @LDiscountAllowed BIT

SELECT 
  @AllDiscount = Reservationaddress.DiscountRate,
  @AllDiscountIsFixedAmount = Reservationaddress.AllDiscountIsFixedAmount,
  @ExtraDiscount = Reservationaddress.ExtrasDiscountRate,
  @ExtraDiscountIsFixedAmount = ReservationAddress.ExtraDicountIsFixedAmount,
  @WareDiscount = ReservationAddressWareDiscountXtab.DiscountValue,
  @WareDiscountIsFixedAmount = ReservationAddressWareDiscountXtab.IsFixedAmount
FROM Reservationaddress WITH (NOLOCK) 
INNER JOIN ReservationAddressXTab WITH (NOLOCK) ON ReservationAddressXTab.AddressNumber = ReservationAddress.AddressNumber
  AND ReservationAddressXTab.ReferenceNumber = @AReferenceNumber
  AND ReservationAddressXTab.GuestNumber = @AGuestNumber
LEFT OUTER JOIN ReservationAddressWareDiscountXtab WITH (NOLOCK) ON ReservationAddressWareDiscountXtab.FK_ReservationAddressNumber = ReservationAddress.AddressNumber
  AND ReservationAddressWareDiscountXtab.FK_WareNumber = @AWareNumber
WHERE ReservationAddress.AddressType = @AAddressTypeNumber

SELECT @LDiscountAllowed = Ware.ReservationDiscount FROM Ware WITH (NOLOCK) WHERE WareNumber = @AWareNumber

SET @ADiscountRate = 0
SET @ADiscountIsFixedAmount = 0

IF @LDiscountAllowed = 1
BEGIN
  IF ISNULL(@WareDiscount, 0) <> 0
  BEGIN
    SET @ADiscountRate = @WareDiscount
    SET @ADiscountIsFixedAmount = @WareDiscountIsFixedAmount
  END
  ELSE IF ISNULL(@ExtraDiscount, 0) <> 0
  BEGIN
    SET @ADiscountRate = @ExtraDiscount
    SET @ADiscountIsFixedAmount = @ExtraDiscountIsFixedAmount
  END
  ELSE IF ISNULL(@AllDiscount, 0) <> 0
  BEGIN
    SET @ADiscountRate = @AllDiscount
    SET @ADiscountIsFixedAmount = @AllDiscountIsFixedAmount
  END
END