SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'WMAN_LogSheet_PutInfo') )
DROP PROCEDURE WMAN_LogSheet_PutInfo
GO

CREATE PROCEDURE WMAN_LogSheet_PutInfo 
	@Marca DATETIME,
	@observaciones VARCHAR(500),
	@id_oper INT,
	@id_datos INT,
	@id_opc INT
AS
BEGIN

	DECLARE @id_terminal INT = ISNULL((SELECT TOP 1 id_terminal FROM Terminales ORDER BY id_terminal ASC), 0)
	
	IF @id_datos = 0
	BEGIN
		SET @id_datos = ISNULL((SELECT TOP 1 da.id_datos 
		                        FROM       Datos       da
		                        INNER JOIN Juegos_Datos en ON da.id_juego = en.id_juego 
		                        WHERE  en.log_sheet = 1
		                        ORDER BY da.id_datos ASC), 0)
	END
	ELSE
	BEGIN
		IF NOT EXISTS  (SELECT da.id_datos 
						FROM       Datos       da
						INNER JOIN Juegos_Datos en ON da.id_juego = en.id_juego 
						WHERE  da.id_datos = @id_datos
						  AND  en.log_sheet = 1)
		BEGIN
			SET @id_datos = 0
		END
	END
	
	IF @id_datos <> 0 AND @id_terminal <> 0
	BEGIN

		INSERT INTO Log_Sheet
		(Marca, id_terminal, observaciones, id_oper, id_datos, id_opc) 
		VALUES (@Marca, @id_terminal, @observaciones, @id_oper, @id_datos, @id_opc)
    
    END
                    
	RETURN

END
GO

