<?php

class Seguro_Model_Proponentes extends Agro_Db_Table_Abstract {
	protected $_schema = 'seguro';
	protected $_name = 'proponentes';
	protected $_primary = 'id';
	public $_order = 'ds_nome_proponente asc';

	public $_columnExcel = array(
		'id' => 'Cod.',
		'ds_nome_proponente' => 'Nome',
		'cpf_cnpj' => 'CPF_CNPJ',
		'tp_pessoa' => 'Tipo',
		'fl_inadimplente' => 'Inadimplente',
		'fl_restricao' => 'RT'
	);
	
	public function atualizarInadimplentes($inadimplentes) {
		$this->getDefaultAdapter()->beginTransaction();
		
		if (is_array($inadimplentes)) {
			try {
				foreach ($inadimplentes as $inadimplente) {
					$this->update(array('fl_inadimplente' => $inadimplente['fl_inadimplente']), 'id = '. $inadimplente['id']);
				}
				$this->getDefaultAdapter()->commit();
				return true;
			} catch (Exception $e) {
				$this->getDefaultAdapter()->rollback();
				return false;
			}
		}
		
	}

    /**
     * Adiciona o cpf na tabela proponentes_abc caso o checkbox esteja selecionado
	 *
     * @param string $cpf_cnpj
     * @param string $dtVencimento
	 * @return bool
     */
    private function addProgramaAbc(string $cpf_cnpj, string $dtVencimento) : bool
	{
		$cpfCnpj = preg_replace('/[^a-zA-Z0-9_ %\[\]\(\)%&]/s','', $cpf_cnpj);

		$modelProponentesAbc = new Seguro_Model_ProponentesAbc();
		$proponenteAbc = $modelProponentesAbc->getByCpfCnpj($cpfCnpj);
		$id = !empty($proponenteAbc) ? $proponenteAbc->id : null;

        try {
            $modelProponentesAbc->save([
				'id' => $id,
				'cpf_cnpj' => $cpfCnpj,
				'dt_vencimento' => $dtVencimento,
            ]);
            return true;
        } catch (Exception $e) {
            return false;
        }
    }

    /**
     * Remove o cpf da tabela proponentes_abc caso o checkbox nao esteja selecionado
     * @param String $cpf_cnpj
     */
    private function removeProgramaAbc(string $cpf_cnpj) : bool {
        $cpf_cnpj = preg_replace('/[^a-zA-Z0-9_ %\[\]\(\)%&]/s','', $cpf_cnpj);
        try {
            $ProponentesAbc = new Seguro_Model_ProponentesAbc();
            if ($ProponentesAbc->existsCpfCnpj($cpf_cnpj)) {
                return $ProponentesAbc->deleteByCpfCnpj($cpf_cnpj);
            }
            return true;
        } catch (Exception $e) {
            return false;
        }
    }

