SET TERM ^ ;

CREATE OR ALTER trigger tbpdv_cfe_forma_pagamento_b05i for tbpdv_cfe_forma_pagamento
active before insert position 1
AS
DECLARE VARIABLE BANDEIRA_DESCRICAO VARCHAR(100);
DECLARE VARIABLE BANDEIRA_ID INTEGER;

BEGIN
  IF(COALESCE(NEW.BANDEIRA_CARTAO, '') = '' AND COALESCE(NEW.CARTAO_BANDEIRA_ID, 0) > 0) THEN
  BEGIN

    SELECT FIRST 1 T.DESCRICAO FROM TBCARTAO_BANDEIRA T WHERE T.ID = NEW.CARTAO_BANDEIRA_ID INTO :BANDEIRA_DESCRICAO;

    NEW.BANDEIRA_CARTAO = :BANDEIRA_DESCRICAO;

  END

  IF(COALESCE(NEW.BANDEIRA_CARTAO, '') <> '' AND COALESCE(NEW.CARTAO_BANDEIRA_ID, 0) = 0) THEN
  BEGIN
        
        :BANDEIRA_ID = COALESCE((SELECT FIRST 1 T.ID FROM TBCARTAO_BANDEIRA T WHERE T.DESCRICAO LIKE SUBSTRING(NEW.BANDEIRA_CARTAO FROM 1 FOR 4)||'%'), 0);

        NEW.CARTAO_BANDEIRA_ID = :BANDEIRA_ID;

  END

  IF(COALESCE(NEW.ADQUIRENTE_ID, 0) = 0 AND CHAR_LENGTH(COALESCE(NEW.CODIGO_AUTORIZACAO, '')) > 0) THEN
  BEGIN
        NEW.ADQUIRENTE_ID = 25;

  END

  IF(COALESCE(NEW.ADQUIRENTE_ID, 0) = 999) THEN
  BEGIN
        NEW.ADQUIRENTE_ID = 990;
  END
END^

SET TERM ; ^

