﻿DROP PROCEDURE IF EXISTS sp_FollowUpCsengetesiRend
GO

CREATE PROCEDURE sp_FollowUpCsengetesiRend
   @intezmenyId int
  ,@aktTanevId int
  ,@kovetkezoTanevId int
  ,@csengetesiRendId int
AS
BEGIN
  DECLARE @csengrendNev nvarchar(100)
         ,@kovCsengrendId int

  SELECT @csengrendNev = C_NEV FROM T_CSENGETESIREND_OSSZES WHERE ID = @csengetesiRendId
  
  IF EXISTS (SELECT 1 FROM T_CSENGETESIREND_OSSZES WHERE C_TANEVID=@kovetkezoTanevId AND TOROLT='F' AND C_NEV=@csengrendNev AND ISNULL(ELOZOTANEVIREKORDID,0)<>@csengetesiRendId)
  BEGIN
    UPDATE T_CSENGETESIREND_OSSZES SET ELOZOTANEVIREKORDID = NULL WHERE ELOZOTANEVIREKORDID=@csengetesiRendId
    UPDATE T_CSENGETESIREND_OSSZES SET ELOZOTANEVIREKORDID = @csengetesiRendId WHERE C_TANEVID=@kovetkezoTanevId AND TOROLT='F' AND C_NEV=@csengrendNev AND ISNULL(ELOZOTANEVIREKORDID,0)<>@csengetesiRendId
  END

  SELECT @kovCsengrendId = ID FROM T_CSENGETESIREND_OSSZES WHERE ELOZOTANEVIREKORDID=@csengetesiRendId

  IF (SELECT TOROLT FROM T_CSENGETESIREND_OSSZES WHERE ID = @csengetesiRendId)='T' OR (SELECT TOROLT FROM T_CSENGETESIREND_OSSZES WHERE ID=@kovCsengrendId)='T'
  BEGIN
    RETURN
  END
    IF @kovCsengrendId IS NULL
    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
        ,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
GO