	public function save($data)
    {
        try {
            $row = $this->getRow($data['id_proponente']);

            $row->tp_pessoa = $data['tp_pessoa'] ?? null;
            $row->ds_nome_proponente = $data['ds_nome_proponente'];
            $row->ds_email_proponente = $data['ds_email_proponente'];
            $row->dt_nascimento = $data['dt_nascimento']
                ? Agro_Util::formatDate($data['dt_nascimento'], Zend_Date::W3C)
                : null;
            $row->id_estado_civil = !empty($data['id_estado_civil']) ? $data['id_estado_civil'] : null;
            $row->ds_documento_natureza = $data['ds_documento_natureza'];
            $row->ds_documento_numero = $data['ds_documento_numero'] ?? null;
            $row->id_orgao_expedidor = !empty($data['id_orgao_expedidor']) ? $data['id_orgao_expedidor'] : null;
            $row->dt_documento_exp = $data['dt_documento_exp']
                ? Agro_Util::formatDate($data['dt_documento_exp'], Zend_Date::W3C)
                : null;
            $row->ds_endereco_rua = $data['ds_endereco_rua_proponente'];
            $row->ds_endereco_nro = $data['ds_endereco_nro_proponente'];
            $row->ds_endereco_complem = $data['ds_endereco_complemento_proponente'];
            $row->ds_endereco_bairro = $data['ds_endereco_bairro_proponente'];
            $row->ds_endereco_cep = $data['ds_endereco_cep_proponente'];
            $row->id_municipio = !empty($data['id_municipio_proponente']) ? $data['id_municipio_proponente'] : null;
            $row->ds_tel_residencia = $data['ds_tel_residencia'];
            $row->ds_tel_propriedade = $data['ds_tel_propriedade'];
            $row->ds_tel_celular = $data['ds_tel_celular'];
            $row->cpf_cnpj = $data['cpf_cnpj'];
            $row->fl_inadimplente = $data['fl_inadimplente'];
            $row->fl_validacao_receita = $data['fl_validacao_receita'];
            $row->fl_restricao = $data['fl_restricao'];

            if (array_key_exists('ds_sexo', $data['ds_sexo'])) {
                $row->ds_sexo = $data['ds_sexo'];
            }

            if ($data['cpf_cnpj']) {
                $data['fl_programa_abc']
                    ? $this->addProgramaAbc($data['cpf_cnpj'], $data['dt_vencimento_programa_abc'])
                    : $this->removeProgramaAbc($data['cpf_cnpj']);
            }

            return $row->save();
        } catch (Exception $e) {
            if ($e->getCode() == 23505) {
                $this->setMessage(MSG_CPFCNPJ_EXISTENTE);
            }

            return false;
        }
    }

	public function saveByCpfCnpj($data) {
		$Row = $this->fetchRow("cpf_cnpj = '{$data['cpf_cnpj']}'");
		if (!$Row) $Row = $this->createRow();

		$Row->tp_pessoa = $data['tp_pessoa'];
		$Row->ds_nome_proponente = $data['ds_nome_proponente'];
		$Row->ds_nome_proponente = $data['ds_nome_proponente'];
		$Row->ds_email_proponente = $data['ds_email_proponente'];
		$Row->ds_sexo = $data['ds_sexo'];
		$Row->dt_nascimento = Agro_Util::formatDate($data['dt_nascimento'], Zend_Date::W3C);
		$Row->id_estado_civil = $data['id_estado_civil'] ? $data['id_estado_civil'] : null;
		$Row->ds_documento_natureza = $data['ds_documento_natureza'];
		$Row->ds_documento_numero = $data['ds_documento_numero'];
		$Row->id_orgao_expedidor = $data['id_orgao_expedidor'] ? $data['id_orgao_expedidor'] : null;
		$Row->dt_documento_exp = Agro_Util::formatDate($data['dt_documento_exp'], Zend_Date::W3C);
		$Row->ds_endereco_rua = ($data['ds_endereco_rua_proponente'] ? $data['ds_endereco_rua_proponente'] : $data['ds_endereco_rua']);
		$Row->ds_endereco_nro = ($data['ds_endereco_nro_proponente'] ? $data['ds_endereco_nro_proponente'] : $data['ds_endereco_nro']);
		$Row->ds_endereco_complem = ($data['ds_endereco_complemento_proponente'] ? $data['ds_endereco_complemento_proponente'] : $data['ds_endereco_complemen']);
		$Row->ds_endereco_bairro = ($data['ds_endereco_bairro_proponente'] ? $data['ds_endereco_bairro_proponente'] : $data['ds_endereco_bairro']);
		$Row->ds_endereco_cep = ($data['ds_endereco_cep_proponente'] ? $data['ds_endereco_cep_proponente'] : $data['ds_endereco_cep']);
		$Row->id_municipio = ($data['id_municipio_proponente'] ? $data['id_municipio_proponente'] : $data['id_municipio']);
		$Row->ds_tel_residencia = $data['ds_tel_residencia'];
		$Row->ds_tel_propriedade = $data['ds_tel_propriedade'];
		$Row->ds_tel_celular = $data['ds_tel_celular'];
		$Row->cpf_cnpj = $data['cpf_cnpj'];

		return $Row->save();
	}

