CREATE FUNCTION dbo.GetDiscountedPrice (@ABasePrice MONEY, @ADiscountType INT, @ADiscountValue MONEY, @APaxCnt INT) RETURNS MONEY AS
/*
  Created by Kent Johansen october 2014.
  Used for discount products
    TProductDiscountType = (pdtMoney, pdtPercent, pdtNone, pdtPPS);
    TProductPaxType = (pptAll, pptAdult, pptChild1, pptChild2);

  Changes:
    KJ 20200227: Added PPS (Per person sharing)
*/
BEGIN
  DECLARE @Res MONEY
  IF @ABasePrice <= 0
    SET @Res = 0
  ELSE
  BEGIN
    DECLARE @NumberOfDecimals INT
    DECLARE @MinPrice MONEY
    DECLARE @MaxPrice MONEY

    SELECT @NumberOfDecimals = KeyValue FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'NumberOfDecimalsInPrices'
    SET @NumberOfDecimals = ISNULL(@NumberOfDecimals, 2)

    SELECT @MinPrice = KeyValue FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'RoomTypeDifferentialMinPrice'
    SET @MinPrice = ISNULL(@MinPrice, 0)
    SELECT @MaxPrice = KeyValue FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'RoomTypeDifferentialMaxPrice'
    SET @MaxPrice = ISNULL(@MaxPrice, 0)
  
    IF @ADiscountType = 0 -- Money
      SET @Res = ROUND(@ABasePrice - @ADiscountValue, @NumberOfDecimals)
    ELSE IF @ADiscountType = 1 -- Percent
      SET @Res = ROUND(@ABasePrice - (@ABasePrice * (@ADiscountValue/100.0)), @NumberOfDecimals)
    ELSE IF @ADiscountType = 3 -- PPS (Per Person Sharing)
      SET @Res = ROUND(@ABasePrice - (@APaxCnt * @ADiscountValue), @NumberOfDecimals)
  
    IF @MinPrice <> 0 AND @Res < @MinPrice
      SET @Res = @MinPrice
    IF @MaxPrice <> 0 AND @Res > @MaxPrice
      SET @Res = @MaxPrice
  END
  RETURN @Res
END