-- dbo.ET_TabPohybyZbozi_HDC_D
CREATE TRIGGER dbo.ET_TabPohybyZbozi_HDC_D ON dbo.TabPohybyZbozi
WITH EXECUTE AS CALLER
FOR DELETE
AS
BEGIN
 SET NOCOUNT ON

-- !! trigger neupravujte, bude stejne pregenerovan pri startu pluginu PluginHDCRTN nebo sluzby HDCDZApi !!

 DECLARE
  @id INT,
  @dpz TINYINT,
  @idPHId INT,
  @idPHIdent1 INT,
  @idPHIdent2 INT,
  @idObjHlav INT



 DECLARE c CURSOR LOCAL FAST_FORWARD FOR
  SELECT d.ID, d.DruhPohybuZbo
   FROM deleted d
 OPEN c
 WHILE (1=1)
  BEGIN
   FETCH NEXT FROM c INTO @id, @dpz
   IF (@@FETCH_STATUS<>0) BREAK


-- sync informace pro reseni ASol/ProHolding/HDC
   IF (@dpz=4)
    BEGIN

     IF OBJECT_ID(N'dbo._TabVyroba_VydejMatSarze', N'U') IS NOT NULL
      DELETE FROM dbo._TabVyroba_VydejMatSarze WHERE IDPohybZbozi=@id


     IF OBJECT_ID(N'dbo.TabPohybyZbozi_EXT', N'U') IS NOT NULL
      BEGIN
       SET @idPHId=(SELECT _HDCAPI_PHident FROM dbo.TabPohybyZbozi_EXT WHERE ID=@id)
       IF (@idPHId IS NOT NULL)
        IF OBJECT_ID(N'dbo._TabVyroba_Objednavky', N'U') IS NOT NULL
         SELECT @idPHIdent1=IdPHIdent, @idPHIdent2=IdPHIdent2 FROM dbo._TabVyroba_Objednavky WHERE ID=@idPHId
        IF OBJECT_ID(N'dbo._TabVyroba_Objednavky_Pol', N'U') IS NOT NULL
         BEGIN
          SELECT @idObjHlav=IDHlava FROM dbo._TabVyroba_Objednavky_Pol WHERE IDPohybOZ=@id
          DELETE FROM dbo._TabVyroba_Objednavky_Pol WHERE IDPohybOZ=@id
          IF OBJECT_ID(N'dbo._TabVyroba_Objednavky', N'U') IS NOT NULL
           UPDATE dbo._TabVyroba_Objednavky SET MnozVydane=ISNULL( (SELECT SUM(Mnozstvi) FROM dbo._TabVyroba_Objednavky_Pol WHERE IDHlava=@idObjHlav), 0) WHERE ID=@idObjHlav
         END
      END
    END


   IF (@dpz=0)
    BEGIN
     IF OBJECT_ID(N'dbo._TabVyroba_PaletyPohybOZ', N'U') IS NOT NULL
      UPDATE dbo._TabVyroba_PaletyPohybOZ SET IDPohybOZ=NULL WHERE IDPohybOZ=@id
    END

   IF OBJECT_ID(N'dbo._hdc_PZ_PuvodniVC', N'U') IS NOT NULL
    DELETE FROM dbo._hdc_PZ_PuvodniVC WHERE IDPohybZbozi=@id


  END
 CLOSE c
 DEALLOCATE c

END
