 <?php

class Seguro_Model_InformacoesBancarias extends Agro_Db_Table_Abstract {
    protected $_schema = 'seguro';
    protected $_name = 'informacoes_bancarias';
    protected $_primary = 'id';
    public $_order = 'id';

    public function add(int $idProposta, array $row)
    {
		return $this->save([
            'id_proposta' => $idProposta,
            'cpf_cnpj' => $row['cpf_cnpj'],
            'id_banco' => $row['id_banco'],
            'nu_conta_corrente' => $row['nu_conta_corrente'],
            'nu_digito_conta_corrente' => $row['nu_digito_conta_corrente'],
            'nu_agencia' => $row['nu_agencia'],
            'nu_digito_agencia' => $row['nu_digito_agencia'],
            'id_forma_pagamento' => $row['id_forma_pagamento'],
            'ds_tipo_conta' => $row['ds_tipo_conta'],
            'fl_conta_conjunta' => $row['fl_conta_conjunta']
        ]);
	}

    public function getInformacoesBancarias($idProposta, $id='') {

        $select = "
            (SELECT 
        		DISTINCT pp.cpf_cnpj, 
        		pp.ds_nome_proponente as ds_nome,
	            ib.id_usuario_criacao,
	            ib.id_usuario_alteracao,
	            ib.dt_criacao,
	            ib.dt_alteracao,
	            ib.fl_ativo,
	            ib.fl_del,
	            ib.id,
	            pp.id_proposta,
	            ib.id_banco,
	            ib.nu_conta_corrente,
	            ib.nu_digito_conta_corrente,
	            ib.nu_agencia,
	            ib.nu_digito_agencia,
	            ib.id_forma_pagamento,
	            b.ds_nome_banco,
	            fp.ds_forma_pagamento,
	            fp.ds_chave,
	            'PROPONENTE' as tipo_proponente_beneficiario,
                ib.ds_tipo_conta as info_ds_tipo_conta,
                ib.fl_conta_conjunta as info_fl_conta_conjunta
            FROM 
        		seguro.propostas_proponentes as pp
                LEFT JOIN seguro.informacoes_bancarias as ib ON pp.cpf_cnpj = ib.cpf_cnpj
                LEFT JOIN sistema.bancos as b ON ib.id_banco = b.id
                LEFT JOIN sistema.formas_pagamento as fp ON ib.id_forma_pagamento = fp.id
            WHERE 
        		btrim(pp.cpf_cnpj) NOT IN (
        									SELECT btrim(cpf_cnpj) FROM seguro.informacoes_bancarias 
        									WHERE id_proposta = ".$idProposta."
										)
            AND 
        		pp.id_proposta = ".$idProposta." ";

            if ($id){
                $select .= " AND ib.id = ". $id;
            }
        
        $select .= " LIMIT 1)";
        
        $select .= "
            UNION

            SELECT 
        		pb.nr_cpf_cnpj as cpf_cnpj,
        		case when (pb.ds_tipo_conta) = 's' then b.ds_nome_banco
			         when (pb.ds_tipo_conta) = 'n' then pb.ds_nome_beneficiarios
			    end as ds_nome,
                ib.id_usuario_criacao,
            	ib.id_usuario_alteracao,
            	ib.dt_criacao,
	            ib.dt_alteracao,
	            ib.fl_ativo,
	            ib.fl_del,
	            ib.id,
	            pb.id_proposta,
	            ib.id_banco,
	            ib.nu_conta_corrente,
	            ib.nu_digito_conta_corrente,
	            ib.nu_agencia,
	            ib.nu_digito_agencia,
	            ib.id_forma_pagamento,
	            b.ds_nome_banco,
	            fp.ds_forma_pagamento,
	            fp.ds_chave,
	            'BENEFICIARIO' as tipo_proponente_beneficiario,
                ib.ds_tipo_conta as info_ds_tipo_conta,
                ib.fl_conta_conjunta as info_fl_conta_conjunta
            FROM 
        		seguro.propostas_beneficiarios as pb
            	LEFT JOIN seguro.informacoes_bancarias as ib ON pb.nr_cpf_cnpj = ib.cpf_cnpj
            	                                            AND pb.id_proposta = ib.id_proposta
            	LEFT JOIN sistema.bancos as b ON ib.id_banco = b.id
            	LEFT JOIN sistema.formas_pagamento as fp ON ib.id_forma_pagamento = fp.id
            WHERE 
        		btrim(pb.nr_cpf_cnpj) NOT IN (SELECT btrim(cpf_cnpj) FROM seguro.informacoes_bancarias WHERE id_proposta = ".$idProposta.")
        	  AND pb.fl_del = false
              AND pb.id_proposta = ".$idProposta;


            if ($id){
                $select .= " AND ib.id = ". $id;
            }


        $select .= "
            UNION

            SELECT ib.cpf_cnpj,
                CASE WHEN (ds_nome_proponente is null) THEN ds_nome_beneficiarios
                     WHEN (ds_nome_proponente = '') THEN ds_nome_beneficiarios
                     WHEN (ds_nome_beneficiarios = '') THEN ds_nome_proponente
                     WHEN (ds_nome_beneficiarios is null) THEN ds_nome_proponente
                END AS ds_nome,
                ib.id_usuario_criacao,
                ib.id_usuario_alteracao,
                ib.dt_criacao,
                ib.dt_alteracao,
                ib.fl_ativo,
                ib.fl_del,
                ib.id,
                ib.id_proposta,
                ib.id_banco,
                ib.nu_conta_corrente,
                ib.nu_digito_conta_corrente,
                ib.nu_agencia,
                ib.nu_digito_agencia,
                ib.id_forma_pagamento,
                b.ds_nome_banco,
                fp.ds_forma_pagamento,
                fp.ds_chave,
                CASE 
                    WHEN ib.nu_conta_corrente IS NULL OR ib.nu_conta_corrente = '' THEN '-'
                    WHEN (ds_nome_proponente is null) THEN 'BENEFICIARIO' 
                        ELSE 'PROPONENTE' 
                END AS tipo_proponente_beneficiario,
                ib.ds_tipo_conta as info_ds_tipo_conta,
                ib.fl_conta_conjunta as info_fl_conta_conjunta
            FROM 
        		seguro.informacoes_bancarias as ib
            	LEFT JOIN seguro.propostas_proponentes as pp ON ib.cpf_cnpj = pp.cpf_cnpj AND ib.id_proposta = pp.id_proposta
            	LEFT JOIN seguro.propostas_beneficiarios as pb ON ib.cpf_cnpj = pb.nr_cpf_cnpj AND ib.id_proposta = pb.id_proposta AND pb.fl_del = false
            	LEFT JOIN sistema.bancos AS b ON ib.id_banco = b.id JOIN sistema.formas_pagamento as fp ON ib.id_forma_pagamento = fp.id
            WHERE 
        		ib.id_proposta = ".$idProposta;
            
            if ($id){
                $select .= " AND ib.id = ". $id;
            }

        $select .= "

            ORDER BY id DESC";
        
        $info = $this->_db->fetchAll($select);

        return $info;
    }

    public function getData($where) {
        $select = $this->select()->setIntegrityCheck(false);
        //$select->from(array('ib' => 'seguro.informacoes_bancarias'),array('*','ds_nome' => new Z  _Db_Expr('case when pp.ds_nome_proponente is null then sb.ds_nome_beneficiario else pp.ds_nome_proponente end')));
        $select->from(array('ib' => 'seguro.informacoes_bancarias'),array('*','ds_nome' => new Zend_Db_Expr('
            case when (upper(sb.tp_pessoa) = \'J\') and (pp.ds_nome_proponente is null) and (sb.ds_nome_beneficiario = \'\') then (
                SELECT b.ds_nome_banco||\' - \'||pb.ds_agencia as ds_banco
                FROM seguro.propostas_beneficiarios as pb
                JOIN sistema.bancos as b
                ON b.id = pb.id_banco
                WHERE pb.id_proposta = ib.id_proposta
            ) when (pp.ds_nome_proponente is null) then sb.ds_nome_beneficiario
              when (sb.ds_nome_beneficiario = \'\') then pp.ds_nome_proponente
              else pp.ds_nome_proponente end')));
        $select->joinLeft(array('b' => 'sistema.bancos'), 'ib.id_banco = b.id', 'ds_nome_banco');
        $select->join(array('fp' => 'sistema.formas_pagamento'), 'ib.id_forma_pagamento = fp.id', array('ds_forma_pagamento','ds_chave'));
        $select->joinLeft(array('sb' => 'seguro.beneficiarios'), 'sb.cpf_cnpj = ib.cpf_cnpj', null);
        $select->joinLeft(array('pp' => 'seguro.propostas_proponentes'), 'pp.id_proposta = ib.id_proposta and pp.cpf_cnpj = ib.cpf_cnpj', null);
        $select->where("ib.fl_ativo = true");

        foreach ($where as $clause) {
            if (is_array($clause)) {
                $field = $clause['field'];
                $operator = $clause['operator'];
                $value = $clause['value'];

                $select->where("$field $operator ?", $value);
            }
        }

        return $select;
    }

    public function getInformacoesBancariasByProposta($idProposta) {
        $where[] = array('field' => 'ib.id_proposta', 'operator' => '=', 'value' => $idProposta);
        $Select = $this->getData($where);

        $Row = $this->fetchAll($Select);
        return $Row;
    }

    public function getInformacoesBancariasByCpfCnpj($cpf_cnpj) {
        $where[] = array('field' => 'ib.cpf_cnpj', 'operator' => '=', 'value' => $cpf_cnpj);
        $select = $this->getData($where);
        $Row = $this->fetchAll($select);
        return $Row;
    }

    public function getInformacoesBancariasById($id, $idProposta) {
        $where[] = array('field' => 'ib.id', 'operator' => '=', 'value' => $id);
        $where[] = array('field' => 'ib.id_proposta', 'operator' => '=', 'value' => $idProposta);
        $Row = $this->fetchRow($this->getData($where));
        if ($Row) {
            return $Row;
        }
        return;
    }

    /**
     * Retorna as informações bancárias da proposta informada, ou de outra proposta vinculada a mesma proposta mãe
     * @param int $idProposta
     * @return mixed
     */
    public function getInformacoesBancariasPropostaMaeByProposta(int $idProposta)
    {
        $campos = array('*','ds_nome' => new Zend_Db_Expr('
            case when (upper(sb.tp_pessoa) = \'J\') and (pp.ds_nome_proponente is null) and (sb.ds_nome_beneficiario = \'\') then (
                SELECT b.ds_nome_banco||\' - \'||pb.ds_agencia as ds_banco
                FROM seguro.propostas_beneficiarios as pb
                JOIN sistema.bancos as b
                ON b.id = pb.id_banco
                WHERE pb.id_proposta = ib.id_proposta
            ) when (pp.ds_nome_proponente is null) then sb.ds_nome_beneficiario
              when (sb.ds_nome_beneficiario = \'\') then pp.ds_nome_proponente
              else pp.ds_nome_proponente end'));

        $select = $this->select();
        $select->setIntegrityCheck(false);
        $select->from(['prop' => 'seguro.propostas'], []);
        $select->join(['prop2' => 'seguro.propostas'], 'prop2.id_proposta_mae = prop.id_proposta_mae', []);
        $select->join(['ib' => 'seguro.informacoes_bancarias'], 'ib.id_proposta = prop2.id', $campos);
        $select->joinLeft(['b' => 'sistema.bancos'], 'ib.id_banco = b.id', 'ds_nome_banco');
        $select->join(['fp' => 'sistema.formas_pagamento'], 'ib.id_forma_pagamento = fp.id', ['ds_forma_pagamento','ds_chave']);
        $select->joinLeft(['sb' => 'seguro.beneficiarios'], 'sb.cpf_cnpj = ib.cpf_cnpj', null);
        $select->joinLeft(['pp' => 'seguro.propostas_proponentes'], 'pp.id_proposta = ib.id_proposta and pp.cpf_cnpj = ib.cpf_cnpj', null);
        $select->where("ib.fl_ativo = true");
        $select->where("prop.id = ?", $idProposta);

        return $this->fetchAll($select);
    }

    public function deleteByPropostaCpfCnpj(int $idProposta, string $cpfCnpj)
    {
        $this->getAdapter()->query("delete from seguro.informacoes_bancarias where id_proposta = {$idProposta} and cpf_cnpj = '{$cpfCnpj}'");
    }

    public function findByPropostaCpfCnpj(int $idProposta, string $cpfCnpj)
    {
        $select = $this->select();
        $select
            ->setIntegrityCheck(false)
            ->from(['ib' => 'seguro.informacoes_bancarias'])
            ->where('ib.id_proposta = ?', $idProposta)
            ->where('ib.cpf_cnpj = ?', $cpfCnpj);

        return $this->_db->fetchRow($select);
    }

    public function save(array $dados)
    {
        $row = $this->getRow($dados['id']);

        $row->cpf_cnpj = $dados['cpf_cnpj'];
        $row->id_proposta = $dados['id_proposta'];
        $row->id_banco = $dados['id_banco'];
        $row->nu_conta_corrente = $dados['nu_conta_corrente'];
        $row->nu_digito_conta_corrente = $dados['nu_digito_conta_corrente'];
        $row->nu_agencia = $dados['nu_agencia'];
        $row->nu_digito_agencia = $dados['nu_digito_agencia'];
        $row->id_forma_pagamento = $dados['id_forma_pagamento'];
        $row->ds_tipo_conta = trim($dados['ds_tipo_conta']);
        $row->fl_conta_conjunta = !empty($dados['fl_conta_conjunta']) ? 'true' : 'false';

        return $row->save();
    }
}