	public function getData($where=false) {
		$select = $this->select();
		$select->setIntegrityCheck(false);
		$select->from(array('p' => "seguro.proponentes"));
		$select->joinLeft(array('m' => 'sistema.municipios'), 'p.id_municipio = m.id', 'ds_nome_municipio');
		$select->joinLeft(array('e' => 'sistema.estados'), 'm.id_estado = e.id', 'ds_sigla');

		if (is_array($where)) {
			foreach ($where as $clause) {
				if (is_array($clause)) {
					$field = $clause['field'];
					$operator = $clause['operator'];
					$value = $clause['value'];

					$select->where("$field $operator ?", $value);
				} else {
					$select->where($clause, '');
				}
			}
		} elseif ($where != '') {
			$select->where($where);
		}

		$select->order($this->_order);
		return $select;
	}

	/**
	 * Busca corretores e monta combo
	 *
	 * @return array
	 */
	public function getComboProponente() {
		$select = $this->select();
		$select->setIntegrityCheck(false);
		$select->from(array('c' => 'seguro.proponentes'), array('id','ds_nome_proponente', 'cpf_cnpj'));
		$select->order('ds_nome_proponente');
		$Rs = $this->fetchAll($select);

		if ($Rs) {
			$options[] = null;
			foreach ($Rs as $row) {
				$options[$row['id']] = $row['ds_nome_proponente'] . ' - ' . $row['cpf_cnpj'];
			}

			return $options;
		} else {
			return false;
		}
	}

	public function getValorSubvencaoFederalAno($cpf_cnpj,$id_proposta="",$inicioVigencia) {
		$ano = substr($inicioVigencia,0,4);

		$Select = $this->select()->setIntegrityCheck(false)->distinct(true);
		$Select->from(array('p' => 'seguro.propostas'), null);
		$Select->join(array('pp' => 'seguro.propostas_proponentes'), 'p.id = pp.id_proposta', null);
		$Select->join(array('ppa' => 'seguro.propostas_parcelas'), 'p.id = ppa.id_proposta', 'sum(vl_subvencao_federal) as acumulado_subvencao');
		$Select->join(array('s' => 'sistema.status'), 'p.id_status = s.id', null);
		$Select->where("seguro.dt_vigencia_inicio_original(p.id) between '$ano-01-01' and '$ano-12-31'");
		$Select->where("s.ds_chave not in ('NAO_ENVIADA' , 'DEVOLVIDA' , 'PROPOSTA_CANCELADA' , 'APOLICE_CANCELADA', 'PROPOSTA_INCOMPLETA' , 'ORCAMENTO_ENDOSSO', 'ENDOSSO_INCOMPLETO', 'ENDOSSO_ANULADO', 'ENDOSSO_CANCELADO', 'SOLICITACAO_CANCELADA')");
		$Select->where("pp.cpf_cnpj = ?", $cpf_cnpj);
		if($id_proposta){
			$Select->where("p.id <> ?", $id_proposta);
		}

		$value = $this->getAdapter()->fetchOne($Select);

		if($value < 0 || !$value){
			$value = 0;
		}

		return ($value ? $value : 0);
	}

