CREATE OR REPLACE PROCEDURE COPIA_PRATO_CARDTRAB 
(
   P_NRCARDAPIOTRAB IN NUMBER, 
	P_NRCOMPCARDTRAB IN NUMBER,
	P_NRDIACARDTRABDEST IN NUMBER,
	P_NRCONFIGCARDTRABDEST IN NUMBER,
	P_NRORG IN NUMBER,
	P_CDOPERADOR IN VARCHAR2,
   P_SUBTITUIR IN VARCHAR2 DEFAULT 'S'
)
AS
	V_QTDE NUMBER;  
   V_NRDIACARDTRABORI NUMBER;
   V_NRCONFIGCARDTRABORI NUMBER;
   V_NRCOMPCARDTRABDEST NUMBER;
   V_CDFILAUXPRAT VARCHAR2(4);
   V_CDPRATO VARCHAR2(10);
   V_VRPECONSCARDTRAB FLOAT;
BEGIN
	-- Confere se é uma composição válida e se ela pertence ao cardápio informado
	SELECT MAX(NRDIACARDTRAB), MAX(NRCONFIGCARDTRAB), 
	       MAX(CDFILAUXPRAT), MAX(CDPRATO), MAX(VRPECONSCARDTRAB)
     INTO V_NRDIACARDTRABORI, V_NRCONFIGCARDTRABORI,
          V_CDFILAUXPRAT, V_CDPRATO, V_VRPECONSCARDTRAB
     FROM COMPCARDTRAB
    WHERE NRCOMPCARDTRAB = P_NRCOMPCARDTRAB
      AND NRCARDAPIOTRAB = P_NRCARDAPIOTRAB;

  	IF V_NRDIACARDTRABORI IS NOT NULL AND 
      V_NRCONFIGCARDTRABORI IS NOT NULL AND
      (V_NRDIACARDTRABORI <> P_NRDIACARDTRABDEST OR 
      V_NRCONFIGCARDTRABORI <> P_NRCONFIGCARDTRABDEST) THEN
     	
      -- Busca a composição para o dia e coluna de destino
   	SELECT MAX(NRCOMPCARDTRAB)
        INTO V_NRCOMPCARDTRABDEST
        FROM COMPCARDTRAB
       WHERE NRCARDAPIOTRAB = P_NRCARDAPIOTRAB
         AND NRDIACARDTRAB = P_NRDIACARDTRABDEST
         AND NRCONFIGCARDTRAB = P_NRCONFIGCARDTRABDEST;

      IF V_NRCOMPCARDTRABDEST IS NOT NULL THEN
         /*Se não pode substituir sai da função*/
         IF P_SUBTITUIR = 'N' THEN
            RETURN;
         ELSE
            /*Atualiza o prato e comensais da composição*/
            UPDATE COMPCARDTRAB
               SET CDFILAUXPRAT = V_CDFILAUXPRAT,
                   CDPRATO = V_CDPRATO,
                   VRPECONSCARDTRAB = V_VRPECONSCARDTRAB,
                   NRORGULTATU = P_NRORG,
                   CDOPERULTATU = P_CDOPERADOR,
                   DTULTATU = SYSDATE
             WHERE NRCOMPCARDTRAB = V_NRCOMPCARDTRABDEST;
         END IF;
      ELSE      
         V_NRCOMPCARDTRABDEST := TO_NUMBER(RETORNA_NOVO_CODIGO('COMPCARDTRAB', 1));
         INSERT INTO COMPCARDTRAB
         (NRCOMPCARDTRAB,NRCARDAPIOTRAB,
			 NRDIACARDTRAB, NRCONFIGCARDTRAB,
			 CDFILAUXPRAT,CDPRATO,VRPECONSCARDTRAB,
			 NRORG, NRORGINCLUSAO, NRORGULTATU,
			 CDOPERINCLUSAO,CDOPERULTATU,
			 DTINCLUSAO, DTULTATU)         
         VALUES
         (V_NRCOMPCARDTRABDEST, P_NRCARDAPIOTRAB, 
          P_NRDIACARDTRABDEST, P_NRCONFIGCARDTRABDEST,
          V_CDFILAUXPRAT, V_CDPRATO, V_VRPECONSCARDTRAB,
          P_NRORG, P_NRORG, P_NRORG,
          P_CDOPERADOR, P_CDOPERADOR,
          SYSDATE, SYSDATE);
      END IF;
   END IF;
END;