<?php

class Agro_Db_Table_Row_Proposta extends Agro_Db_Table_Row_Dao_Proposta {

	public function apolice() {
		return $this->vl_custo_apolice;
	}

	public function fora_periodo_renovacao() {
		if ($this->id_proposta_renovada) {
			$propriedade = $this->propriedade();
			$comercializacao = $this->comercializacao($propriedade['id_estado'], $propriedade['id_municipio']);

			if (strtotime($comercializacao['dt_comercializacao_fim']) < strtotime(date('Y-m-d'))) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}

	public function comercializacao($estado=false, $municipio=false, ?int $idUsuario = null, int $idProponente = null) {
        $propriedade = $this->propriedade();

	    if (!empty($idProponente)) {
            $select = Agro_Db_Table_Abstract::getDefaultAdapter()->select();
            $select->from(array('c' => 'comercializacao.comercializacoes'), '*');
            $select->join(array('m' => 'comercializacao.comercializacoes_municipios'), 'c.id = m.id_comercializacao', false);
            $select->join(array('p' => 'comercializacao.comercializacoes_proponentes'), 'c.id = p.id_comercializacao', false);
            $select->where("id_produto = ?", $this->id_produto, 'integer');
            $select->where("id_municipio = ?", $propriedade['id_municipio'], 'integer');
            $select->where("id_proponente = ?", $idProponente, 'integer');

            $Row = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchRow($select);

            if ($Row && $Row['fl_ativo'] === true) {
                return $Row;
            }
        }

	    if (!empty($idUsuario)) {
            $select = Agro_Db_Table_Abstract::getDefaultAdapter()->select();
            $select->from(array('c' => 'comercializacao.comercializacoes'), '*');
            $select->join(array('u' => 'comercializacao.comercializacoes_usuarios'), 'c.id = u.id_comercializacao', false);
            $select->where("id_produto = ?", $this->id_produto, 'integer');
            $select->where("id_usuario = ?", $idUsuario, 'integer');

            $Row = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchRow($select);

            if ($Row && $Row['fl_ativo'] === true) {
                return $Row;
            }
        }

    	$select = Agro_Db_Table_Abstract::getDefaultAdapter()->select();
		$select->from(array('c' => 'comercializacao.comercializacoes'), '*');
		$select->join(array('m' => 'comercializacao.comercializacoes_municipios'), 'c.id = m.id_comercializacao', false);
		$select->where("id_produto = ?", $this->id_produto, 'integer');
		$select->where("id_municipio = ?", $propriedade['id_municipio'], 'integer');
		$Row = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchRow($select);

		if ($Row) {
			if($Row['fl_ativo'] == false) return false;
			return $Row;
		} else {
			$select = Agro_Db_Table_Abstract::getDefaultAdapter()->select();
			$select->from(array('c' => 'comercializacao.comercializacoes'), '*');
			$select->join(array('e' => 'comercializacao.comercializacoes_estados'), 'c.id = e.id_comercializacao', false);
			$select->where("id_produto = ?", $this->id_produto, 'integer');
			$select->where("id_estado = ?", $propriedade['id_estado'], 'integer');
			$Row = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchRow($select);

			if ($Row) {
				if($Row['fl_ativo'] == false) return false;
				return $Row;
			}
		}
    }

	public function agrupamento(
		bool $consideraOrcamento = true,
		array $valoresFranquia = [],
		bool $flCoberturaPrincipal = false
	) {
	    if ($consideraOrcamento) {
            $return = $this->_agrupamentoOrcamento();
            if ($return !== false) return $return;
        }

        $return = $this->_agrupamentoUsuario($valoresFranquia);
        if ($return !== false && !empty($return)) {
            return $return;
        }

		$return = $this->_agrupamentoProponenteUsuario($valoresFranquia);
		if ($return !== false && !empty($return)) {
			return $return;
		}
		
		$return = $this->_agrupamentoProponente($valoresFranquia);
		if ($return !== false && !empty($return)) {
			return $return;
		}
		
		$return = $this->_agrupamentoPreposto($valoresFranquia);
		if ($return !== false && !empty($return)) {
			return $return;
		}
		
		$return = $this->_agrupamentoCorretor($valoresFranquia);
		if ($return !== false && !empty($return)) {
			return $return;
		}
		
		$return = $this->_agrupamentoMunicipio($valoresFranquia);
		if ($return !== false && !empty($return)) {
			return $return;
		}
		
		$return = $this->_agrupamentoEstado($valoresFranquia);
		if ($return !== false && !empty($return)) {
			return $return;
		}
		
		throw new Exception('Agrupamento de Taxas não configurado. Entre em contato com a AgroBrasil para melhor esclarecimento.');
	}

	public function area() {
		$Select = $this->select()->setIntegrityCheck(false)->from(array('i' => 'sumario.itens_segurados'), 'vl_area')->where('i.id_proposta = ?', $this->id);
		$area = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne($Select);
		return ($area ? $area : 0);
	}

	public function min_dt_semeadura($modulo="", $name="") {
		$Select = $this->select()->setIntegrityCheck(false)->distinct(true);
		$Select->from(array('ist' => 'seguro.itens_segurados'), false);
		$Select->join(array('istc' => 'seguro.itens_segurados_complemento'), 'ist.id = istc.id_item_segurado', 'min(dt_semeadura)');
		$Select->where('ist.id_proposta = ?', $this->id);

    	return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne($Select);
	}

	public function min_dt_semeadura_plantio(){
		$Select = $this->select()->setIntegrityCheck(false)->distinct(true);
		$Select->from(array('ist' => 'seguro.itens_segurados'), false);
		$Select->join(array('istc' => 'seguro.itens_segurados_complemento'), 'ist.id = istc.id_item_segurado', "to_char(min(LEAST(dt_semeadura, dt_plantio)), 'DD/MM/YYYY')");
		$Select->where('ist.id_proposta = ?', $this->id);

		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne($Select);
	}

	public function arquivos() {
		$Select = $this->select()->setIntegrityCheck(false)->from('seguro.propostas_arquivos')->where('id_proposta = ?', $this->id);
    	return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);
	}

    public function atributos($tipo='', $chave='')
    {
    	$atributos = (new Produto_Model_Atributogrupos())->getAtributosProposta($this, $tipo);
        $att = $atributosRetorno = array();

    	if (is_array($atributos)) {
    		foreach ($atributos as $Atributo) {
    			$att[$Atributo['grupo_padrao']][$Atributo['nivel_hierarquia']][$Atributo['ds_chave_rn']] = $Atributo['ds_valor'];
    		}

            $atributosRetorno = current($att[1]);

            /**
             * Caso hajam atributos que não sejam do grupo padrão, utilizamos os valores desta pegando o primeiro
             * grupo encontrado com base na hierarquia
             */
            if (!empty($att[0])) {
                $atributosRetorno = current($att[0]);
            }
    	}

    	if ($chave) {
    		return $atributosRetorno[$chave];
    	}

    	return $atributosRetorno;
    }

	public function atributo_rn($modulo, $name) {

		$Select = $this->select()->setIntegrityCheck(false)->distinct(true);
		$Select->from(array('g' => 'produto.produtos_grupos_atributos_rn'), false);
		$Select->join(array('p' => 'produto.produtos_atributos_rn'), 'g.id = p.id_grupo_atributo_rn', 'ds_valor');
		$Select->join(array('a' => 'produto.atributos_rn'), 'a.id = p.id_atributo_rn', false);
		$Select->join(array('t' => 'produto.tipo_atributo'), 't.id = a.id_tipo_atributo', false);
		$Select->join(array('m' => 'produto.atributos_modulos'), 'm.id = a.id_atributo_modulo', false);
		$Select->where('m.ds_chave_atributo_modulo = ?', $modulo);
		$Select->where('g.id_produto = ?', $this->id_produto);
		$Select->where('a.ds_chave_rn = ?', $name);
		$Select->where('p.fl_del is false');

    	return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne($Select);
	}