	public function getValorSubvencaoEstadualAno($cpf_cnpj, $inicioVigencia, $id_proposta, $sigla_uf) {
		$ano = substr($inicioVigencia,0,4);

		$Select = $this->select()->setIntegrityCheck(false)->distinct(true);
		$Select->from(array('p' => 'seguro.propostas'), null);
		$Select->join(array('pp' => 'seguro.propostas_proponentes'), 'p.id = pp.id_proposta', null);
		$Select->join(array('ppa' => 'seguro.propostas_parcelas'), 'p.id = ppa.id_proposta', 'sum(vl_subvencao_estadual) as acumulado_subvencao');
		$Select->join(array('s' => 'sistema.status'), 'p.id_status = s.id', null);
		$Select->join(array('pr' => 'seguro.propostas_propriedades'), 'p.id = pr.id_proposta', null);
		$Select->join(array('m' => 'sistema.municipios'), 'm.id = pr.id_municipio', null);
		$Select->join(array('e' => 'sistema.estados'), 'e.id = m.id_estado', null);
		$Select->where("seguro.dt_vigencia_inicio_original(p.id) between '$ano-01-01' and '$ano-12-31'");
		$Select->where("s.ds_chave not in ('NAO_ENVIADA' , 'DEVOLVIDA' , 'PROPOSTA_CANCELADA' , 'APOLICE_CANCELADA', 'PROPOSTA_INCOMPLETA' , 'ORCAMENTO_ENDOSSO', 'ENDOSSO_INCOMPLETO', 'ENDOSSO_ANULADO', 'SOLICITACAO_CANCELADA')");
		$Select->where("pp.cpf_cnpj = ?", $cpf_cnpj);
		$Select->where("p.id <> ?", $id_proposta);
		$Select->where("e.ds_sigla = ?", $sigla_uf);

		$value = $this->getAdapter()->fetchOne($Select);

		return ($value ? $value : 0);
	}

	public function getValorSubvencaoEstadualAnoCotacao($cpf_cnpj, $inicioVigencia, $id_proposta = '', $sigla_uf) {
		$ano = substr($inicioVigencia,0,4);

		$Select = $this->select()->setIntegrityCheck(false)->distinct(true);
		$Select->from(array('p' => 'seguro.propostas'), null);
		$Select->join(array('pp' => 'seguro.propostas_proponentes'), 'p.id = pp.id_proposta', null);
		$Select->join(array('ppa' => 'seguro.propostas_parcelas'), 'p.id = ppa.id_proposta', 'sum(vl_subvencao_estadual) as acumulado_subvencao');
		$Select->join(array('s' => 'sistema.status'), 'p.id_status = s.id', null);
		$Select->join(array('pr' => 'seguro.propostas_propriedades'), 'p.id = pr.id_proposta', null);
		$Select->join(array('m' => 'sistema.municipios'), 'm.id = pr.id_municipio', null);
		$Select->join(array('e' => 'sistema.estados'), 'e.id = m.id_estado', null);
		$Select->where("seguro.dt_vigencia_inicio_original(p.id) between '$ano-01-01' and '$ano-12-31'");
		$Select->where("s.ds_chave not in ('NAO_ENVIADA' , 'DEVOLVIDA' , 'PROPOSTA_CANCELADA' , 'APOLICE_CANCELADA', 'PROPOSTA_INCOMPLETA' , 'ORCAMENTO_ENDOSSO', 'ENDOSSO_INCOMPLETO', 'ENDOSSO_ANULADO', 'SOLICITACAO_CANCELADA')");
		$Select->where("pp.cpf_cnpj = ?", $cpf_cnpj);
		$Select->where("e.ds_sigla = ?", $sigla_uf);

		if($id_proposta != ''){
			$Select->where("p.id <> ?", $id_proposta);
		}

		$value = $this->getAdapter()->fetchOne($Select);

		return ($value ? $value : 0);
	}

