CREATE PROCEDURE dbo.RecurringPatternWareAvailable @AWareNumber INT, @AStartDateTime DATETIME, @AEndDateTime DATETIME, @AAvailable INT OUTPUT, @AArrangementlineID INT = -1 AS
SET NOCOUNT ON

-- TODO: Support for menu ware

/*Last Changed:
  MLJ 2022-10-10 Updated after change to resultset from dbo.RecurringPatternAvailableWares
  MLJ 2022-07-29 Now implemented by calling dbo.RecurringPatternAvailableWares
  KJ 20220712: Ext: Availability on transactions
  KJ 20220530: Bug Fix for "Still possible to book even if recurringpattern specified deleted for a single period". Case #CR218831
  RN 20210212: CR204839, Added DISTINCT ArrangementLineNumber
  KJ 20201208: Error in get number of sold.
  KJ 20201201: Total rewrite to handle custom period on Arr lines
  RN 2017 0908 Added ArrangementlineID as parameter and using it on SQL.
  AV 2008 0722 Return number of available units insted of true false
  AV 2008 0701
*/

DECLARE @DayStarts VARCHAR(5)
SELECT @DayStarts = KeyValue FROM HotelSetup WITH (NOLOCK) WHERE SearchKey = 'Arr24Hoursstarts'
IF ISNULL(@DayStarts,'') = ''
	SET @DayStarts = '07:00'

IF CONVERT(VARCHAR(5), @AStartDateTime, 108) < @DayStarts
  SET @AStartDateTime = DATEADD(DAY, 1, @AStartDateTime)
   
IF CONVERT(VARCHAR(5), @AEndDateTime, 108) < @DayStarts
  SET @AEndDateTime = DATEADD(DAY, 1, @AEndDateTime)

DECLARE @WarePeriods [RecurringPatternAvailableWaresTable]
INSERT INTO @WarePeriods VALUES (@AWareNumber, @AStartDateTime, @AEndDateTime, @AArrangementlineID)
DECLARE @Result TABLE
(
	WareNumber int, 
	StartDateTime datetime, 
	EndDateTime datetime, 
	Available int,
	WareLinkGroupID int
)
INSERT INTO @Result
EXEC [dbo].[RecurringPatternAvailableWares] @WarePeriods
SELECT @AAvailable=MIN(Available) FROM @Result
