CREATE PROCEDURE [dbo].[USR_UpdateUser]
	@HttpRequestInfo	NVARCHAR(MAX) = NULL,
	
	@UserId					BIGINT,
	@Email					nvarchar(250) ,
	@UserName				nvarchar(50) ,
	@UserTypeId				tinyint ,
	@Password				varchar(100) ,
	@FirstName				nvarchar(50) ,
	@LastName				nvarchar(50) ,
	@CountryId				int ,
	@PhonePrefix			varchar(20) ,
	@Phone					varchar(50) ,
	@Address				nvarchar(100) ,
	@City					nvarchar(100) ,
	@ZipCode				varchar(16) ,
	@BirthDate				date ,
	@Gender					varchar(50) ,
	@LanguageId				tinyint ,
	@IsUSTaxEntity			bit ,
	@KYCApproved			bit ,
	@TermsOfServiceChecked	bit ,
	@MailVerfied			bit ,
	@PhoneVerified			bit,
	@HasAvatar				bit

	AS

	DECLARE @TranStarted	BIT,
	@ERROR	SMALLINT,
	@RC	INT,
	@RowCount	INT,
	@ErrorMessage	VARCHAR(100),

	@HttpRequestId	BIGINT = NULL,
	@AccountCurrency	CHAR(3),


	@AllowMarketPrimary	BIT = 1,
	@AllowMarketSecondary	BIT = 0,
	@IsDemo	BIT = 0,
	@ExpiryDate	DATETIME2 = NULL


	SET @TranStarted = 0 
	SET @RC	 = 0 
	  
	   
	IF( @@TRANCOUNT = 0 )                        
	BEGIN                        
	  
	 BEGIN TRANSACTION                        
	 SET @TranStarted = 1                        
	END                        
	ELSE                        
	 SET @TranStarted = 0 
	 
	
 BEGIN TRY      

	-- Save HttpRequestId --
	IF @HttpRequestInfo IS NOT NULL
	BEGIN
	INSERT INTO HttpRequests (HttpRequestInfo) VALUES (@HttpRequestInfo)
	SET @HttpRequestId = SCOPE_IDENTITY()
	END

	-- Upadte User --
	UPDATE Users 
	SET FirstName = @FirstName, 
		LastName = @LastName,
		Email = @Email,
		Phone = @Phone,
		PhonePrefix = @PhonePrefix,
		BirthDate = @BirthDate,
		[Address] = @Address,
		City = @City,
		ZipCode = @ZipCode,  
		LanguageId = @LanguageId,
		HasAvatar = @HasAvatar,
		UserName = @UserName
	Where UserId = @UserId -- userid goes from authorization, but email is unique
	
	EXEC REG_GetUsers @UserId;

	IF @TranStarted = 1 
	COMMIT TRANSACTION  
	RETURN 0 

	  
  END TRY 
	 
  BEGIN CATCH  
	   
	IF( @TranStarted = 1 )    
	ROLLBACK TRANSACTION  
	 
	 
	EXEC USP_LogError            
	EXEC USP_RethrowError                       
   
	IF @RC = 0
	SET @RC = 1   ---- Unexpected Error	                        
	RETURN @RC                        
  END CATCH
