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

CREATE PROCEDURE [dbo].[sp_GetTanuloiGondviseloAdatok]
   @pTanuloId    INT
  ,@pTanevId    INT
  ,@pIntezmenyId  INT
AS
BEGIN

  SET NOCOUNT ON;

  --NOTE: 0. tábla - Gondviselo adatok
  SELECT
     g.ID AS GondviseloId
    ,g.C_NEV AS GondviseloNeve
    ,g.C_ISTORVENYESKEPVISELO TorvenyesKepviselo
    ,utolsoBelepes.UtolsoBelepes
    ,utolsoBelepes.UtolsoBelepesMobil
    ,e.C_EMAILCIM AS EmailCim
    ,t.C_TELEFONSZAM AS Telefonszam
  FROM T_GONDVISELO_OSSZES g
    LEFT JOIN T_EMAIL_OSSZES e ON e.C_GONDVISELOID = g.ID AND e.TOROLT = 'F' AND e.C_ALAPERTELMEZETT = 'T'
    LEFT JOIN T_TELEFON_OSSZES t ON  t.C_GONDVISELOID = g.ID AND t.TOROLT = 'F' AND t.C_ALAPERTELMEZETT = 'T'
    OUTER APPLY (
      SELECT  
        MAX(CASE WHEN C_IDP IN ('F', '_') THEN C_UTOLSOBELEPES END) AS UtolsoBelepes, 
        MAX(CASE WHEN C_IDP IN ('T', '_') THEN C_UTOLSOBELEPESMOBIL END) AS UtolsoBelepesMobil
      FROM (
        SELECT  C_GONDVISELOID, C_FELHASZNALOID, C_TANEVID, '_' C_IDP, C_UTOLSOBELEPES, C_UTOLSOBELEPESMOBIL
        FROM T_FELHASZNALOBELEPES_OSSZES 
        WHERE TOROLT = 'F' 
        AND C_BEJELENTKEZESINEV <> 'KRETA_TECHNICAL_FORI'

        UNION ALL

        SELECT C_GONDVISELOID, C_FELHASZNALOID, C_TANEVID, C_IDP, C_LASTACTIVITY, C_LASTACTIVITY
        FROM T_FELHASZNALOBELEPESTORTENET_OSSZES
      ) b 
      WHERE b.C_GONDVISELOID = g.ID
        AND b.C_FELHASZNALOID = g.C_TANULOID
        AND b.C_TANEVID = g.C_TANEVID
    ) utolsoBelepes
  WHERE g.C_TANULOID = @pTanuloId AND g.TOROLT = 'F'

  --NOTE: 1. tábla - Gondviselo címek
  SELECT
     g.ID AS GondviseloId
    ,CONCAT(c.C_IRANYITOSZAM, ', ', c.C_VAROS, ', ', c.C_KOZTERULET, ' ', c.C_KOZTERULETJELLEGENEV, c.C_HAZSZAM) AS CimText
    ,dibCTip.C_NAME AS CimTipus
    ,c.C_CIMTIPUSA AS CimTipusId
  FROM T_GONDVISELO_OSSZES g
    LEFT JOIN  T_CIM_OSSZES c ON c.C_GONDVISELOID = g.ID AND c.TOROLT = 'F'
    INNER JOIN T_DICTIONARYITEMBASE_OSSZES dibCTip ON dibCTip.ID = c.C_CIMTIPUSA 
      AND dibCTip.C_TANEVID = @pTanevId 
      AND dibCTip.TOROLT = 'F'
      AND dibCTip.C_INTEZMENYID=@pIntezmenyId
  WHERE g.C_TANULOID = @pTanuloId 
    AND g.TOROLT = 'F' 
END
GO

