﻿

-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date, ,>
-- Description:	<Description, ,>
-- =============================================
CREATE FUNCTION [dbo].[fis_admin_getUserAccount]
(
	@useraccount_id varchar(5)
)
RETURNS @RET TABLE ( [useraccount_id] varchar(5), [auth] smallint, [name] nvarchar(100) null, [firstname] nvarchar(100) null, [email] varchar(255) NULL, [mobile] varchar(50) null, [functions] varchar(1000), [language] varchar(2), [fullname] nvarchar(255) null, [fullname_rev] nvarchar(255) null)
AS
BEGIN
	DECLARE @auth smallint = -1;
	DECLARE @email varchar(255), @name nvarchar(100), @firstname nvarchar(100), @mobile varchar(50), @functions varchar(1000) = '', @title varchar(50), @gender varchar(1), @password varchar(5), @language varchar(2), @fullname nvarchar(255), @fullname_rev nvarchar(255);

	SELECT TOP(1) @useraccount_id = [useraccount_id]
				,@auth		= CASE WHEN [useraccount_id] is null THEN -1 ELSE 1 END
				,@name		= CAST(DECRYPTBYKEY(ua.[name_enc])	as nvarchar(100))
				,@firstname = CAST(DECRYPTBYKEY(ua.[firstname_enc])	as nvarchar(100))
				,@title		= CAST(DECRYPTBYKEY(ua.[title_enc])	as varchar(50))
				,@gender	= CAST(DECRYPTBYKEY(ua.[gender_enc])	as varchar(1))
				--,@password = DECRYPTBYKEY(ua.[password_enc])	
				,@email		= CAST(DECRYPTBYKEY(ua.[email_enc])	as varchar(255))
				,@mobile	= CAST(DECRYPTBYKEY(ua.[mobile_enc])	as varchar(50))
				,@language	= ua.[language]
				,@fullname = [dbo].[fis_admin_getUserName](ua.[name_enc], ua.[firstname_enc], ua.[title_enc])
				,@fullname_rev = [dbo].[fis_admin_getUserName_rev](ua.[name_enc], ua.[firstname_enc], ua.[title_enc])
		FROM [dbo].[fis_useraccounts] as ua
		WHERE ua.[DateDeleted] is null AND ua.[DateDisabled] is null
			AND ua.[useraccount_id] = @useraccount_id;
	
	SET @auth = ISNULL(TRY_CAST((SELECT TOP(1) [value] FROM [fis_useraccounts_settings] WHERE [useraccount_id] = @useraccount_id and [key] = 'intranet_admin') as smallint), @auth);
	SET @functions = STUFF(
						(SELECT ',' + [value] as [text()] FROM [fis_useraccounts_settings] WHERE [useraccount_id] = @useraccount_id and [key] = 'intranet_function' FOR XML PATH(''), TYPE).value('.','nvarchar(max)')
					, 1,1,'');

	INSERT INTO @RET 
		VALUES( 
				 @useraccount_id
				,IIF(@useraccount_id is null, -1, @auth)
				,IIF(@useraccount_id is null, null, @name)
				,IIF(@useraccount_id is null, null, @firstname)
				,IIF(@useraccount_id is null, null, @email)
				,IIF(@useraccount_id is null, null, @mobile)
				,IIF(@useraccount_id is null, null, @functions)
				,IIF(@useraccount_id is null, null, @language)
				,IIF(@useraccount_id is null, null, @fullname)
				,IIF(@useraccount_id is null, null, @fullname_rev)
			  );

	RETURN;

END