CREATE PROCEDURE dbo.CreateReceiptAndCheckout @FkFolio INT, @FkUser INT = NULL, @FkDepartment INT = NULL, @IdentityKind INT = 1 AS
SET NOCOUNT ON
/*
nb20240626 New  
Created by Nenad Blagojevic juni 2024
Comments:
Checkout is limited , remark for extended functionality use PE.checkout
*/
DECLARE 
  @PkInvoice INT
exec dbo.CreateReceipt @PkInvoice OUTPUT, @FkFolio, @FkUser, @FkDepartment, @IdentityKind
UPDATE Folios SET OpenFolio = 0 WHERE FolioNumber = @FkFolio
DECLARE @Reference INT, @TableId INT, @LineId INT
select @Reference = ReferenceNumber, @TableId = HL.ConferenceRoomNumber, @LineId = ReservationConfLineNumber 
FROM ReservationConferenceLine HL (nolock) 
  JOIN FolioRestResTableChairsXTab FT (nolock) on FT.RestaurantReservationNumber = ReservationConfLineNumber 
where FT.FolioNumber = @FkFolio
  AND TableBooking = 1 AND TableStatus >= 5
IF ISNULL(@Reference, 0) > 0 and ISNULL(@TableId, 0) > 0 and ISNULL(@LineId, 0) > 0
BEGIN
  UPDATE ReservationConferenceLine SET TableStatus = 6 
  WHERE ReservationConfLineNumber = @LineId AND TableStatus >= 5
  --checkout linked bowling lanes
  UPDATE ReservationConferenceLine SET TableStatus = 6 
  WHERE ReservationConfLineNumber in (
    SELECT ReservationConfLineNumber FROM ReservationConferenceLine HL (nolock)
	  JOIN ConferenceRooms H (nolock) ON HL.ConferenceRoomNumber = H.ConferenceRoomNumber AND H.IsTable = 1 AND H.ConferenceRoomTypeNumber IN (3,9) --[htrtBowling, htrtBowlingSchedule]
    WHERE HL.ReferenceNumber = @Reference AND HL.TableStatus >= 5)
  --Only tablebooking
  IF EXISTS(SELECT R.ReferenceNumber, R.GuestNumber, R.Status
    FROM Reservations R  WITH (NOLOCK)
      LEFT JOIN ReservationRoomLineXTab RLX WITH (NOLOCK) ON RLX.ReferenceNumber = R.ReferenceNumber
      LEFT JOIN ReservationConferenceLine RCL WITH (NOLOCK) ON RCL.ReferenceNumber = R.ReferenceNumber
    WHERE R.ReferenceNumber = @Reference AND RLX.LineNumber IS NULL AND ISNULL(TableBooking,0) = 1) AND 
    (SELECT COUNT(*) FROM Folios (NOLOCK) WHERE ReferenceNumber = @Reference) = 0
  BEGIN    
    DECLARE @RCount INT, @TlCount INT, @HlCount INT, @RlCount INT
    SELECT @RlCount = COUNT(*) FROM ReservationRoomLineXTab  WITH (NOLOCK)
    WHERE ReferenceNumber = @Reference AND GuestNumber = 0
    SELECT @HlCount = COUNT(*) FROM ReservationConferenceLine WITH (NOLOCK)
    WHERE ReferenceNumber = @Reference AND TableBooking = 0
    SELECT @TlCount = COUNT(*) FROM ReservationConferenceLine WITH (NOLOCK)
    WHERE ReferenceNumber = @Reference AND TableBooking = 1
    SELECT @RCount = COUNT(*) FROM Reservations  WITH (NOLOCK)
    WHERE ReferenceNumber = @Reference AND GuestNumber > 0 AND Status < 6
      AND ISNULL(ArrivalDate, '') <> ''
    IF @RlCount = 0 AND @HlCount = 0 AND @RCount = 0 AND @TlCount = 1
	  UPDATE Reservations SET Status = 6 WHERE ReferenceNumber = @Reference AND GuestNumber = 0 and Status = 5
  END
END