	public function getValorSubvencaoEstadualAnoPorCultura($cpf_cnpj, $inicioVigencia, $id_proposta, $sigla_uf, $id_cultura) {
		$ano = substr($inicioVigencia, 0, 4);

		$Select = $this->select()->setIntegrityCheck(false)->distinct(true)
			->from(array('p' => 'seguro.propostas'), null)
			->join(array('pp' => 'seguro.propostas_proponentes'), 'p.id = pp.id_proposta', null)
			->join(array('ppa' => 'seguro.propostas_parcelas'), 'p.id = ppa.id_proposta', 'sum(vl_subvencao_estadual) as acumulado_subvencao')
			->join(array('s' => 'sistema.status'), 'p.id_status = s.id', null)
			->join(array('pr' => 'seguro.propostas_propriedades'), 'p.id = pr.id_proposta', null)
			->join(array('m' => 'sistema.municipios'), 'm.id = pr.id_municipio', null)
			->join(array('e' => 'sistema.estados'), 'e.id = m.id_estado', null)
			->join(array('pd' => 'produto.produtos'), 'p.id_produto = pd.id', null)
			->join(array('pg' => 'produto.produtos_geral'), 'pd.id_produto_geral = pg.id', null)
			->join(array('pc' => 'produto.culturas'), 'pg.id_cultura = pc.id', null)
			->where("seguro.dt_vigencia_inicio_original(p.id) between '$ano-01-01' and '$ano-12-31'")
			->where("s.ds_chave not in ('NAO_ENVIADA' , 'DEVOLVIDA' , 'PROPOSTA_CANCELADA' , 'APOLICE_CANCELADA', 'PROPOSTA_INCOMPLETA' , 'ORCAMENTO_ENDOSSO', 'ENDOSSO_INCOMPLETO', 'SOLICITACAO_CANCELADA')")
			->where("pp.cpf_cnpj = ?", $cpf_cnpj)
			->where("p.id <> ?", $id_proposta)
			->where("e.ds_sigla = ?", $sigla_uf)
			->where("pc.id in (".$id_cultura.")");

		$value = $this->getAdapter()->fetchOne($Select);

		return ($value ? $value : 0);
	}
	public function getValorSubvencaoEstadualAnoPorCulturaCotacao($cpf_cnpj, $inicioVigencia, $id_proposta = "", $sigla_uf, $id_cultura) {
		$ano = substr($inicioVigencia, 0, 4);

		$Select = $this->select()->setIntegrityCheck(false)->distinct(true)
			->from(array('p' => 'seguro.propostas'), null)
			->join(array('pp' => 'seguro.propostas_proponentes'), 'p.id = pp.id_proposta', null)
			->join(array('ppa' => 'seguro.propostas_parcelas'), 'p.id = ppa.id_proposta', 'sum(vl_subvencao_estadual) as acumulado_subvencao')
			->join(array('s' => 'sistema.status'), 'p.id_status = s.id', null)
			->join(array('pr' => 'seguro.propostas_propriedades'), 'p.id = pr.id_proposta', null)
			->join(array('m' => 'sistema.municipios'), 'm.id = pr.id_municipio', null)
			->join(array('e' => 'sistema.estados'), 'e.id = m.id_estado', null)
			->join(array('pd' => 'produto.produtos'), 'p.id_produto = pd.id', null)
			->join(array('pg' => 'produto.produtos_geral'), 'pd.id_produto_geral = pg.id', null)
			->join(array('pc' => 'produto.culturas'), 'pg.id_cultura = pc.id', null)
			->where("seguro.dt_vigencia_inicio_original(p.id) between '$ano-01-01' and '$ano-12-31'")
			->where("s.ds_chave not in ('NAO_ENVIADA' , 'DEVOLVIDA' , 'PROPOSTA_CANCELADA' , 'APOLICE_CANCELADA', 'PROPOSTA_INCOMPLETA' , 'ORCAMENTO_ENDOSSO', 'ENDOSSO_INCOMPLETO', 'SOLICITACAO_CANCELADA')")
			->where("pp.cpf_cnpj = ?", $cpf_cnpj)
			->where("e.ds_sigla = ?", $sigla_uf)
			->where("pc.id in (".$id_cultura.")");
			
			if ($id_proposta !== "") {
				$Select->where("p.id <> ?", $id_proposta);
			}
		$value = $this->getAdapter()->fetchOne($Select);

		return ($value ? $value : 0);
	}

