CREATE OR REPLACE PROCEDURE REPLICA_PRATO_CARDTRAB
(
   P_NRCARDAPIOTRAB IN NUMBER,
   P_NRCOMPCARDTRAB IN NUMBER,
   P_NRORG IN NUMBER,
   P_CDOPERADOR IN VARCHAR2,
   P_DOM IN VARCHAR2,
   P_SEG IN VARCHAR2,
   P_TER IN VARCHAR2,
   P_QUA IN VARCHAR2,
   P_QUI IN VARCHAR2,
   P_SEX IN VARCHAR2,
   P_SAB IN VARCHAR2,
   P_SUBTITUIR IN VARCHAR2 DEFAULT 'S',
   P_COPIA_PRATO IN VARCHAR2 DEFAULT 'S',
   P_COMENSAIS IN FLOAT DEFAULT NULL,
   P_1COMENSAL IN VARCHAR2 DEFAULT 'N'
)
AS   
   V_NRDIACARDTRABORI NUMBER;
   V_NRSEMANA NUMBER;
   V_NRDIASEMANA NUMBER;
   V_NRCONFIGCARDTRABORI NUMBER;
   V_QTCOMENSAIS FLOAT;
BEGIN
   SELECT MAX(C.NRDIACARDTRAB), MAX(C.NRCONFIGCARDTRAB), MAX(D.NRSEMANA), MAX(D.NRDIASEMANA)
     INTO V_NRDIACARDTRABORI, V_NRCONFIGCARDTRABORI, V_NRSEMANA, V_NRDIASEMANA
     FROM COMPCARDTRAB C
          INNER JOIN DIACARDTRAB D ON D.NRDIACARDTRAB = C.NRDIACARDTRAB
    WHERE C.NRCOMPCARDTRAB = P_NRCOMPCARDTRAB
      AND C.NRCARDAPIOTRAB = P_NRCARDAPIOTRAB;
   
   IF V_NRDIACARDTRABORI IS NOT NULL AND
      V_NRCONFIGCARDTRABORI IS NOT NULL THEN
      FOR C_DIAS IN
      (
         SELECT NRDIACARDTRAB
           FROM DIACARDTRAB
          WHERE NRCARDAPIOTRAB = P_NRCARDAPIOTRAB            
            AND QTCOMENSAIS > 0
            AND ((NRDIASEMANA = 1 AND P_DOM = 'S') OR
                 (NRDIASEMANA = 2 AND P_SEG = 'S') OR
                 (NRDIASEMANA = 3 AND P_TER = 'S') OR
                 (NRDIASEMANA = 4 AND P_QUA = 'S') OR
                 (NRDIASEMANA = 5 AND P_QUI = 'S') OR
                 (NRDIASEMANA = 6 AND P_SEX = 'S') OR
                 (NRDIASEMANA = 7 AND P_SAB = 'S'))
      ) LOOP
         COPIA_PRATO_CARDTRAB( 
            P_NRCARDAPIOTRAB, P_NRCOMPCARDTRAB, C_DIAS.NRDIACARDTRAB, 
            V_NRCONFIGCARDTRABORI, P_NRORG, P_CDOPERADOR, 
            P_SUBTITUIR, P_COPIA_PRATO, P_COMENSAIS, P_1COMENSAL 
         );
      END LOOP;
   END IF;
END;
/