IF  EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[SPWEB_KURUMLOGIN]') AND OBJECTPROPERTY(id,N'IsProcedure') = 1)
DROP PROCEDURE SPWEB_KURUMLOGIN
GO

CREATE PROCEDURE [dbo].[SPWEB_KURUMLOGIN]
@username nvarchar(20), @password  nvarchar(20), @ip nvarchar(20)
AS
BEGIN
   DECLARE 
      @KayitSayi int,
      @HastaWebsifre nvarchar(10),
	  @userid int=0,
	  @sonucmesaj nvarchar(200)=''
      
    SET @KayitSayi = 0
	
	SET @KayitSayi=(SELECT COUNT(CARIID) FROM CARI WITH(NOLOCK) WHERE CARIID = @username AND WEBSIFRE = @password)
	IF @KayitSayi=1
	BEGIN
		SELECT @userid = CARIID, @HastaWebsifre = WEBSIFRE
		FROM CARI WITH(NOLOCK) WHERE CARIID = @username AND WEBSIFRE = @password
	END
	

    IF @KayitSayi = 1   
    BEGIN

			SELECT DBO.FN_BASIT_ID_SIFRELE(CARIID) AS id, 'Partner' as role, UNVANI AS adi, '' AS soyadi, '' AS cep, '' AS email, GETDATE() AS songiristarihi, 
					(CASE WHEN ISNULL(WEBSIFRETARIHI,DATEADD(MONTH,-5,GETDATE()))<DATEADD(MONTH,-3,GETDATE()) THEN 1 ELSE 0 END) AS sifredegismeli, 1 AS sonuc, (CASE WHEN CARI.OSGBKURUMU=1 THEN 1 ELSE 0 END) as osgbkurumu 
			FROM CARI WITH(NOLOCK) WHERE CARIID=@userid
			set @sonucmesaj = 'Webden başarılı login'			
	END
	ELSE IF @KayitSayi > 1
	BEGIN
			SELECT TOP 1 '' as id, 'Partner' as role, null as adi, null as soyadi, null as cep, null as email, null as songiristarihi, 0 as sifredegismeli, 5 as sonuc, 0 as osgbkurumu FROM HKIMLIK WITH(NOLOCK)
			set @sonucmesaj = @username +' bilgisine karşılık gelen birden fazla kişi kayıtlı'			
	END
	ELSE IF @KayitSayi = 0
	BEGIN
			SELECT TOP 1 '' as id, 'Partner' as role, null as adi, null as soyadi, null as cep, null as email, null as songiristarihi, 0 as sifredegismeli, 6 as sonuc, 0 as osgbkurumu FROM HKIMLIK WITH(NOLOCK)			
			set @sonucmesaj = 'Kullanıcı adı:'+@username+' Şifre:'+@password+' bilgileri ile başarısız login denemesi'
	END

	IF @sonucmesaj<>''
		EXEC SPWEB_LOGLA 'kurumlogin',@userid,@sonucmesaj,@ip

END
GO

IF EXISTS (SELECT [name] FROM [sys].[database_principals] WHERE [type] = N'S' AND [name] = N'mediwebuser')
BEGIN
	BEGIN TRY
		GRANT EXECUTE ON [dbo].[SPWEB_KURUMLOGIN] TO [mediwebuser]
	END TRY
	BEGIN CATCH
	END CATCH
END
GO