	public function validacaoReceitaOK($cpf_pnpj){
		$Rs = $this->fetchRow("cpf_cnpj = '$cpf_pnpj'");
		if ($Rs->fl_validacao_receita){
			return true;

		} else {
			return false;
		}

	}

	public function inadimplente($cpf_pnpj){
		$Rs = $this->fetchRow("cpf_cnpj = '$cpf_pnpj'");
		if ($Rs->fl_inadimplente == true){
			return true;
		} else {
			return false;
		}
	
	}
	
	public function setReceitaValidado($cpf_cnpj){
		return $this->getAdapter()->query("update seguro.proponentes set fl_validacao_receita = true where cpf_cnpj = '$cpf_cnpj'");
	}

	public function getProponente($cpf_cnpj) {
		
		$colunasMunicipio = [
			'id_estado',
			'ds_nome_municipio',
			'ds_latitude',
			'ds_longitude',
			'vl_altitude',
			'vl_area',
			'ds_ano_instalacao',
			'cd_bacen',
			'nr_ibge',
			'nr_cep',
			'id_regiao'
		];
		$colunasEstado = ['ds_nome_estado', 'ds_sigla', 'nr_ibge', 'id_pais'];

		$select = $this->select()->setIntegrityCheck(false);
		$select->from(array('p' => 'seguro.proponentes'));
		$select->join(array('m' => 'sistema.municipios'), 'p.id_municipio = m.id', $colunasMunicipio);
		$select->join(array('e' => 'sistema.estados'), 'm.id_estado = e.id', $colunasEstado);
		$select->where('cpf_cnpj = ?', $cpf_cnpj);
		$select->where('p.fl_del is not true');
		$select->where('p.fl_ativo is true');
		$row = $this->fetchRow($select);

		if ($row) {
			$row->dt_documento_exp = Agro_Util::formatDate($row->dt_documento_exp, Zend_Date::DATES);
			$row->dt_nascimento = Agro_Util::formatDate($row->dt_nascimento, Zend_Date::DATES);

			return $row->toArray();
		}else{
			$this->removeSocio($cpf_cnpj);
		}
	}

	public function removeSocio($cpf_cnpj){
		try{
			//pega o id principal pra excluir os dependentes
			$Select = $this->select()->setIntegrityCheck(false);
			$Select->from(array('pps' => 'seguro.propostas_proponentes_socios'));
			$Select->where('pps.cnpj_segurado = ?', $cpf_cnpj);
			$id = $this->_db->fetchOne($Select);

			if($id){
				$this->getAdapter()->query("DELETE FROM seguro.propostas_proponentes_socios WHERE id_parent = $id");
			}

			$this->getAdapter()->query("DELETE FROM seguro.propostas_proponentes_socios WHERE cnpj_segurado = '{$cpf_cnpj}'");

			return true;

		}catch (Exception $e){
			die($e);
		}
	}

