CREATE PROCEDURE [dbo].[USR_Users_RegisterNewUser]

    @HttpRequestInfo           nvarchar(max) ,
    @CreateIPAddress           varchar(50) ,
	@ApiConsumerId             int,
	@UserName                  nvarchar(250) ,
	@Email                     nvarchar(250) ,
    @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 ,
    --@CreateOrigin             sysname ,    
    --@Source                   varchar(max) ,
    --@TermsOfServiceChecked    bit ,
    --@MailVerfied              bit ,
    --@PhoneVerified            bit,
    @NewUserFreeCreditAmount  decimal(22, 8) = NULL



AS

----------------------------------------------------------------------------
-------------- Changed By : Yoav Pinkas 2018-04-17
-------------- Adding Error Handler (Try/Catch) and Logical Transaction
----------------------------------------------------------------------------

/*
---- Example:
DECLARE @RC int
DECLARE @Email nvarchar(250) = 'yoav.pinkas@gmail.com'
DECLARE @UserTypeId tinyint =  0,	----Real
DECLARE @Password varchar(100) = 'ÁAABBBCCC' 
DECLARE @FirstName nvarchar(50) = 'Yoav' 
DECLARE @LastName nvarchar(50) = 'Pinkas' 
DECLARE @CountryId int = 104 --- Israel
DECLARE @PhonePrefix varchar(20) = '+972' 
DECLARE @Phone varchar(50) = '541223344'
DECLARE @Address nvarchar(100) = 'Hanavi Yerucham 28'
DECLARE @City nvarchar(100) = 'Bney-Brak'
DECLARE @ZipCode varchar(16) = '55900'
DECLARE @BirthDate date = '1966-12-01'
DECLARE @Gender varchar(50) = 1 -- Male
DECLARE @LanguageId tinyint  = 27 -- Hebrew
DECLARE @IsUSTaxEntity bit = 0
DECLARE @KYC_Approved bit = 0 

DECLARE @CreateIPAddress varchar(50)
DECLARE @Source varchar(max)
DECLARE @TermsOfServiceChecked bit
DECLARE @MailVerfied bit
DECLARE @PhoneVerified bit

-- TODO: Set parameter values here.

EXECUTE @RC = [dbo].[USR_Users_RegisterNewUser] 
   @Email
  ,@UserTypeId
  ,@Password
  ,@FirstName
  ,@LastName
  ,@CountryId
  ,@PhonePrefix
  ,@Phone
  ,@Address
  ,@City
  ,@ZipCode
  ,@BirthDate
  ,@Gender
  ,@LanguageId
  ,@IsUSTaxEntity
  ,@KYC_Approved
  ,@CreateDate
  ,@CreateOrigin
  ,@CreateIPAddress
  ,@Source
  ,@TermsOfServiceChecked
  ,@MailVerfied
  ,@PhoneVerified
GO
*/


    DECLARE	@UserId						BIGINT,
			@AccountId					BIGINT,
            @UserRoleId					tinyint = 0,  --- Regular
            @AccountCurrencySymbol		varchar(30) = 'KNOKS',
            @RegistrationDate			datetime2,
            @HttpRequestId				BIGINT,
			@PlatformUserId				bigint,
			@PlatformAccountId			bigint,

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



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

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

            INSERT INTO [dbo].[Users]
                       ([UserRoleId]
                       ,[Email]
                       ,[UserTypeId]
					   ,[UserName]
                       ,[Password]
                       --,[FirstName]
                       --,[LastName]
                       --,[CountryId]
                       --,[PhonePrefix]
                       --,[Phone]
                       --,[Address]
                       --,[City]
                       --,[ZipCode]
                       --,[BirthDate]
                       --,[Gender]
                       --,[LanguageId]
                       --,[IsUSTaxEntity]
                       --,[RegistrationDate]
                       --,[KYC_Approved]
                       ,[CreateDate]
                       ,[CreateOrigin]
                       ,[CreateIPAddress]
                       ,[Source]
                       --,[TermsOfServiceChecked]
                       --,[MailVerfied]
                       --,[PhoneVerified]
                       ,[ApiConsumerId]
                       ,[HttpRequestId]
					   ,[Rank])
                VALUES(
                        @UserRoleId            
                       ,@Email                
                       ,@UserTypeId  
					   ,@UserName
                       ,@Password                
                       --,@FirstName            
                       --,@LastName                
                       --,@CountryId                
                       --,@PhonePrefix            
                       --,@Phone                
                       --,@Address            
                       --,@City                    
                       --,@ZipCode                
                       --,@BirthDate            
                       --,@Gender                
                       --,@LanguageId            
                       --,@IsUSTaxEntity            
                       --,@RegistrationDate    
                       --,@KYCApproved        
                       ,GETUTCDATE()        
                       ,0 --@CreateOrigin        
                       ,@CreateIPAddress    
                       ,'web' -- @Source                
                       --,@TermsOfServiceChecked
                       --,@MailVerfied        
                       --,@PhoneVerified
                       ,@ApiConsumerId
                       ,@HttpRequestId
					   ,0) -- Padawan

			SELECT @UserId = SCOPE_IDENTITY()


            INSERT INTO [dbo].[Accounts]
                       ([UserId]
                       ,[Symbol]
                       ,[CurrentBalance]
                       ,[CurrentBonusBalance]
                       ,[TotalPending]
                       ,[CreateDate]
					   ,[WalletAddress]
                        )
            VALUES(
                       @UserId
                      ,@AccountCurrencySymbol
                      ,0
                      ,0
                      ,0
                      ,GetDate()
					  ,'')

			SELECT @AccountId = SCOPE_IDENTITY()
			
		IF @NewUserFreeCreditAmount IS NOT NULL AND @NewUserFreeCreditAmount > 0
		BEGIN
		--Token Credit
			SELECT @PlatformUserId = [UserId] FROM Users WHERE [UserTypeId] = 2 --Platform
			SET @PlatformAccountId = (SELECT TOP 1 [AccountId] FROM [Accounts] WHERE [UserId] = @PlatformUserId)

			EXEC	[dbo].[TRN_Account_TransferMoney]
							@FromUserId = @PlatformUserId,
							@FromAccountId = @PlatformAccountId,
							@FromExternalReferenceId = NULL,
							@FromWalletAddress = NULL,
							@FromAccountTransactionTypeId = 1, --FreeTokensCredit
							@ToUserId = @UserId,
							@ToAccountId = @AccountId,
							@ToExternalReferenceId = NULL,
							@ToWalletAddress = NULL,
							@ToAccountTransactionTypeId = 1, --FreeTokensCredit
							@Amount = @NewUserFreeCreditAmount,
							@AmountUSD = NULL,
							@OperatorId = NULL,
							@Comment = NULL,
							@PendingId = NULL,
							@KnokId = NULL
		END

			IF( @TranStarted = 1 )            
				COMMIT TRANSACTION            



            EXECUTE USR_Users_GetData    @UserId

			RETURN 0

END TRY           
BEGIN CATCH            
    IF( @TranStarted = 1 )            
		ROLLBACK TRANSACTION            

	EXEC [USP_LogError]           
	EXEC [USP_RethrowError]   
	
	IF @RC = 0 
		SET @RC = 1			         
	RETURN @RC
END CATCH
