IF OBJECT_ID('sp_FollowUpCsengetesiRend') IS NOT NULL BEGIN
  DROP PROCEDURE sp_FollowUpCsengetesiRend
END
GO

CREATE PROCEDURE sp_FollowUpCsengetesiRend
   @intezmenyId int
  ,@aktTanevId int
  ,@kovetkezoTanevId int
  ,@csengetesiRendId int
AS
BEGIN
  DECLARE @isAktTorolt char(1)
         ,@isKovetkezoTorolt char(1)

  SELECT @isAktTorolt = TOROLT FROM T_CSENGETESIREND_OSSZES WHERE ID = @csengetesiRendId AND C_INTEZMENYID = @intezmenyId AND C_TANEVID = @aktTanevId
  SELECT @isKovetkezoTorolt = TOROLT FROM T_CSENGETESIREND_OSSZES WHERE ELOZOTANEVIREKORDID = @csengetesiRendId AND C_INTEZMENYID = @intezmenyId AND C_TANEVID = @kovetkezoTanevId

  IF NOT(@isAktTorolt = 'T' OR ISNULL(@isKovetkezoTorolt,'F')='T')
    BEGIN
    IF NOT EXISTS(SELECT TOP 1 ID FROM T_CSENGETESIREND_OSSZES WHERE C_TANEVID = @kovetkezoTanevId AND C_INTEZMENYID = @intezmenyId AND ELOZOTANEVIREKORDID = @csengetesiRendId)
    BEGIN
      INSERT INTO T_CSENGETESIREND_OSSZES 
      (
         C_AKTIV
        ,C_NEV
        ,C_MUKODESIHELYID
        ,C_INTEZMENYID
        ,C_TANEVID
        ,TOROLT
        ,SERIAL
        ,LASTCHANGED
        ,CREATED
        ,MODIFIER
        ,CREATOR
        ,NNID
        ,ELOZOTANEVIREKORDID
      ) 
      SELECT
         csr.C_AKTIV
        ,csr.C_NEV
        ,mh.ID
        ,@intezmenyId
        ,@kovetkezoTanevId
        ,csr.TOROLT
        ,0
        ,GETDATE()
        ,GETDATE()
        ,csr.MODIFIER
        ,csr.CREATOR
        ,csr.NNID
        ,csr.ID
      FROM T_CSENGETESIREND_OSSZES csr
        LEFT JOIN T_MUKODESIHELY_OSSZES mh ON mh.ELOZOTANEVIREKORDID = csr.C_MUKODESIHELYID AND mh.TOROLT = 'F' AND mh.C_INTEZMENYID = @intezmenyId AND mh.C_TANEVID = @kovetkezoTanevId
      WHERE csr.C_TANEVID = @aktTanevId AND csr.C_INTEZMENYID = @intezmenyId AND csr.ID = @csengetesiRendId AND csr.TOROLT = 'F'
    END
    ELSE
    BEGIN
      UPDATE t SET
         C_AKTIV = old.C_AKTIV
        ,C_NEV = old.C_NEV
        --,TOROLT = old.TOROLT
        ,SERIAL = t.SERIAL+1
        ,LASTCHANGED = GETDATE()
        ,MODIFIER=old.MODIFIER
      FROM T_CSENGETESIREND_OSSZES t
        INNER JOIN T_CSENGETESIREND_OSSZES old ON old.ID = t.ELOZOTANEVIREKORDID AND old.C_INTEZMENYID = @intezmenyId AND old.C_TANEVID = @aktTanevId AND old.ID = @csengetesiRendId
      WHERE t.TOROLT = 'F' AND t.C_INTEZMENYID = @intezmenyId AND t.C_TANEVID = @kovetkezoTanevId AND t.ELOZOTANEVIREKORDID = @csengetesiRendId
    END

    IF (SELECT C_AKTIV FROM T_CSENGETESIREND_OSSZES WHERE ELOZOTANEVIREKORDID=@csengetesiRendId)='T'
      UPDATE T_CSENGETESIREND_OSSZES SET C_AKTIV='F' WHERE C_TANEVID=@kovetkezoTanevId AND C_INTEZMENYID=@intezmenyId AND TOROLT='F' AND ELOZOTANEVIREKORDID<>@csengetesiRendId
  END
END