    public function getValorSubvencaoFederalAnoGrupo($cpf_cnpj, $id_proposta = "", $inicioVigencia, array $idsTipoProduto) {
        $ano = substr($inicioVigencia,0,4);
        $tiposProduto = [];

        if (empty($idsTipoProduto)) {
            return 0;
        }

        foreach ($idsTipoProduto as $id) {
            if ((int) $id === Produto_Model_Tipos::MULTIRRISCO) {
                continue;
            }

            $tiposProduto[] = "'{$id}'";
        }

        $SelectDentro = $this->select()->setIntegrityCheck(false)->distinct(true);
        $SelectDentro->from(array('p' => 'seguro.propostas'), 'p.id');
        $SelectDentro->join(array('pp' => 'seguro.propostas_proponentes'), 'p.id = pp.id_proposta', null);
        $SelectDentro->join(array('ppa' => 'seguro.propostas_parcelas'), 'p.id = ppa.id_proposta', 'ppa.nr_parcela, ppa.vl_subvencao_federal');
        $SelectDentro->join(array('s' => 'sistema.status'), 'p.id_status = s.id', null);
        $SelectDentro->join(array('prod' => 'produto.produtos'), 'prod.id = p.id_produto', null);
        $SelectDentro->join(array('pgar' => 'produto.produtos_grupos_atributos_rn'), 'pgar.id_produto = prod.id', null);
        $SelectDentro->join(array('par' => 'produto.produtos_atributos_rn'), 'par.id_grupo_atributo_rn = pgar.id', null);
        $SelectDentro->join(array('ar' => 'produto.atributos_rn'), 'ar.id = par.id_atributo_rn', null);
        $SelectDentro->joinLeft(array('pgarp' => 'produto.produtos_grupos_atributos_rn_proponentes'), 'pgarp.id_grupo_atributo_rn = pgar.id', null);
        $SelectDentro->joinLeft(array('prop' => 'seguro.proponentes'), 'prop.id = pgarp.id_proponente', null);
        $SelectDentro->where("seguro.dt_vigencia_inicio_original(p.id) between '$ano-01-01' and '$ano-12-31'");
        $SelectDentro->where("s.ds_chave not in ('NAO_ENVIADA' , 'DEVOLVIDA' , 'PROPOSTA_CANCELADA' , 'APOLICE_CANCELADA', 'PROPOSTA_INCOMPLETA' , 'ORCAMENTO_ENDOSSO', 'ENDOSSO_INCOMPLETO', 'ENDOSSO_ANULADO', 'ENDOSSO_CANCELADO', 'SOLICITACAO_CANCELADA')");
        $SelectDentro->where("pp.cpf_cnpj = ?", $cpf_cnpj);
        $SelectDentro->where("string_to_array(ds_valor, ',') && array[" . implode(', ', $tiposProduto) . "]");
        $SelectDentro->where("ar.ds_chave_rn = ?", Produto_Model_Atributos::DS_CHAVE_PROD_SUBVENCAO_FEDERAL_VALOR_MAX_GRUPO);
        $SelectDentro->where("((prop.cpf_cnpj = '{$cpf_cnpj}' AND pgar.fl_grupo_padrao = false) OR (pgar.fl_grupo_padrao = true))");

        if($id_proposta){
            $SelectDentro->where("p.id <> ?", $id_proposta);
        }
		
		$SelectFora = "SELECT SUM(fora.vl_subvencao_federal) AS acumulado_subvencao FROM ($SelectDentro) as fora;";
        $value = $this->getAdapter()->fetchOne($SelectFora);

        if($value < 0 || !$value){
            $value = 0;
        }

        return ($value ? $value : 0);
    }

    public function getInadimplentesById(array $idsProponentes)
    {
        $select = $this->select()->setIntegrityCheck();
        $select->from(['sp' => "{$this->_schema}.{$this->_name}"], ['id', 'ds_nome_proponente', 'cpf_cnpj']);
        $select->where('sp.fl_inadimplente is true');
        $select->where('sp.id in (' . implode(', ', $idsProponentes) . ')');

        return $this->fetchAll($select)->toArray();
    }
	
	/**
	 * Retorna se o proponente de uma proposta está inadimplente
	 *
	 * @param int $idProposta
	 * @return bool
	 */
	public function isInadimplenteByProposta(int $idProposta): bool
	{
		$select = $this->select()->setIntegrityCheck();
        $select->from(['sp' => "{$this->_schema}.{$this->_name}"], ['cpf_cnpj']);
		$select->join(['pp' => "seguro.propostas_proponentes"], "pp.cpf_cnpj = sp.cpf_cnpj", false);
        $select->where('sp.fl_inadimplente is true');
        $select->where('pp.id_proposta = ?', $idProposta);

		$rs = $this->getAdapter()->fetchOne($select);
        return !empty($rs);
	}
}
