CREATE PROCEDURE [dbo].[OnlineUpdateSegPos] @Referencenumber INT, @ProductNumber INT, @GuestNumber INT=0, @CustomerNumber int = 0 AS
SET NOCOUNT ON
/*
    Created by Troels Buch Nov 2015
    
    Changes:
	SG 20170524: Added CustomerNumber (Company, if logged in). Set Segment and POS from customer, if not set on product.
    TBU20160713: Added @GuestNumber

    NOTES: 	- 

*/


DECLARE @SetOneSeg BIT
DECLARE @SetOnePos BIT
DECLARE @SegNumber INT
DECLARE @PosNumber INT
DECLARE @CustomerSegment INT
DECLARE @CustomerPOSNumber INT
SET @SegNumber = 0
SET @PosNumber = 0

select @SegNumber=seg.NUMBER, @SetOneSeg=SetOneSegment from SEGMENTS seg with (nolock) 
          inner join ProductSegmentsXTab prosegx with (nolock) on seg.NUMBER = prosegx.SegmentNumber 
		  inner join productextended prox (nolock) on prox.FK_ProductNumber = prosegx.ProductNumber 
         where prosegx.ProductNumber =@ProductNumber and SetOneSegment=1 


select @PosNumber=pos.NUMBER, @SetOnePos=prox.SetOnePOS from POINTOFSALES pos with (nolock) 
          inner join ProductPOSXtab proposx with (nolock) on proposx.PointOfSaleNumber = pos.NUMBER 
		      inner join productextended prox (nolock) on prox.FK_ProductNumber = proposx.ProductNumber 
          where proposx.ProductNumber =@ProductNumber and prox.SetOnePOS=1 

IF @SetOneSeg = 1 AND @SegNumber >0
BEGIN
	UPDATE Reservations SET MarketSegment = @SegNumber 
    WHERE referencenumber = @Referencenumber AND GuestNumber=@GuestNumber 
END ELSE
BEGIN
    IF @CustomerNumber > 0
	BEGIN
	  SELECT @CustomerSegment = SegmentNumber FROM Customer with (nolock) WHERE CustomerNumber = @CustomerNumber
	  UPDATE Reservations SET MarketSegment = @CustomerSegment 
      WHERE referencenumber = @Referencenumber AND GuestNumber=@GuestNumber
	END
END

IF @SetOnePos = 1 AND @PosNumber >0
BEGIN
	UPDATE Reservations SET Pointofsale = @PosNumber 
    WHERE referencenumber = @Referencenumber AND GuestNumber=@GuestNumber 
END ELSE
BEGIN
    IF @CustomerNumber > 0
	BEGIN
	  SELECT @CustomerPOSNumber = PointOfSaleNumber FROM Customer with (nolock) WHERE CustomerNumber = @CustomerNumber
	  UPDATE Reservations SET Pointofsale = @CustomerPOSNumber 
      WHERE referencenumber = @Referencenumber AND GuestNumber=@GuestNumber 
	END
END



