DROP PROCEDURE IF EXISTS [dbo].[uspCheckTanarOra]
GO

CREATE PROCEDURE [dbo].[uspCheckTanarOra]
   @tanarId int
  ,@startDate datetime
  ,@endDate datetime
  ,@intezmenyId int
  ,@tanevId int
  ,@oraszam int = null
  ,@isNapirend bit = null
  ,@isEgyediHelyettesites bit = 0
AS
BEGIN
  SET NOCOUNT ON;
  
  DECLARE @CsakOrarendiOrak BIT = 0; --tanórák is
  DECLARE @IdoszakKezdete DATETIME = CAST(@startDate AS DATE);
  DECLARE @IdoszakVege DATETIME = CAST(DATEADD(DAY, 1, @endDate) AS DATE);
  CREATE TABLE #OrarendTable 
  (
     ORARENDIID int
    ,OraKezdete datetime
    ,OraVege datetime
    ,Oraszam int
    ,TargyNev nvarchar(300)
    ,Megtartott char(1)
    ,OsztalyNev nvarchar(255)
    ,TanarNev nvarchar(255)
    ,TeremNev nvarchar(255)
    ,OraTipus nvarchar(200) 
  )
  
  INSERT INTO #OrarendTable 
  (
     ORARENDIID
    ,OraKezdete
    ,OraVege
    ,Oraszam
    ,TargyNev
    ,Megtartott
    ,OsztalyNev
    ,TanarNev
    ,TeremNev
    ,OraTipus
  )
  EXEC sp_GetOrarend 
     @pIntezmenyId = @intezmenyId
    ,@pTanevId = @tanevId
    ,@pIdoszakKezdete = @IdoszakKezdete
    ,@pIdoszakVege = @IdoszakVege
    ,@pTanarId = @tanarId
    ,@pIsHelyettesitesNelkul  = 0
    ,@pOsztalyCsoportId  =  NULL
    ,@pTanuloId = NULL
    ,@pTantargyId  = NULL
    ,@pTeremId = NULL
    ,@pCsakOrarendiOrak  = @CsakOrarendiOrak
    ,@pIsNapirend = @isNapirend
    ,@pOszlopok = N'ORARENDIID,OraKezdete,OraVege,Oraszam,TargyNev,Megtartott,OsztalyNev,TanarNev,TeremNev,OraTipus'

  IF(@isNapirend = 1)
  BEGIN
    SELECT 
       sgo.ORARENDIID AS C_ORARENDIORAID
      ,sgo.TargyNev
      ,sgo.OsztalyNev
      ,sgo.TanarNev
      ,sgo.TeremNev
      ,sgo.Megtartott
      ,oo.C_TULORA
    FROM #OrarendTable AS sgo
    INNER JOIN T_ORARENDIORA oo on oo.ID = sgo.ORARENDIID
    WHERE (sgo.OraTipus = 'OrarendiOra' OR @isEgyediHelyettesites = 1)
      AND sgo.OraKezdete < @endDate
      AND sgo.OraVege > @startDate
  END  
  ELSE IF(@oraszam IS NULL)
  BEGIN
    SELECT 
       sgo.ORARENDIID AS C_ORARENDIORAID
      ,sgo.TargyNev
      ,sgo.OsztalyNev
      ,sgo.TanarNev
      ,sgo.TeremNev
      ,sgo.Megtartott
      ,oo.C_TULORA
    FROM #OrarendTable AS sgo
    INNER JOIN T_ORARENDIORA oo on oo.ID = sgo.ORARENDIID
    WHERE (sgo.OraTipus = 'OrarendiOra' OR @isEgyediHelyettesites = 1)
      AND sgo.OraKezdete = @startDate
      AND sgo.OraVege = @endDate
  END
  ELSE
  BEGIN
    SELECT 
       sgo.ORARENDIID AS C_ORARENDIORAID
      ,sgo.TargyNev
      ,sgo.OsztalyNev
      ,sgo.TanarNev
      ,sgo.TeremNev
      ,sgo.Megtartott
      ,oo.C_TULORA
    FROM #OrarendTable AS sgo
    INNER JOIN T_ORARENDIORA oo on oo.ID = sgo.ORARENDIID
    WHERE (sgo.OraTipus = 'OrarendiOra' OR @isEgyediHelyettesites = 1)
      AND sgo.Oraszam = @oraszam
  END

END
GO
