CREATE PROCEDURE [dbo].[OnlineUpdateReservationStatus]
  @AReferenceNumber int
  ,@AGuestNumber int
  ,@AStatus int
  ,@AUseDefaultConfirmedState bit = 0
AS
BEGIN
	SET NOCOUNT ON;

	/*
	Changes:
	TBU20150716: Update roomlines status
	*/
	
	declare @CurrentStatus int  -- Find current status for reservation.
	select @CurrentStatus = Status
	  from Reservations
	  where ReferenceNumber = @AReferenceNumber
	    and GuestNumber = @AGuestNumber
		
    select @CurrentStatus = ISNULL(@CurrentStatus,2) -- Default status = 2:Guaranteed.	
	
	declare @PicassoOnlineConfirmedState int  -- Find setting for PicassoOnlineConfirmedState.
	select @PicassoOnlineConfirmedState = keyvalue 
	  from HOTELSETUP with (nolock)
	  where SEARCHKEY = 'PicassoOnlineConfirmedState' 
	
	select @PicassoOnlineConfirmedState = ISNULL(@PicassoOnlineConfirmedState,2) -- 2:Guaranteed.
	
	IF (@AUseDefaultConfirmedState = 0 AND @CurrentStatus < 5)
	BEGIN
	    -- Update status with "status from parameter".
		update Reservations 
		  set Status = @AStatus
		  where ReferenceNumber = @AReferenceNumber
		    and GuestNumber = @AGuestNumber
    END
    else
	IF (@CurrentStatus < 5)
    BEGIN
        -- Update status with "status from Hotelsetup.PicassoOnlineConfirmedState".
		update Reservations 
		  set Status = @PicassoOnlineConfirmedState
		  where ReferenceNumber = @AReferenceNumber
		    and GuestNumber = @AGuestNumber
		
		-- Update roomlines
		update ReservationRoomline set StatusRL = @PicassoOnlineConfirmedState
		where ReservationRoomline.linenumber IN (  select ReservationRoomline.linenumber from ReservationRoomline (nolock)
		INNER JOIN Reservationroomlinextab (NOLOCK) ON Reservationroomlinextab.linenumber = ReservationRoomline.linenumber 
		where Reservationroomlinextab.referencenumber = @AReferenceNumber)
    END
END


