CREATE PROCEDURE dbo.CanChargeTableReservation @ADate CHAR(8), @AReferenceNumber int, @AGuestNumber int AS
BEGIN
  SET NOCOUNT ON
  /*
  20220519 RN Created
  */

  DECLARE @TableLineCount int
  DECLARE @ResConfLineNbr int
  DECLARE @ExtrasCount int
  DECLARE @ProductCount int
  DECLARE @Result bit

  SET @Result = 0
  SET @ExtrasCount = 0
  SET @ProductCount = 0

  SELECT
    @TableLineCount = COUNT(*)
  FROM ReservationConferenceLine WITH (NOLOCK)
  LEFT OUTER JOIN ConferenceRooms WITH (NOLOCK) ON ReservationConferenceLine.ConferenceRoomNumber = ConferenceRooms.ConferenceRoomNumber
  INNER JOIN CONFERENCEROOMTYPES WITH (NOLOCK) ON ReservationConferenceLine.BookedConferenceRoomTypeNumber = ConferenceRoomTypes.ConferenceRoomTypeNumber AND ConferenceRoomTypes.ResourceType NOT IN (3,9) -- do not select bowling resourcetypes
  LEFT OUTER JOIN ReservationConferenceLine RCL (NOLOCK) ON RCL.ReferenceNumber = ReservationConferenceLine.ReferenceNumber AND RCL.GuestNo = ReservationConferenceLine.GuestNo AND ISNULL(RCL.TableBooking, 0) = 0
  LEFT OUTER JOIN ReservationRoomlineXtab on ReservationRoomlineXtab.ReferenceNumber = ReservationConferenceLine.ReferenceNumber
  WHERE (1=1)
    AND ReservationConferenceLine.ReferenceNumber = @AReferenceNumber
    AND ReservationConferenceLine.GuestNo = @AGuestNumber
    AND ReservationConferenceLine.TableBooking = 1
    AND ISNULL(ReservationConferenceLine.TableStatus, -1) < 6
    --AND ReservationConferenceLine.ArrivalDate = @ADate
    AND ReservationRoomlineXtab.ReferenceNumber is null
    AND ISNULL(RCL.ReferenceNumber, -999) = -999


  IF @TableLineCount > 0
  BEGIN
    SELECT @ExtrasCount = COUNT(*)
    FROM ArrangementLines (NOLOCK)
    INNER JOIN ArrangementReservationsXtab (NOLOCK) ON ArrangementLines.ArrangementLineNumber = ArrangementReservationsXtab.ArrangementLineNumber
    WHERE ArrangementReservationsXtab.ReferenceNumber = @AReferenceNumber
      AND ArrangementReservationsXtab.GuestNumber = @AGuestNumber
	  AND ArrangementLines.Date = @ADate
	  AND ISNULL(ArrangementLines.PacketItemNumber,0 ) = 0

    SELECT @ProductCount = COUNT(*)
    FROM ReservationConferenceLine (NOLOCK)
    WHERE ReservationConferenceLine.ReferenceNumber = @AReferenceNumber
      AND ReservationConferenceLine.GuestNo = @AGuestNumber
	  AND ISNULL(ReservationConferenceLine.TableBooking, 0) = 1
	  AND ISNULL(ReservationConferenceLine.TableStatus, -1) <= 5
	  AND ISNULL(RESERVATIONCONFERENCELINE.ProductNumber, 0) > 0
  END

--  print 'Tablecount: ' + convert(varchar(10), @tableLINEcount)
--  print 'ExtrasCount: ' + CONVERT(varchar(10), @extrascount)
--  print 'ProductCount: ' + CONVERT(varchar(10), @productCount)

  IF (@ExtrasCount > 0) OR (@ProductCount > 0)
    SET @Result = 1

  SELECT @Result
END