﻿-- =============================================
-- Author:		<Author,,Name>
-- Create date: <Create Date,,>
-- Description:	<Description,,>
-- =============================================
CREATE PROCEDURE [dbo].[fds__createReminder]
	@InvId varchar(15)
	, @type varchar(3)
	, @amount numeric(10,3)
	, @amount_payed numeric(10,3)
	, @SendToAddress [nvarchar](1000)
	, @SendToEmail [nvarchar](255)
	, @subject nvarchar(255)
	, @text nvarchar(2000)
	, @authuser varchar(25)
	, @Id varchar(10) OUT
	
AS
BEGIN
	SET NOCOUNT ON;

    
	IF [dbo].[fis_getModuleAuth]('fds_reminder', @authuser) < 2
		THROW 60000, N'not authorized', 1;  

	INSERT INTO [dbo].[fds__admin_activity] ([activity] ,[authuser] ,[info])
		VALUES ('fds__createReminder' ,@authuser , 'invid: ' + ISNULL(@invid, ''));

    DECLARE @now datetime = GETUTCDATE();
	DECLARE @today date = @now;
	

	DECLARE @newid varchar(10) = [dbo].[fds__fn_reminder_id]();

	DECLARE @OUT [dbo].[fds__tt__reminder_core];
	DECLARE @CustomerId bigint = dbo.fds__fn_invoice_customerid(@InvId);

	INSERT INTO [dbo].[fds__reminder]
           ([Id]
		   ,[version]
           ,[InvId]
		   ,[CustomerId]
		   ,[SendToAddress]
		   ,[SendToEmail]
           ,[type]
           ,[amount]
           ,[amount_payed]
		   ,[subject]
           ,[text]
           ,[IsSent]
           ,[CustomValues]
           ,[DateSent]
		   ,[UserSent]
           ,[DateFinalized]
           ,[UserFinalized]
           ,[DateCreated]
           ,[UserCreated]
           ,[DateModified]
           ,[UserModified]
           ,[file]
		   ,[file_guid])
	OUTPUT inserted.*
		INTO @OUT
     VALUES
           (@newid
		   ,0  --version
           ,@InvId
		   ,@CustomerId
		   ,@SendToAddress
		   ,@SendToEmail
           ,@type
           ,@amount
           ,@amount_payed
		   ,@subject
           ,@text
           ,0  --IsSent, bit,>
           ,null --<CustomValues, nvarchar(max),>
           ,NULL --<DateSent, datetime,>
		   ,NULL --[UserSent]
           ,NULL --<DateFinalized, datetime,>
           ,NULL --<UserFinalized, varchar(25),>
           ,@now
           ,@authuser
           ,@now
           ,@authuser
           ,NULL
		   ,NEWID());


	SELECT TOP(1) @Id = [id] FROM @out;


	With inv as(
		select TOP(1) * FROM [dbo].[fds__invoices] WHERE [id] = @InvId
	)
	SELECT TOP(1) 
		o.*
	  , [InvoiceId]			= inv.[InvoiceId]
	  , [InvoiceDate]		= inv.[DateFinalized]
	  , [hasFile]			= CAST (  CASE WHEN o.[file] is null THEN 0 ELSE 1 END as bit)
	  , [UserNameFinalized]	=  [dbo].[fis_admin_getUserName_byID](o.[UserFinalized])
	  , [UserEmailFinalized] =  [dbo].[fis_admin_getUserEmail_byID](o.[UserFinalized])
	from @out as o 
		join inv on o.[invid] = inv.[id];




END