	public function atributos_rn($modulo, $parent=null) {
		$Select = $this->select()->setIntegrityCheck(false)->distinct(true);
		$Select->from(array('g' => 'produto.produtos_grupos_atributos_rn'), false);
		$Select->join(array('p' => 'produto.produtos_atributos_rn'), 'g.id = p.id_grupo_atributo_rn', 'ds_valor');
		$Select->join(array('a' => 'produto.atributos_rn'), 'a.id = p.id_atributo_rn');
		$Select->join(array('t' => 'produto.tipo_atributo'), 't.id = a.id_tipo_atributo', array('ds_chave_tipo_atributo'));
		$Select->join(array('m' => 'produto.atributos_modulos'), 'm.id = a.id_atributo_modulo', false);
		$parent ? $Select->where('a.id_parent = ?', $parent) : $Select->where('a.id_parent = 0');
		$Select->where('m.ds_chave_atributo_modulo = ?', $modulo);
		$Select->where('g.id_produto = ?', $this->id_produto);
		$Select->where('p.fl_del is false');
		$Select->order('a.ds_ordem');
		
		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);
	}

	public function autorizacaoPreposto() {
		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll("select fl_autorizacao_cancelamento, fl_autorizacao_endosso from sistema.prepostos where id_usuario = {$this->id_usuario_criacao}");
	}

	public function beneficiarios() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p' => 'seguro.propostas_beneficiarios'), array('p.*','to_char(p.dt_nascimento, \'DD/MM/YYYY\') as dt_nascimento'));
		$Select->joinLeft(array('b' => 'sistema.bancos'), 'p.id_banco = b.id', 'ds_nome_banco');
		$Select->joinLeft(array('ib' => 'seguro.informacoes_bancarias'), 'ib.id_proposta = '.$this->id.' and ib.cpf_cnpj = p.nr_cpf_cnpj', array('nu_conta_corrente','nu_digito_conta_corrente','nu_agencia','nu_digito_agencia','id_forma_pagamento'));
		$Select->joinLeft(array('bc' => 'sistema.bancos'), 'bc.id = ib.id_banco', 'nr_banco');
		$Select->where("p.id_proposta = ?", $this->id);
		$Select->where("p.fl_del = false");
		$Select->order('id asc');
    	$Rs = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);
    	
    	$result = array();
		if ($Rs) {
			foreach ($Rs as $beneficiario) {
				$arr = $beneficiario;

				if (strlen($beneficiario['nr_cpf_cnpj']) > 14){
					$arr['tp_pessoa'] = 'J';
				} else {
					$arr['tp_pessoa'] = 'F';
				}

				$result[] = $arr;
			}
		}

		return $result;
	}

	public function boletos() {
		$select = $this->select()->setIntegrityCheck(false)->distinct(true);
		$select->from(array('b' => 'seguro.proposta_boletos'));
		$select->where('b.id_proposta = ?', $this->id);
		$select->where('b.id_versao = ?', $this->id_versao);

		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($select);
	}

	public function boleto_vencido() {
		$boletos = $this->boletos();
		if (count($boletos)) {
			$parcela = current($this->parcelas(1));

			if (strtotime($parcela['dt_vencimento']) < strtotime(date('Y-m-d'))) {
				return true;
			}
		}

		return false;
	}

	public function carencia() {
		$dateTime = (new Seguro_Model_Propostas())->getDataTransmissaoPropostaMae($this->id);

		$configuracoes = (new Produto_Model_CondicaoEspecialConfiguracao())->getConfiguracoesPorProdutoData(
			$this->id_produto,
			$dateTime
		);

		if (empty($configuracoes)) {
			return [];
		}

		$idsConfiguracoesCondicoesEspeciais = array_column($configuracoes, 'id');

		$select = $this->select()->setIntegrityCheck(false)->distinct(true);
		$select->from(array('pc' => 'produto.produtos_coberturas'), 'fl_cobertura_principal');
		$select->join(array('pce' => 'produto.produtos_coberturas_condicoes_especiais'), 'pc.id_cobertura = pc.id_cobertura and pc.id_produto = pce.id_produto',null);
		$select->join(array('ce' => 'produto.condicoes_especiais'), 'pce.id_condicao_especial = ce.id', array('ds_titulo', 'ar_condicoes_adicionais', 'ds_complemento'));
		$select->join(array('sc' => 'seguro.propostas_coberturas'), 'sc.id_cobertura = pc.id_cobertura and sc.id_cobertura = pce.id_cobertura', null);
		$select->join(
			array('config' => 'produto.condicao_especial_configuracao'),
			'config.id_condicao_especial = ce.id',
			'ds_condicao_especial'
		);
		$select->where('pc.fl_contratacao_automatica = false');
		$select->where('pc.id_produto = ?', $this->id_produto);
		$select->where('sc.id_proposta = ?', $this->id);
		$select->where('config.id IN (?)', $idsConfiguracoesCondicoesEspeciais);
		$select->order('fl_cobertura_principal DESC');

		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($select);
	}

	public function cobranca() {
	    $Produto = $this->produto();

		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p'=>'seguro.propostas_coberturas'), array("count(*) as total", "sum(vl_premio) as liquido"));
		$Select->where("p.id_proposta = ?", $this->id);
		$Select->where("p.fl_ativo = true");
		$Row = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchRow($Select);

		$ret = array();
		$ret['condicao_comercial'] = $Row['total'];
		$ret['premio_liquido'] = $Row['liquido'];
		$ret['iof'] = 'isento';

		if($this->id_versao && $Produto['ds_nome_fantasia'] == 'ESSOR SEGUROS'){
		    $sqlVersao = " and b.id_versao = ".$this->id_versao;
		}
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p'=>'seguro.propostas_parcelas'), array('nr_parcela', 'vl_total', 'vl_segurado', 'vl_subvencao_federal', 'vl_subvencao_estadual', 'dt_vencimento', 'fl_pago as fl_pago_parcela', 'id_motivo_cobranca_subvencao_segurado'));
		$Select->joinLeft(array('b' => 'seguro.proposta_boletos'), " p.id_proposta = b.id_proposta and p.nr_parcela = b.nr_parcela and b.fl_ativo = true $sqlVersao", array('ds_identificador'));
		$Select->where("p.id_proposta = ?", $this->id);
		$Select->where("p.fl_ativo = true");
		$Select->order("p.nr_parcela");
		$Rs = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);

		if ($Rs) {
			foreach ($Rs as $Row) {
				$Select = Agro_Db_Table_Abstract::getDefaultAdapter()->select()->distinct();
				$Select->from('seguro.proposta_boletos');
				$Select->where('id_proposta = ?', $this->id);
				if($this->id_versao && $Produto['ds_nome_fantasia'] == 'ESSOR SEGUROS'){
				    $Select->where('id_versao = ?', $this->id_versao);
				}
				$Select->where('nr_parcela = ?', ($Row['nr_parcela'] ? $Row['nr_parcela'] : 1));
				$Select->where('fl_ativo = true');
				$Boleto = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchRow($Select);

				if ($this->isEndosso()) {
					if ($this->endossoReducao()) {
						if ($Row['vl_total'] < 0) {
							$Row['vl_total'] = $Row['vl_total'] * (-1);
						}

						if ($Row['vl_segurado'] < 0) {
							$Row['vl_segurado'] = $Row['vl_segurado'] * (-1);
						}

						if ($Row['vl_subvencao_federal'] < 0) {
							$Row['vl_subvencao_federal'] = $Row['vl_subvencao_federal'] * (-1);
						}

						if ($Row['vl_subvencao_estadual'] < 0) {
							$Row['vl_subvencao_estadual'] = $Row['vl_subvencao_estadual'] * (-1);
						}
					}
				}

				$ret['parcelamento'][$Row['nr_parcela']] = $Row;
				$ret['parcelamento'][$Row['nr_parcela']]['nu_boleto'] = $Boleto['nu_boleto'];
				$ret['parcelamento'][$Row['nr_parcela']]['fl_pago']   = $Boleto['fl_pago'];
			}
		}

		return $ret;
	}

	public function comissao() {
		//$corretor = $this->corretor();
		//return $corretor['vl_comissao'];

		return 1;
	}

	public function condicoes($inicioVigencia=null) {

		$corretor = self::corretor();
    	$preposto = self::preposto();
    	$proponente = self::proponente();
    	$propriedade = self::propriedade();
		
    	/*
    	 * Se o segurado estiver inadimplente, busca as condições configuradas para inadimplentes por:
    	 * - CPF/CNPJ
    	 * - Preposto
    	 * - Corretor
    	 * - Condição default para inadimplente
    	 */
    	if ($this->inadimplente()) {
   			$Rs = $this->_getParcelamentoInadimplentes(false, $proponente['cpf_cnpj']);

			if (empty($Rs)) {
				$Rs = $this->_getParcelamentoInadimplentes($preposto['id_usuario'], false);
			}
    		
			if (empty($Rs)) {
				$Rs = $this->_getParcelamentoInadimplentes($corretor['id_usuario'], false);
			}

			if (empty($Rs)) {
				$Rs = $this->_getParcelamentoInadimplentes();

				if (empty($Rs)) {
					$Rs = array();
					$Rs['nr_parcelas'] = 1;
				}
			}
			
			return $Rs;
    	}
		
		$Rs = $this->_getParcelamentoProposta($inicioVigencia);
		$temParcelamentoProposta = !empty($Rs);
		
    	if ($proponente['cpf_cnpj'] && !$temParcelamentoProposta) {
    		$Rs = $this->_getParcelamentoProponente($proponente['cpf_cnpj'], $inicioVigencia);
    	}
		
		if (!$Rs) {
			if ($preposto['id_usuario']) {
				$Rs = $this->_getParcelamentoUsuario($preposto['id_usuario'], $inicioVigencia);
			}
		}
		
		if (!$Rs) {
			if ($corretor['id_usuario']) {
				$Rs = $this->_getParcelamentoUsuario($corretor['id_usuario'], $inicioVigencia);
			}
		}

		if (!$Rs) {
			if ($propriedade['id_municipio']) {
				$Rs = $this->_getParcelamentoMunicipio($propriedade['id_municipio'], $inicioVigencia);
			}
		}
		
		/**
		 * Se a condição de pagamento encontrada estiver vinculada a outras propostas que não sejam a proposta em questão,
		 * essa condição de pagamento não poderá ser utilizada e será buscada a condição padrão
		 */
		if (!empty($Rs) && !$temParcelamentoProposta) {
			$idsProposta = (new Produto_Model_CondicaoPagamentoProposta())
				->getIdsPropostasVinculadas((int) $Rs['id_condicao_pagamento']) ?? [];

			if (!empty($idsProposta) && !in_array($this->id, $idsProposta)) {
				$Rs = null;
			}
		}
		
		if (!$Rs) {
			$Rs = $this->_getParcelamentoDefault();
		}

		return $Rs;
    }

	public function clientes_propostas() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('cp' => 'seguro.clientes_propostas'));
		$Select->from(array('c' => 'seguro.clientes'), 'c.id = cp.id_cliente');
		$Select->where('cp.id_proposta = ?', $this->id);
    	return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);
	}

	public function cliente() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('cp' => 'seguro.clientes_propostas'),null);
		$Select->join(array('c' => 'seguro.clientes'), 'c.id = cp.id_cliente', array('ds_nome_cliente'));
		$Select->where('cp.id_proposta = ?', $this->id);
    	return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne($Select);
	}

	public function coberturas($tipo=false, $all=false) {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('c' => 'produto.coberturas'), array('ds_nome_cobertura', 'ds_descricao_cobertura', 'ds_chave_cobertura', 'cd_cobertura_seguradora', 'id_legacy'));
		$Select->join(array('pc' => 'produto.produtos_coberturas'), 'c.id = pc.id_cobertura', array('id_cobertura','fl_cobertura_principal', 'fl_taxa_relacionada', 'fl_somente_renovacoes', 'fl_vistoria_previa', 'vl_lmi', 'id_condicao_especial', 'fl_vistoria_preliminar', 'fl_cobertura_dependente', 'id_cobertura_dependencia', 'fl_exibir_franquia', 'fl_vistoria_final', 'id_tipo_liquidacao', 'fl_contratacao_automatica', 'nr_prioridade_liquidacao', 'fl_exibir_regulacao_perdas'));
		$Select->where('pc.id_produto = ?', $this->id_produto);
		$Select->order(array('pc.fl_cobertura_principal desc', 'c.id'));

		if (!$all) {
			$Select->where('pc.fl_ativo = true');
		}

		if ($tipo == 'principal') {
			$Select->where('fl_cobertura_principal is true');
			return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchRow($Select);
		}

		if ($tipo == 'adicional') {
			$Select->where('fl_cobertura_principal is false');
		}
		
		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);
	}

	public function coberturas_contratadas($tipo=false) {
		$dateTime = $this->dt_transmissao
			? DateTime::createFromFormat('Y-m-d H:i:s', $this->dt_transmissao)
			: (new DateTime('now'));

		if ($this->id != $this->id_proposta_mae) {
			$proposta = (new Seguro_Model_Propostas())->find($this->id_proposta_mae)->current();
			
			if (empty($proposta['dt_transmissao'])) {
				$dateTime = new DateTime('now');
			} else {
				$dateTime = DateTime::createFromFormat('Y-m-d H:i:s', $proposta['dt_transmissao']);
			}
		}
		
		$configuracoesCoberturas = (new Produto_Model_ProdutoCoberturaConfig())->getConfiguracoesPorProdutoData(
			$this->id_produto,
			$dateTime
		);

		$idsConfiguracoesCoberturas = array_column($configuracoesCoberturas, 'id');

		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('pc' => 'seguro.propostas_coberturas'));
		$Select->join(array('c' => 'produto.coberturas'), 'c.id = pc.id_cobertura');
		$Select->join(array('d' => 'produto.produtos_coberturas'), 'c.id = d.id_cobertura and d.id_produto = '.$this->id_produto, array(
			'fl_cobertura_principal',
			'fl_taxa_relacionada',
			'fl_somente_renovacoes',
			'fl_vistoria_previa',
			'id_condicao_especial',
			'fl_vistoria_preliminar',
			'fl_cobertura_dependente',
			'id_cobertura_dependencia',
			'fl_exibir_franquia',
			'fl_vistoria_final',
			'id_tipo_liquidacao',
			'fl_contratacao_automatica',
			'nr_prioridade_liquidacao',
			'fl_exibir_regulacao_perdas',
			'ds_observacao',
			'ds_observacao_interna',
			'cd_cobertura_seguradora as codigo_cobertura_seguradora'
		));
		
		$Select->join(
			array('pcconfig' => 'produto.produto_cobertura_config'),
			'pcconfig.id_produto = d.id_produto AND pcconfig.id_cobertura = d.id_cobertura',
			array('ds_frase_outros_riscos_excluidos', 'ds_frase_condicoes_particulares')
		);

		$Select->where('id_proposta = ?', $this->id);
		$Select->where('pc.fl_ativo is true');
		$Select->where('pc.fl_del is false');
		$Select->where('pcconfig.id IN (?)', $idsConfiguracoesCoberturas);

		if ($tipo == 'principal') {
			$Select->where('pc.fl_principal is true');
			return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchRow($Select);
		}

		if ($tipo == 'adicional') {
			$Select->where('pc.fl_principal is false');
		}
		$Select->order('c.id asc');
		
		$Rs = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);
		$return = array();
		if (count($Rs)) {
			foreach ($Rs as $Row) {
				$return[$Row['id_cobertura']] = $Row;
			}
		}

		return $return;
	}

	public function cor() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('s' => 'sistema.status'), 'ds_cor');
		$Select->where('id = ?', $this->id_status);

		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne($Select);
	}

	public function corretor() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('pc' => 'seguro.propostas_corretores'), array('vl_comissao','vl_comissao_assessoria'));
		$Select->join(array('c' => 'sistema.corretores'), 'pc.id_usuario = c.id_usuario');
		$Select->where('id_proposta = ?', $this->id);

		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchRow($Select);
	}

	public function comercial() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('u' => 'sistema.prepostos'), 'id_comercial');
		$Select->where('id_usuario = ?', $this->id_usuario_criacao);
		$rs = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchRow($Select);

		if(!$rs){
    		$Select = $this->select()->setIntegrityCheck(false);
    		$Select->from(array('u' => 'sistema.corretores'), 'id_comercial');
    		$Select->where('id_usuario = ?', $this->id_usuario_criacao);
    		$rs = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchRow($Select);
		}

		return $rs;
	}

	public function corretores_renovacao() {
		$Select = $this->select()->setIntegrityCheck(false)->from('seguro.propostas_corretores_renovacao')->where('id_proposta = ?', $this->id);
    	return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);
	}

	public function croquis() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p'=>'seguro.propostas_arquivos'), array('ds_nome_arquivo', 'fl_origem_upload'));
		$Select->join(array('t'=>'sistema.tipo_arquivo'), 'p.id_tipo_arquivo = t.id', null);
		$Select->where("upper(t.ds_nome_arquivo) = upper(?)", "CROQUI_PROPOSTA");
		$Select->where("p.id_proposta = ?", $this->id);
		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);
	}

	public function digitador() {
		$preposto = self::preposto();

		if ($preposto) {
			return $preposto['ds_nome_preposto'];
		} else {
			$corretor = self::corretor();
			return $corretor['ds_nome_fantasia'];
		}
	}

	public function doc() {
	    return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne("select seguro.id_proposta_mae_completo({$this->id})");
    }

    public function proposta_mae() {
    	return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne("select seguro.id_proposta_mae({$this->id})");
    }

	public function endosso() {
		$Select = $this->select()->setIntegrityCheck(false)->from('seguro.propostas_endosso')->where('id_proposta = ?', $this->id);
    	return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);
	}

	public function isEndosso() {
		$status = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne("select ds_chave from sistema.status where id = {$this->id_status}");
		switch ($status) {
			case 'ENDOSSO_INCOMPLETO':
			case 'ORCAMENTO_ENDOSSO':
			case 'ENDOSSO_AGUARDANDO_ENVIO_SEG':
			case 'SOLICITACAO_ENDOSSO':
				return true;
			default:
				return false;
		}
	}

	public function lmga() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('i' => 'sumario.itens_segurados'), 'vl_lmga');
		$Select->where('i.id_proposta = ?', $this->id);
		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne($Select);
	}

	/**
	 * Função temporária e de exceção para buscar a LMGA de um grupo de variedades na maçã
	 * Solicitação: 921
	 */
	public function lmga_parcelamento_maca() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('i' => 'seguro.itens_segurados'), 'sum(vl_lmga)');
		$Select->where('i.id_proposta = ?', $this->id);
		$Select->where('i.id_variedade in (348, 845, 868, 1034, 1350, 1688)');
		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne($Select);
	}

	/**
	 * Função temporária e de exceção para buscar a LMGA de um grupo de variedades na Uva de Vinho e Uva de Mesa
	 * Solicitação: 1288
	 */
	public function lmga_variedades_uva() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('i' => 'seguro.itens_segurados'), 'sum(vl_lmga)');
		$Select->where('i.id_proposta = ?', $this->id);
		$Select->where('i.id_variedade in (719, 854, 871, 1397, 1541, 1577, 1689, 4061, 4080, 4081, 4075, 4076, 4077, 4078, 4079, 4080, 4081, 4084, 4083, 867, 5388)');
		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne($Select);
	}

	/**
	 * Verifica se deve validar somente renovações sem sinsitro
	 * @param $idUsuario
	 * @return boolean
	 */
	public function renovacaoSemSinistro(int $idUsuario = null) : bool
	{
		if (!empty($this->id_proposta_renovada)) {
			$grupoPadrao = empty($idUsuario) ? true : false;
			$ProdutosAtributos = new Produto_Model_ProdutosAtributos();
			$produtoAtributos = $ProdutosAtributos->getAtributosFromProduto($this->id_produto, $grupoPadrao, 'p', true, true, $idUsuario);

			if (empty($produtoAtributos)) {
                $produtoAtributos = $ProdutosAtributos->getAtributosFromProduto($this->id_produto, true, 'p', true, true);
            }
			
			if (array_key_exists(Produto_Model_Atributos::DS_CHAVE_PROD_VALIDAR_RENOVACAO_SEM_SINISTRO, $produtoAtributos) && 
				$produtoAtributos[Produto_Model_Atributos::DS_CHAVE_PROD_VALIDAR_RENOVACAO_SEM_SINISTRO] == 1)
			{
				$modelAvisosSinistro = new Sinistro2_Model_AvisosSinistro();
				return !$modelAvisosSinistro->hasAvisoSinistroByPropostaRenovada($this->id_proposta_renovada);
			}
		}

		return true;
	}
	
	public function inadimplente() {
		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne("select fl_inadimplente from seguro.proponentes where cpf_cnpj = (select cpf_cnpj from seguro.propostas_proponentes where id_proposta = {$this->id})");
	}

	public function itens_segurados($id=null) {
	    if ($id) {
            $Select = $this->select()->setIntegrityCheck(false)->from('seguro.v_unidades_seguradas')->where('id_proposta = ?', $this->id);
        } else {
            $Select = $this->select()->setIntegrityCheck(false)->from('seguro.v_unidades_seguradas')->where('id_proposta = ?', $this->id);
        }
		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);
	}

	public function count_itens_segurados() {
		return count(self::itens_segurados());
	}

	public function observacoes($principal=true) {
		if ($principal) {
			$Select = $this->select()->setIntegrityCheck(false)->from(array('p' => 'seguro.propostas_observacoes'))->join(array('u' => 'sistema.usuarios'), 'p.id_usuario_criacao = u.id', 'ds_nome_usuario')->where('id_proposta = ?', $this->id)->where('fl_principal is true');
			return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchRow($Select);
		} else {
			$Select = $this->select()->setIntegrityCheck(false)->from(array('p' => 'seguro.propostas_observacoes'))->join(array('u' => 'sistema.usuarios'), 'p.id_usuario_criacao = u.id', 'ds_nome_usuario')->where('id_proposta = ?', $this->id)->where('fl_principal is false');
            return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);
		}
	}

	public function observacoes_arquivos() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('o' => 'seguro.propostas_observacoes'),array('o.dt_criacao as data_criacao','o.*'));
		$Select->joinLeft(array('a' => 'seguro.propostas_observacoes_arquivos'), 'o.id = a.id_observacao', 'ds_nome_arquivo');
		$Select->join(array('u' => 'sistema.usuarios'), 'u.id = o.id_usuario_criacao','ds_nome_usuario');
		$Select->where('o.id_proposta = ?', $this->id);
        $Select->where('o.fl_principal = false');
        $Select->order('o.dt_criacao');

		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);
	}

	public function observacoes_arquivos_geral($all=null, $somenteAdicionais = true) {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('pr' => 'seguro.propostas'), null);
		$Select->join(array('o' => 'seguro.propostas_observacoes'), 'pr.id = o.id_proposta', array('o.dt_criacao as data_criacao','o.*'));
		$Select->joinLeft(array('a' => 'seguro.propostas_observacoes_arquivos'), 'o.id = a.id_observacao', array('ds_nome_arquivo','a.id as id_observacao_arquivo'));
		$Select->join(array('u' => 'sistema.usuarios'), 'u.id = o.id_usuario_criacao','ds_nome_usuario');
		$Select->where('pr.id_endosso = ?', $this->id_endosso);

		if ($somenteAdicionais) {
		    $Select->where('o.fl_principal = false');
        }

		if ($all<>null) {
			$Select->where('o.fl_observacao_endosso = ?', $all);
		}
        
		$Select->order('o.dt_criacao');
          
		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);
	}

	public function parcelas($nro=null, bool $flTodosEndossos = false) {
		$this->id_versao ? 'and b.id_versao = '.$this->id_versao : '';

		$select = $this->select()->setIntegrityCheck(false)->order('p.nr_parcela');
    	$select->from(array('p' => 'seguro.propostas_parcelas'));
    	$select->join(array('pr' => 'seguro.propostas'), 'pr.id = p.id_proposta', 'ds_identificador_seguradora');
    	$select->joinLeft(array('b' => 'seguro.proposta_boletos'), 'p.id_proposta = b.id_proposta and p.nr_parcela = b.nr_parcela and b.fl_ativo = true'.($this->id_versao ? ' and b.id_versao = '.$this->id_versao : ''), array('nu_boleto', 'ds_identificador', 'fl_pago', 'id_versao'));

		if ($flTodosEndossos) {
			$select->where('pr.id_endosso = ?', $this->id_endosso);
		} else {
			$select->where('p.id_proposta = ?', $this->id);
		}

    	$select->where("p.fl_ativo = true");

    	if ($nro) {
    		$select->where("p.nr_parcela = ?", $nro);
    	}

    	return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($select);
	}

	public function pendencias() {
		$Select = $this->select()->setIntegrityCheck(false)->from(array('p' => 'seguro.propostas_pendencias'))->where('p.id_proposta = ?', $this->id);
    	return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);
	}

	public function produtividade_estimada() {
		$propriedade = self::propriedade();
		if (!self::isEndosso()) {
			$agrupamento = self::agrupamento();
		}

		if ($propriedade && $agrupamento) {
			$Select = $this->select()->setIntegrityCheck(false);
			$Select->from('comercializacao.taxas_agrupamento_municipios', 'vl_produtividade_estimada');
			$Select->where("id_municipio = ?", $propriedade['id_municipio']);

			if ($agrupamento['id']) {
				$Select->where("id_taxa_agrupamento = ?", $agrupamento['id']);
			}	
			return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne($Select);
		}
	}

	public function produto() {
		if ($this->id) {
			$Select = $this->select()->setIntegrityCheck(false);
			$Select->from(array('pr' => 'seguro.propostas'), false);
			$Select->join(array('pd' => 'produto.produtos'), 'pd.id = pr.id_produto', array('id', 'id_produto_geral', 'id_safra', 'id_seguradora', 'nr_susep', 'ds_nome_produto', 'ar_condicoes_gerais', 'cd_bacen', 'ds_nome_abreviado', 'cd_produto_seguradora', 'id_legacy', 'fl_liberado', 'ds_chave_produto', 'cd_mapa'));
			$Select->join(array('pconfig' => 'produto.produto_config'), 'pconfig.id_produto = pd.id AND pconfig.fl_ativo IS TRUE', 'id_modelo_vistoria_previa');
			$Select->join(array('pg' => 'produto.produtos_geral'), 'pg.id = pd.id_produto_geral', array('id_tipo_produto', 'id_cultura', 'id_ramo', 'ds_nome_produto_geral', 'cd_produto_geral_seguradora'));
			$Select->join(array('ps' => 'produto.safras'), 'ps.id = pd.id_safra', array('ds_nome_safra'));
			$Select->join(array('c'  => 'produto.culturas'), 'c.id = pg.id_cultura', array('id_nomenclatura', 'ds_nome_cultura', 'nr_ibge', 'ds_chave_cultura', 'cd_cultura_seguradora', 'cd_bacen', 'id_legacy'));
			$Select->join(array('e'  => 'sistema.empresas'), 'e.id = pd.id_seguradora', array('cpf_cnpj', 'ds_nome_fantasia', 'ds_razao_social'));
			$Select->where('pr.id = ?', $this->id);

			return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchRow($Select);
		}

		return;
	}

	public function preposto() {
		if ($this->id_usuario_criacao) {
			$Select = $this->select()->setIntegrityCheck(false);
			$Select->from(array('p' => 'sistema.prepostos'));
			$Select->joinLeft(array('pf' => 'sistema.prepostos_frase_declaracao'), 'p.id_prepostos_frase_declaracao = pf.id', array('ds_frase'));	
			$Select->where('p.id_usuario = ?', $this->id_usuario_criacao);

			return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchRow($Select);
		}

		return;
	}

	public function premio_liquido() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p'=>'seguro.propostas_coberturas'), "sum(vl_premio) as liquido");
		$Select->where("p.id_proposta = ?", $this->id);
		$Select->where("p.fl_ativo = true");
		$Select->where("p.fl_del = false");

		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne($Select);
	}

	public function proponente($coluna='') {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p' => 'seguro.propostas_proponentes'));
        $Select->join(array('po' => 'seguro.proponentes'), 'po.cpf_cnpj = p.cpf_cnpj', array('id as id_proponente','fl_validacao_receita','fl_restricao'));
		$Select->join(array('m' => 'sistema.municipios'), 'p.id_municipio = m.id', array('id_estado', 'ds_nome_municipio', 'ds_latitude', 'ds_longitude', 'vl_altitude', 'vl_area', 'ds_ano_instalacao', 'cd_bacen', 'nr_ibge', 'nr_cep'));
		$Select->join(array('e' => 'sistema.estados'), 'm.id_estado = e.id', array('ds_nome_estado', 'ds_sigla', 'nr_ibge', 'id_pais'));
		$Select->join(array('c' => 'sistema.paises'), 'e.id_pais = c.id', array('ds_nome_pais'));
		$Select->joinLeft(array('ec' => 'sistema.estado_civil'), 'p.id_estado_civil = ec.id', array('ds_nome_estado_civil'));
		$Select->joinLeft(array('o' => 'sistema.orgao_expedidor'), 'p.id_orgao_expedidor = o.id', array('ds_nome_orgao'));
		$Select->joinLeft(array('ae' => 'sistema.atividades_economicas'), 'p.id_atividade_economica = ae.id', array('ds_nome_atividade_economica'));
		$Select->joinLeft(array('fr' => 'sistema.faixa_remuneracao'), 'fr.id = p.id_renda', array('ds_faixa_remuneracao'));
		$Select->joinLeft(array('fe' => 'sistema.faixa_receita'), 'fe.id = p.id_patrimonio', array('ds_faixa_receita as ds_patrimonio'));
		$Select->joinLeft(array('fe2' => 'sistema.faixa_receita'), 'fe2.id = p.id_renda_bruta', array('ds_faixa_receita as ds_renda_bruta'));
		$Select->joinLeft(array('pej' => 'seguro.propostas_email_justificativa'), 'pej.id_proposta = p.id_proposta', array('nr_justificativa', 'ds_justificativa'));
		$Select->where('p.id_proposta = ?', $this->id);
		$Row = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchRow($Select);
		if ($coluna) {
			return $Row[$coluna];
		} else {
			return $Row;
		}
	}

	public function propriedade($coluna='') {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p' => 'seguro.propostas_propriedades'));
		$Select->join(array('m' => 'sistema.municipios'), 'p.id_municipio = m.id', array('id_estado', 'ds_nome_municipio', 'ds_latitude', 'ds_longitude', 'vl_altitude', 'vl_area', 'ds_ano_instalacao', 'cd_bacen', 'nr_ibge', 'nr_cep'));
		$Select->join(array('e' => 'sistema.estados'), 'm.id_estado = e.id', array('ds_nome_estado', 'ds_sigla', 'nr_ibge', 'id_pais'));
		$Select->join(array('c' => 'sistema.paises'), 'e.id_pais = c.id', array('ds_nome_pais'));

		$Select->join(array('pr' => 'seguro.propostas'), 'pr.id = p.id_proposta',null);
		$Select->join(array('pd' => 'produto.produtos'), 'pd.id = pr.id_produto',null);
		$Select->join(array('pg' => 'produto.produtos_geral'), 'pg.id = pd.id_produto_geral',null);
		$Select->joinLeft(array('mr' => 'sistema.municipios_culturas_regioes'), 'pg.id_cultura = mr.id_cultura and p.id_municipio = mr.id_municipio', array('id_regiao'));

		$Select->where('p.id_proposta = ?', $this->id);

		$Row = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchRow($Select);
		if ($coluna) {
			return $Row[$coluna];
		} else {
			return $Row;
		}
	}

	public function pessoa_autorizada($coluna='') {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p' => 'seguro.propostas_pessoa_autorizada_vistoria'));
		$Select->where('id_proposta = ?', $this->id);
	
		$Row = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);
		if ($coluna) {
			return $Row[$coluna];
		} else {
			return $Row;
		}
	}

	public function producao_forrageira($coluna='') {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p' => 'seguro.propostas_indice_producao_forrageira'));
		$Select->where('id_proposta = ?', $this->id);
		$Select->order('ano desc');
	
		$Row = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);
		if ($coluna) {
			return $Row[$coluna];
		} else {
			return $Row;
		}
	}

	public function proponente_ppe() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p' => 'seguro.propostas_proponentes_relacionamento_ppe'));
		$Select->where('id_proposta = ?', $this->id);

		$Row = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);
		return $Row;
	}

	public function verifica_consulta_sem_retorno() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p' => 'seguro.propostas_consulta_cadin'), array('fl_retorno_pendente', 'ds_retorno'));
		$Select->where('id_proposta = ?', $this->id);
		$Select->where('fl_ativo = true');
		$Select->where('fl_solicitacao_pendente = false');

		$Row = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);

		if($Row[0]['fl_retorno_pendente'] == true && $Row[0]['ds_retorno'] == ''){
			return true;
		} elseif($Row[0]['fl_retorno_pendente'] == true && $Row[0]['ds_retorno'] != ''){
			return false;
		} else {
			return false;
		}
	}

	public function verifica_subvencao_concedida() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p' => 'seguro.propostas_consulta_cadin'), 'fl_sucesso');
		$Select->where('id_proposta = ?', $this->id);
		$Select->where('fl_ativo = true');

		$Row = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne($Select);
		return $Row;
	}

	public function ocultarItensSegurados(){
	    $select = $this->select();
	    $select->setIntegrityCheck(false);
	    $select->from(array('po'=>'seguro.propostas_observacoes'),'fl_ocultar_itens_segurados');
	    $select->where('po.id_proposta = ?', $this->id);
	    $select->where('po.fl_ocultar_itens_segurados = ?', true);

	    $Row = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne($select);
	    if($Row) {
	        return $Row;
	    } else {
	        return false;
	    }
	}

	public function propriedades($chave=false) {
		$return = false;

		$dadosProposta = [
			'proponente' => $this->proponente(),
			'preposto' => $this->preposto(),
			'corretor' => $this->corretor(),
			'propriedade' => $this->propriedade()
		];

		try {
			$return = $this->_propriedadesProduto($chave, $dadosProposta);

			$aux = []; // array para não processar mais de uma vez o mesmo grupo
			$idGrupoComPrioridade = 0;

			/**
			 * Ordem de prioridade. Foram atribuídos pesos para as validações a fim de verificar qual grupo tem maior prioridade
			 *
			 * CPF(proponente) + Login (Preposto/Corretor) + Município -> 4 + 2 + 1 = 7
			 * CPF(proponente) + Login (Preposto/Corretor) -> 4 + 2 = 6
			 * CPF(proponente) + Município -> 4 + 1 = 5
			 * CPF(proponente) -> 4
			 * Login (Preposto/Corretor) + Município -> 2 + 1 = 3
			 * Login (Preposto/Corretor) -> 2
			 * Município -> 1
			 * Default
			 */
			$pesoRegras = [
				'id_proponente' => 4, // Proponente
				'id_usuario' => 2, // Preposto/Corretor
				'id_municipio' => 1 // Município
			];

			$maiorPeso = $idGrupoComPrioridade = 0;

			$propostaPossuiProponente = !empty($dadosProposta['proponente'])
				&& !empty($dadosProposta['proponente']['cpf_cnpj']);
			$propostaPossuiPropriedade = !empty($dadosProposta['propriedade'])
				&& !empty($dadosProposta['propriedade']['id_municipio']);
			$propostaPossuiCorretor = !empty($dadosProposta['corretor'])
				&& !empty($dadosProposta['corretor']['id_usuario']);

			foreach ($return as $r) {
				if (array_key_exists($r['id'], $aux)) {
					continue;
				}

				/**
				 * As validações a seguir são necessárias para garantir que os dados da proposta batam
				 * com os dados retornados pela consulta de propriedades do produto.
				 *
				 * Exemplo:
				 *
				 * Proposta para Soja Multirisco com CPF 930.948.410-15, MUNICIPIO 4002, CORRETOR/PREPOSTO (ID_usuario 2462, 469)
				 * Existe a seguinte regra para Soja Multirisco: limitar valor máximo de contratação para CPF(930.948.410-15) e MUNICIPIO 4317
				 *
				 * Como o município da regra difere do municío da proposta, a regra não deve ser aplicada
				 *
				 * E, como a consulta retorna todas as propriedades que satisfaçam pelo menos uma das propriedades da Proposta,
				 * pode haver resultados: CPF 930.948.410-15 e MUNICIPIO 4317. E esses resultados precisam ser ignorados.
				 *
				 * Devem ser considerados apenas resultados que os dados sejam os mesmos da Proposta
				 */

				if (
					$propostaPossuiProponente
					&& !empty($r['cpf_cnpj'])
					&& $dadosProposta['proponente']['cpf_cnpj'] != $r['cpf_cnpj']
				) {
					continue;
				}

				if (
					$propostaPossuiPropriedade
					&& !empty($r['id_municipio'])
					&& $dadosProposta['propriedade']['id_municipio'] != $r['id_municipio']
				) {
					continue;
				}
				
				$tipoUsuario = $propostaPossuiCorretor ? 'corretor' : 'preposto';
				if (!empty($r['id_usuario']) && $dadosProposta[$tipoUsuario]['id_usuario'] != $r['id_usuario']) {
					continue;
				}

				$aux[$r['id']] = true;

				// Calcula peso de cada grupo
				$peso = array_reduce(array_keys($pesoRegras), function($carry, $key) use($pesoRegras, $r) {
					$carry += !empty($r[$key]) ? $pesoRegras[$key] : 0;
					return $carry;
				}, 0);
				
				if ($peso > $maiorPeso) {
					$maiorPeso = $peso;
					$idGrupoComPrioridade = $r['id'];
				}
			}
			
			$atributosGrupo = [];

			foreach ($return as $r) {
				if ($r['id'] == $idGrupoComPrioridade) {
					$atributosGrupo[$r['ds_chave_rn']] = $r['ds_valor'];
				}
			}

			// Consulta default
			if (empty($atributosGrupo)) {
				$return = $this->_propriedadesDefault($chave);
				$atributosGrupo = Agro_Util::array_pairs($return, 'ds_chave_rn', 'ds_valor');
			}
			
			if ($atributosGrupo) {
				return $atributosGrupo;
			} else {
				throw new Exception('Não foram encontrados atributos.');
			}
		} catch (Exception $e) {
			die($e);
		}
	}

	public function questionario(string $cpfCnpj = '') {
        $corretor = $this->corretor();
        $preposto = $this->preposto();
        $proponente = $this->proponente();
        $propriedade = $this->propriedade();

        if (!empty($cpfCnpj)) {
            $proponenteCpfCnpj = (new Seguro_Model_Proponentes())->fetchAll(["cpf_cnpj = '{$cpfCnpj}'"])->toArray();

            if (!empty($proponenteCpfCnpj)) {
                $proponente['id_proponente'] = $proponenteCpfCnpj[0]['id'];
            }
        }

        $idMunicipio = $propriedade['id_municipio'];
        $idProponente = $proponente['id_proponente'];
        $idUsuario = !empty($preposto) ? $preposto['id_usuario'] : $corretor['id_usuario'];

        $campos = [
            'ppar.ds_valor', 'par.id', 'par.ds_chave_rn', 'par.ds_descricao_atributo', 'par.ds_valores_opcoes',
            'par.ds_schema', 'par.ds_table', 'par.ds_option_value', 'par.ds_option_text', 'par.fl_required',
            'par.ds_validar_campo', 'par.ds_validar_campo_valor', 'par.ds_parent_value', 'par.ds_option_filter',
            'pta.ds_chave_tipo_atributo', 'par.ds_ordem'
        ];

        $result = (new Produto_Model_Atributogrupos())->getAtributosProduto(
            $this->id_produto,
            $idUsuario,
            $idMunicipio,
            $idProponente,
            '',
            $campos,
            null,
            Produto_Model_Atributogrupos::TIPO_QUESTIONARIO,
            empty($idProponente)
        )->toArray();

        $questoes = [];

        if (!empty($result)) {
            foreach ($result as $row) {
                if ($row['ds_parent_value']) {
                    continue;
                }

                $questoes[$row['ds_chave_rn']] = $row;
                $questoes[$row['ds_chave_rn']]['chields'] = $this->_buscaQuestionarioPadrao($row['id']);
            }
        } else {
            $questoes = $this->_buscaQuestionarioPadrao();
        }

		return $questoes;
	}

	public function resposta($chave) {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('a' => 'produto.atributos_rn'), false);
		$Select->join(array('q' => 'seguro.propostas_questionario'), 'a.id = q.id_atributo_rn', 'ds_resposta');
		$Select->where('q.id_proposta = ?', $this->id);
		$Select->where('a.ds_chave_rn = ?', $chave);

    	return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne($Select);
	}

	public function respostas() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('a' => 'produto.atributos_rn'), 'ds_chave_rn');
		$Select->join(array('q' => 'seguro.propostas_questionario'), 'a.id = q.id_atributo_rn', 'ds_resposta');
		$Select->where('q.id_proposta = ?', $this->id);

    	return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchPairs($Select);
	}

	public function safra() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('s' => 'produto.safras'));
		$Select->join(array('p' => 'produto.produtos'), 's.id = p.id_safra', false);
		$Select->where("p.id = ?", $this->id_produto);

		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchRow($Select);
	}

	public function status($row=false) {
		if ($row) {
			$Select = $this->select()->setIntegrityCheck(false)->from('sistema.status')->where('id = ?', $this->id_status);
    		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchRow($Select);
		} else {
			$Select = $this->select()->setIntegrityCheck(false)->from('sistema.status', 'ds_chave')->where('id = ?', $this->id_status);
    		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne($Select);
		}
	}

	public function unidades_sem_ciclo() {
		$unidades = self::itens_segurados();
		$propriedade = self::propriedade();

		$result = array();
		if (is_array($unidades)) {
			foreach ($unidades as $unidade) {
				if ($unidade['is_ciclo_variedade']) {
					if (!$this->verifica_data_semeadura($unidade['is_ciclo_variedade'], $propriedade['id_municipio'], $unidade['is_data_semeadura'])) {
						$result[] = $unidade['is_item'];
					}
				}
			}
		}

		return $result;
	}

	public function verifica_data_semeadura($idCiclo, $idMunicipio, $dtSemeadura) {
	    if ($dtSemeadura) {
			$validacao = $this->_validacao('VALIDACAO_ZONEAMENTO');
			$idTipoSolo = self::resposta('QUEST_TIPO_SOLO');

			$Select = $this->select()->setIntegrityCheck(false);
			$Select->from(array('z'=>'produto.validacoes_zoneamento_graos'), 'count(*)');
			$Select->join(array('m'=>'produto.validacoes_zoneamento_graos_municipios'), 'z.id = m.id_validacao_zoneamento_graos', false);
			$Select->where('? between (dt_inicial) and (dt_final)', Agro_Util::formatDate($dtSemeadura, Zend_Date::W3C));
			$Select->where('z.id_produto = ?', $this->id_produto);
			$Select->where('m.id_municipio = ?', $idMunicipio);

			if($idCiclo and $idCiclo <> 16){
    		    $Select->where('z.id_ciclo = ?', $idCiclo);
    		}

			if ($idTipoSolo) {
				$Select->where('z.id_tipo_solo = ?', $idTipoSolo);
			}

			return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne($Select);
		}

		return false;
	}

	public function versao() {
		$count = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne("select count(*) from seguro.propostas_versoes where id_proposta = {$this->id}");
		return ($count ? "V$count" : '');
	}

	public function versao_endosso($text=true) {
		$count = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne("select seguro.nr_endosso($this->id, $this->id_endosso)");
		if ($text) {
			return "Endosso: $count ($this->id)";
		} else {
			return $count;
		}
	}

	/**
	 * Retorna a hash do orçamento da proposta caso possua
	 *
	 * @return string
	 */
	public function getHash(): string
	{
		$modelPropostasHashOrcamento = new Seguro_Model_PropostasHashOrcamento();
		$propostaHashOrcamento = $modelPropostasHashOrcamento->find($this->id)->current();
		return !empty($propostaHashOrcamento->hash) ? $propostaHashOrcamento->hash : '';
	}

	public static function busca_endosso_id(int $idPropostaMae, int $versaoEndosso): int
	{
		return Agro_Db_Table_Abstract::getDefaultAdapter()
			->fetchOne("SELECT seguro.busca_endosso_id($idPropostaMae, $versaoEndosso)");
	}

	public function proposta_vigente() {
		$vigente = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne("select fl_proposta_vigente from seguro.propostas_endosso where id_proposta = {$this->id}");
		return $vigente;
	}

	public function recupera_id_proposta_vigente($id_proposta) {
		$id_proposta = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne("select id_proposta from seguro.propostas_endosso where id_endosso = (select id_endosso from seguro.propostas_endosso where id_proposta = $id_proposta) and fl_proposta_vigente = true");
		return $id_proposta;
	}

	public function propostas_endosso($id_endosso) {
		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll("select pr.id from seguro.propostas pr, sistema.status st where st.id = pr.id_status and st.ds_chave not in ('ENDOSSO_INCOMPLETO', 'ENDOSSO_ANULADO', 'ORCAMENTO_ENDOSSO', 'SOLICITACAO_CANCELADA') and pr.id_endosso={$id_endosso}");
	}

	public function id_proposta_mae($id) {
		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne("select seguro.id_proposta_mae($id) as x");
	}

	public function vigencia($data) {
		if ($data) {
			return Agro_Util::checkBetweenDatas($data, ($this->dt_vigencia_inicio_original ? $this->dt_vigencia_inicio_original : $this->dt_vigencia_inicio), $this->dt_vigencia_fim);
		} else {
			return array($this->dt_vigencia_inicio, $this->dt_vigencia_fim);
		}
	}

	public function vistorias_previas() {
		$Select = $this->select()->setIntegrityCheck(false)->from('seguro.propostas_vistorias_previas')->where('id_proposta = ?', $this->id);
    	return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);
	}

	public function longitude() {
		$Propriedade = $this->propriedade();
	}

	public function endossoAumento() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p' => 'seguro.propostas'));
		$Select->join(array('e' => 'seguro.propostas_endosso'), 'p.id = e.id_proposta');
		$Select->join(array('o' => 'seguro.propostas_endosso_opcoes'), 'o.id_proposta = p.id');
		$Select->join(array('t' => 'seguro.tipo_endosso_opcoes'), 'o.id_endosso_opcao = t.id');
		$Select->where('t.id_tipo_endosso = 1');
		$Select->where('p.id = ?', $this->id);

		return count(Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select));
	}

	public function endossoReducao() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p' => 'seguro.propostas'));
		$Select->join(array('e' => 'seguro.propostas_endosso'), 'p.id = e.id_proposta');
		$Select->join(array('o' => 'seguro.propostas_endosso_opcoes'), 'o.id_proposta = p.id');
		$Select->join(array('t' => 'seguro.tipo_endosso_opcoes'), 'o.id_endosso_opcao = t.id');
		$Select->where('t.id_tipo_endosso = 2');
		$Select->where('p.id = ?', $this->id);

		return count(Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select));
	}

	public function opcoesEndosso() {
		if ($this->isEndosso()) {
			$Tipos = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll("select * from seguro.tipo_endosso");
			$result = array();

			if (is_array($Tipos) && count($Tipos)) {
				foreach ($Tipos as $Tipo) {
					$result[$Tipo['id']]['titulo'] = $Tipo['ds_tipo_endosso'];
					$result[$Tipo['id']]['opcoes'] = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchPairs("select o.id, o.ds_tipo_endosso_opcoes from seguro.tipo_endosso_opcoes o inner join seguro.propostas_endosso_opcoes p on o.id = p.id_endosso_opcao where id_proposta = {$this->id} and o.id_tipo_endosso = {$Tipo['id']}");;
				}
			}

			return $result;
		}

		return false;
	}

	public function id_endosso(){
		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne("select id_endosso from seguro.propostas_endosso where id_proposta = $this->id");
	}

	public function id_proposta_reativacao(){

		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne(
				"
				select
				    max(pe.id_proposta)
				from
				    seguro.propostas_endosso pe,
				    seguro.propostas pr,
				    sistema.status st
				where
				    pe.id_endosso = ".$this->id_endosso()." and
				    pr.id = pe.id_proposta and
				    st.id = pr.id_status and
				    pe.fl_proposta_vigente = false and
				    st.ds_chave = 'APOLICE_EMITIDA'
				"
		);
	}


	public function buscaPropostasEndosso(){
		$Select = Agro_Db_Table_Abstract::getDefaultAdapter()->select();
		$Select->from(array("pe" => "seguro.propostas_endosso"));
        $Select->join(array('pr' => 'seguro.propostas'), 'pr.id = pe.id_proposta', false);
        $Select->join(array('st' => 'sistema.status'), 'st.id = pr.id_status', false);
		$Select->where("pe.id_endosso={$this->id_endosso()}");
		$Select->where("st.ds_chave not in ('ENDOSSO_INCOMPLETO', 'ORCAMENTO_ENDOSSO', 'SOLICITACAO_CANCELADA')");

		$Row = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);

		$propostas = array();
		foreach ($Row as $proposta_endosso){
			$propostas[] = $proposta_endosso["id_proposta"];
		}

		return $propostas;
	}

	public function setEndossoVigente($idProposta="") {

	    $id_endosso = $this->id_endosso();
	    $id_usuario = $this->getUsuarioLogado('id');

        Agro_Db_Table_Abstract::getDefaultAdapter()->query("update seguro.propostas_endosso set fl_proposta_vigente=false, dt_alteracao=now(), id_usuario_alteracao={$id_usuario} where id_endosso = {$id_endosso}");

        if($idProposta){
        	Agro_Db_Table_Abstract::getDefaultAdapter()->query("update seguro.propostas_endosso set fl_proposta_vigente=true, dt_alteracao=now(), id_usuario_alteracao={$id_usuario} where id_proposta = {$idProposta}");
        } else {
        	Agro_Db_Table_Abstract::getDefaultAdapter()->query("update seguro.propostas_endosso set fl_proposta_vigente=true, dt_alteracao=now(), id_usuario_alteracao={$id_usuario} where id_proposta = {$this->id}");
        }

		return true;
	}

	public function subvencao_cultura_municipio() {
	    $propriedade = $this->propriedade();

		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('cs' => 'produto.culturas_municipios_subvencao'));
		$Select->join(array('c'  => 'produto.culturas'), 'c.id = cs.id_cultura', null);
		$Select->join(array('pg' => 'produto.produtos_geral'), 'pg.id_cultura = c.id', null);
		$Select->join(array('pd' => 'produto.produtos'), 'pd.id_produto_geral = pg.id', null);
		$Select->where('pd.id = ?', $this->id_produto);
		$Select->where('cs.id_municipio = ?', $propriedade['id_municipio']);

		$Row = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);
		if(count($Row)){
		    return true;
		}
		return false;
	}

	public function subvencao_federal() {
	    return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne(
	    		"select
	    			sum(vl_subvencao_federal) as vl_subvencao_federal
	    		from
	    		    seguro.propostas_parcelas
	    		where id_proposta = {$this->id} and fl_ativo = true");
	}
	
	public function subvencao_federal_endossos() {
		Agro_Db_Table_Abstract::getDefaultAdapter()->query("SELECT seguro.sumario_parcelas(0);");
		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne("select valor_subvencao_federal from sumario_parcelas pat inner join seguro.propostas pr on pr.id_endosso = pat.id_endosso and pr.id={$this->id}");
	}

	public function subvencao_estadual() {
	    return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne("select sum(vl_subvencao_estadual) as vl_subvencao_estadual from seguro.propostas_parcelas where id_proposta = {$this->id} and fl_ativo = true");
	}
	
	public function subvencao_estadual_endossos() {
		Agro_Db_Table_Abstract::getDefaultAdapter()->query("SELECT seguro.sumario_parcelas(0);");
		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne("select valor_subvencao_estadual from sumario_parcelas pat inner join seguro.propostas pr on pr.id_endosso = pat.id_endosso and pr.id={$this->id}");
	}

	public function premio_segurado() {
		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne(
				"select
				sum(vl_segurado) as vl_segurado
				from
				seguro.propostas_parcelas
				where id_proposta = {$this->id} and fl_ativo = true");

		}

	public function premio_total_parcelamento() {
		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne("select sum(vl_total) as vl_total from seguro.propostas_parcelas where id_proposta = {$this->id} and fl_ativo = true");
	}
	
	/* Recupera o nr de endosso da proposta */
	public function nr_endosso() {
		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne("select seguro.nr_endosso({$this->id},{$this->id_endosso}) as nr_endosso;");
	}

	public static function busca_nr_endosso(int $idProposta, int $versaoEndosso): int
	{
		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne("select seguro.nr_endosso({$idProposta}, {$versaoEndosso}) as nr_endosso;");
	}
	
	/* Recupera a data que o corretor transmitiu a proposta para Agro */
	public function getDataRecepcao() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('pt' => 'log.propostas_transmissao'), 'to_char(pt.dt_criacao, \'dd/mm/yyyy\')');
		$Select->join(array('ss' => 'sistema.status'), 'ss.id = pt.id_status', false);
		$Select->where('pt.id_proposta = ?', $this->id);
		$Select->where('pt.ds_tipo_transmissao = \'EMITIR_PROPOSTA\'');
		$Select->where('ss.ds_chave = \'ENVIADA_AGUARDANDO_CONF\'');
		
		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne($Select);
	}

	public function hasIndicativoEndosso() {
        $modelVP = new Seguro_Model_VistoriaPreviaEmpresa;
        $statusFiltro = [
            Seguro_Model_VistoriaPrevia::ID_STATUS_VP_TRANSMITIDA,
            Seguro_Model_VistoriaPrevia::ID_STATUS_VP_TRANSMITIDA_SEM_FOTOS,
        ];
        $dadosVistoria = $modelVP->getDadosDigitacaoFinalizadaByIdProposta($this->id_proposta_mae, $statusFiltro, true);
        if (!empty($dadosVistoria)) {
            $dadosLaudo = $modelVP->getLaudo($dadosVistoria['id'], $this->id_proposta_mae);
            if (!empty($dadosLaudo)) {
                return 1;
            }
        }

        return 0;
    }

	public function sistema_informacoes_bancarias(): array
	{
		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll(
			$this
				->select()
				->setIntegrityCheck(false)
				->from(array('sibp' => 'seguro.informacoes_bancarias_propostas'), false)
				->join(array('sib' => 'sistema.informacoes_bancarias'), 'sib.id = sibp.id_informacoes_bancarias')
				->where('id_proposta = ?', $this->id)
				->where('sib.fl_ativo IS TRUE')
		);
	}

	public function seguro_informacoes_bancarias(): array
	{
		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll(
			$this
				->select()
				->setIntegrityCheck(false)
				->from(array('sib' => 'seguro.informacoes_bancarias'))
				->where('id_proposta = ?', $this->id)
				->where('fl_ativo IS TRUE')
		);
	}

	public function seguro_informacoes_bancarias_propostas(): array
	{
		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll(
			$this
				->select()
				->setIntegrityCheck(false)
				->from(array('sibp' => 'seguro.informacoes_bancarias_propostas'))
				->where('id_proposta = ?', $this->id)
				->where('fl_ativo IS TRUE')
		);
	}

	public function propostas_tipo_assinatura_documento($coluna='') {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p' => 'seguro.propostas_tipo_assinatura_documento'));
		$Select->where('id_proposta = ?', $this->id);
		$Select->where('fl_ativo = ?', 'true');
	
		$Row = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);
		if ($coluna) {
			return $Row[$coluna];
		} else {
			return $Row;
		}
	}

	public function propostas_email_assinatura_documento($coluna='') {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p' => 'seguro.propostas_email_assinatura_documento'));
		$Select->where('id_proposta = ?', $this->id);
		$Select->where('fl_ativo = ?', 'true');
	
		$Row = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);
		if ($coluna) {
			return $Row[$coluna];
		} else {
			return $Row;
		}
	}

	public function propostas_email_justificativa($coluna='') {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('pej' => 'seguro.propostas_email_justificativa'));
		$Select->join(array('pead' => 'seguro.propostas_email_assinatura_documento'), 'pead.id = pej.id_proposta_email_assinatura_documento', false);
		$Select->where('pead.id_proposta = ?', $this->id);
		$Select->where('pead.fl_ativo = ?', 'true');
		
		$Row = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchAll($Select);
		if ($coluna) {
			return $Row[$coluna];
		} else {
			return $Row;
		}
	}

    public function isSolicitacaoEndosso() {
        $status = Agro_Db_Table_Abstract::getDefaultAdapter()->fetchOne("select ds_chave from sistema.status where id = {$this->id_status}");

        return $status === 'SOLICITACAO_ENDOSSO';
    }

    public function getPropostaAnterior(array $statusAnteriorDesconsiderar = [])
    {
        $campos = ['sp.*'];

        $select = $this->select()->setIntegrityCheck(false);
        $select->from(['spe' => 'seguro.propostas_endosso'], $campos);
        $select->join(['sp' => 'seguro.propostas'], 'sp.id = spe.id_proposta', false);
        $select->where('spe.id_endosso = ?', $this->id_endosso);
        $select->where('spe.id_proposta <> ?', $this->id);

        if (!empty($statusAnteriorDesconsiderar)) {
            $select->where('sp.id_status NOT IN (' . implode(', ', $statusAnteriorDesconsiderar) . ')');
        }

        $select->order('spe.id_proposta desc');
        $select->limit(1);

        return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchRow($select);
    }

	public function podeAnexarTermoSubvencao(string $chaveAtributoRn): bool
	{
		if ($this->id == $this->id_proposta_mae) {
			return true;
		}

		$select = $this->select()
			->setIntegrityCheck(false)
			->from(
				['a' => 'produto.atributos_rn'], 'a.id'
			)
			->join(
				['q' => 'seguro.propostas_questionario'],
				'a.id = q.id_atributo_rn',
				'id_proposta'
			)
			->where('q.id_proposta = ?', $this->id)
			->where('a.ds_chave_rn = ?', $chaveAtributoRn)
			->where('q.ds_resposta = ?', '1')
			->where('NOT EXISTS(
				SELECT
					1
				FROM seguro.propostas_endosso
				INNER JOIN seguro.propostas_endosso aux
					ON aux.id_endosso = propostas_endosso.id_endosso
				INNER JOIN seguro.propostas_questionario
					ON propostas_questionario.id_proposta = aux.id_proposta
				INNER JOIN produto.atributos_rn
					ON atributos_rn.id = propostas_questionario.id_atributo_rn
				WHERE
					propostas_endosso.id_proposta = '. $this->id .'
					AND aux.id_proposta <> propostas_endosso.id_proposta
					AND atributos_rn.ds_chave_rn = \''. $chaveAtributoRn .'\'
					AND propostas_questionario.ds_resposta = \'1\'
			)'
			);

		return Agro_Db_Table_Abstract::getDefaultAdapter()->fetchRow($select) == null ? false : true;
	}
}
