<?php

class Seguro_Model_PropostaLoad extends Agro_Db_Table_Abstract {
	protected $_name = 'propostas';
	protected $_schema = 'seguro';
	protected $_primary = 'id';
	private $idProposta = '';
	private $idProduto = '';

	/**
	 * Metodo inicial da classe
	 *
	 * @param $idProposta integer
	 */
	public function __construct($idProposta) {
		parent::__construct();
		$Proposta = new Zend_Session_Namespace('proposta');
		$Proposta->unsetAll();

		$this->idProposta = $idProposta;

		$Proposta->proposta = $this->fetchProposta();
		$Proposta->segurado = $this->fetchSegurado();
		$Proposta->unidades = $this->fetchItensSegurados();
		$Proposta->croquis = $this->fetchCroquis();
		$Proposta->premio = $this->fetchPremio();
	}

	/**
	 * Busca os ids da proposta
	 *
	 * @return array
	 */
	public function fetchProposta() {
		$Produtos = new Produto_Model_Produtos();
		$Row = $this->find($this->idProposta)->current();

		$this->idProduto = $Row->id_produto;


		$select = $this->select()->distinct(true)->setIntegrityCheck(false);
		$select->from(array('pc' => 'seguro.propostas_corretores'), '*');
		$select->join(array('cor' => 'sistema.corretores'), ' pc.id_usuario = cor.id_usuario', 'ds_nome_fantasia');
		$select->where('id_proposta = ?', $this->idProposta);
		$Corretor = $this->fetchRow($select);

		$ret = array();
		$ret['id_proposta'] = $Row->id;
		$ret['nr_apolice'] = $Row->nr_apolice;
		$ret['dt_vigencia_inicio'] = $Row->dt_vigencia_inicio;
		$ret['dt_vigencia_fim'] = $Row->dt_vigencia_fim;
		$ret['id_produto'] = $Row->id_produto;
		$ret['vl_custo_apolice'] = $Row->vl_custo_apolice;
		$ret['id_proposta_renovada'] = $Row->id_proposta_renovada;
		$ret['vl_comissao'] = $Corretor->vl_comissao;
		$ret['id_corretor'] = $Corretor->id_usuario;
		$ret['nome_corretor'] = $Corretor->ds_nome_fantasia;
		$ret['produto'] = $Produtos->find($this->idProduto)->current()->toArray();

		$select = $this->select()->distinct(true)->setIntegrityCheck(false);
		$select->from(array('pc' => 'seguro.propostas_observacoes'), '*');
		$select->where('id_proposta = ?', $this->idProposta);
		$Rs = $this->fetchRow($select);
		$ret['observacoes'] = $Rs->ds_observacao;

		$select = $this->select()->distinct(true)->setIntegrityCheck(false);
		$select->from(array('p' => 'sistema.prepostos'), '*');
		$select->join(array('u' => 'sistema.usuarios'), ' p.id_usuario = u.id', false);
		$select->where('p.id_usuario = ?', $Row->id_usuario_criacao);
		$select->where("u.tp_usuario = 'P'");
		$arr = $this->fetchRow($select);
		$ret['ds_nome_preposto'] = $arr->ds_nome_preposto;
		$ret['id_preposto'] = $arr->id;

		$select = $this->select()->distinct(true)->setIntegrityCheck(false);
		$select->from(array('p' => 'sistema.prepostos'), '*');
		$select->where('id_usuario = ?', $Row->id_usuario_criacao);
		$Preposto = $this->fetchRow($select);

		// Adiciona o Produto na sessao!
		if ($Row->id_produto) {
			$session = new Zend_Session_Namespace('id_produto');
			$session->value = $Row->id_produto;
		}

		return $ret;
	}

	/**
	 * Busca os dados da aba segurado
	 *
	 */
	public function fetchSegurado() {
		$ret = array();

		$proponente = array(
			'id_proponente_original',
			'cpf_cnpj',
			'tp_pessoa',
			'ds_nome_proponente',
			'ds_email_proponente',
			'ds_sexo',
			'dt_nascimento',
			'id_estado_civil',
			'ds_documento_natureza',
			'ds_documento_numero',
			'id_orgao_expedidor',
			'dt_documento_exp',
			'id_atividade_economica',
			'ds_endereco_rua as ds_endereco_rua_proponente',
			'ds_endereco_nro as ds_endereco_nro_proponente',
			'ds_endereco_complem as ds_endereco_complem_proponente',
			'ds_endereco_bairro as ds_endereco_bairro_proponente',
			'ds_endereco_cep as ds_endereco_cep_proponente',
			'id_municipio as id_municipio_proponente',
			'ds_tel_residencia',
			'ds_tel_propriedade',
			'ds_tel_celular',
			'tp_segurado'
		);

		$propriedade = array(
			'ds_nome_propriedade',
			'ds_endereco as ds_endereco_propriedade',
			'ds_endereco_cep as ds_endereco_cep_propriedade',
			'id_municipio as id_municipio_propriedade',
			'ds_endereco_bairro as ds_endereco_bairro_propriedade',
			'ds_coordenadas',
			'ds_referencia_localizacao',
			'ds_pessoa_autorizada',
			'ds_nome_outra_pessoa',
		    'ds_cpf_outra_pessoa',
			'ds_telefone_outra_pessoa',
			'ds_endereco_nro as ds_endereco_nro_propriedade',
			'ds_endereco_complemento as ds_endereco_complemento_propriedade'
		);

		$select = $this->select()->distinct(true)->setIntegrityCheck(false);
		$select->from(array('proposta' => 'seguro.propostas'));
		$select->join(array('proponente' => 'seguro.propostas_proponentes'), 'proposta.id = proponente.id_proposta', $proponente);
		$select->join(array('prop' => 'seguro.proponentes'), 'prop.cpf_cnpj = proponente.cpf_cnpj', 'fl_inadimplente');
		$select->join(array('propriedade' => 'seguro.propostas_propriedades'), 'proposta.id = propriedade.id_proposta', $propriedade);
		$select->join(array('mpo' => 'sistema.municipios'), 'proponente.id_municipio = mpo.id', array('id_estado as id_estado_proponente'));
		$select->join(array('mpr' => 'sistema.municipios'), 'propriedade.id_municipio = mpr.id', array('id_estado as id_estado_propriedade', 'ds_nome_municipio as municipio_propriedade'));
		$select->where('proposta.id = ?', $this->idProposta);
		$ret = $this->fetchRow($select)->toArray();

		$select = $this->select()->distinct(true)->setIntegrityCheck(false);
		$select->from(array('proposta' => 'seguro.propostas'), false);
		$select->join(array('questionario' => 'seguro.propostas_questionario'), 'proposta.id = questionario.id_proposta');
		$select->join(array('atributo' => 'produto.atributos_rn'), 'questionario.id_atributo_rn = atributo.id');
		$select->where('proposta.id = ?', $this->idProposta);
		$Rs = $this->fetchAll($select);

		foreach ($Rs as $Row) {
			$ret['questionario'][$Row->ds_chave_rn] = ($Row->ds_resposta ? $Row->ds_resposta : 0);
		}

		return $ret;
	}

	public function fetchItensSegurados() {
		$select = $this->select()->distinct(true)->setIntegrityCheck(false);
		$select->from(array('i' => 'seguro.itens_segurados'));
		$select->joinLeft(array('isc' => 'seguro.itens_segurados_complemento'), 'i.id = isc.id_item_segurado');
		$select->where('id_proposta = ?', $this->idProposta);
		$select->order('nr_item_segurado');
		$Rs = $this->fetchAll($select);

		$ret = array();
		if ($Rs) {
			foreach ($Rs as $Row) {
				$Row->ds_espacamento = strtoupper($Row->ds_espacamento);
				$espacamento = explode('X',$Row->ds_espacamento);
				$ret[$Row->nr_item_segurado] = array(
					'IS_AREA' => $Row->vl_area,
					'IS_COORDENADAS_GEOGRAFICAS' => $Row->ds_coordenadas_geograficas,
					'IS_DATA_PODA' => Agro_Util::formatDate($Row->dt_poda, Zend_Date::DATES),
					'IS_DATA_SEMEADURA' => Agro_Util::formatDate($Row->dt_semeadura, Zend_Date::DATES),
					'IS_DATA_PLANTIO_TRANSPLANTE' => Agro_Util::formatDate($Row->dt_plantio, Zend_Date::DATES),
					'IS_ESPACAMENTO_SIMPLES' => $Row->ds_espacamento,
					'IS_ESPACAMENTO_COMPOSTO' => array('n'=>$espacamento[0],'m'=>$espacamento[1]),
					'IS_IDADE' => $Row->vl_idade,
					'IS_IDADE_TELA' => $Row->vl_idade_tela,
					'IS_LMGA_PARCIAL' => Agro_Util::formatDbCurrency($Row->vl_lmga),
					'IS_LOCAL' => $Row->ds_local,
					'IS_NRO_PLANTAS' => $Row->nr_plantas,
					'IS_NRO_PLANTAS_M_LINEAR' => $Row->nr_plantas_metro_linear,
					'IS_PORTAENXERTO' => $Row->id_portaenxerto,
					'IS_PRODUCAO_GARANTIDA' => $Row->vl_producao_garantida,
					'IS_PRODUCAO_PLANTA' => $Row->vl_producao_planta,
					'IS_PRODUTIVIDADE' => Agro_Util::formatDbCurrency($Row->vl_rendimento_tonelada, 2, '.'),
					'IS_DESCRICAO_ITEM' => $Row->ds_item_segurado,
					'IS_TIPO_CONDUCAO' => $Row->ds_tipo_conducao,
					'IS_PRIMEIRO_ANO_PLANTIO' => $Row->ds_primeiro_ano_plantio,
					'IS_CICLO_VARIEDADE' => $Row->id_ciclo,
					'IS_VALOR_TONELADA' => Agro_Util::formatDbCurrency($Row->vl_valor_tonelada),
					'IS_VARIEDADES' => $Row->id_variedade,
					'IS_DT_FINAL_COLHEITA' => Agro_Util::formatDate($Row->dt_final_colheita, Zend_Date::DATES),
					'IS_DT_INICIO_COLHEITA' => Agro_Util::formatDate($Row->dt_inicio_colheita, Zend_Date::DATES)
				);
			}
		}

		return $ret;
	}

	public function fetchCroquis() {
		$select = $this->select()->distinct(true)->setIntegrityCheck(false);
		$select->from(array('pa' => 'seguro.propostas_arquivos'));
		$select->join(array('ta' => 'sistema.tipo_arquivo'), 'pa.id_tipo_arquivo = ta.id', false);
		$select->where('pa.id_proposta = ?', $this->idProposta);
		$select->where('upper(ta.ds_nome_arquivo) = upper(?)', "croqui_proposta");
		$Rs = $this->fetchAll($select);

		$ret = array();
		if ($Rs->count()) {
			$i = 1;
			foreach ($Rs as $Row) {
				$ret[] = $Row->ds_nome_arquivo;

				if (file_exists(PATH_CROQUI."/{$Row->ds_nome_arquivo}")) {
					$source = PATH_CROQUI."/{$Row->ds_nome_arquivo}";
					$dest = PATH_TEMP."/{$Row->ds_nome_arquivo}";
					copy($source, $dest);
				}
			}
		}

		return $ret;
	}

	public function fetchPremio() {
		$ret = array();
		$select = $this->select()->distinct(true)->setIntegrityCheck(false);
		$select->from(array('p' => 'seguro.propostas'), 'vl_comissao');
		$select->join(array('pc' => 'seguro.propostas_coberturas'), 'p.id = pc.id_proposta', array('id_cobertura', 'fl_principal', 'vl_franquia', 'vl_taxa', 'vl_premio'));
		$select->join(array('c' => 'produto.coberturas'), 'c.id = pc.id_cobertura', 'ds_nome_cobertura');
		$select->where('pc.id_proposta = ?', $this->idProposta);
		$Rs = $this->fetchAll($select);

		if ($Rs->count()) {
			foreach ($Rs as $Row) {
				$ret['dados']['comissao'] = $Row->vl_comissao;
				$ret['dados']['coberturas'][$Row->id_cobertura] = $Row->toArray();
			}
		}

		$select = $this->select();
		$select->distinct(true)->setIntegrityCheck(false);
		$select->from(array('p' => 'seguro.propostas_parcelas'));
		$select->where('p.id_proposta = ?', $this->idProposta);
		$select->order('p.nr_parcela');
		$Rs = $this->fetchAll($select);

		if ($Rs->count()) {
			foreach ($Rs as $Row) {
				$ret['vl_segurado_total'] += $Row->vl_segurado;
				$ret['vl_subvencao_federal_total'] += $Row->vl_subvencao_federal;
				$ret['vl_subvencao_estadual_total'] += $Row->vl_subvencao_estadual;
				$ret['dados']['parcela'][$Row->nr_parcela] = array(
				    'nr_parcela' => $Row->nr_parcela,
					'premio_liquido' => $Row->vl_total,
					'premio_federal' => $Row->vl_subvencao_federal,
					'premio_estadual' => $Row->vl_subvencao_estadual,
					'premio_segurado' => $Row->vl_segurado,
				    'fl_pago' => $Row->fl_pago,
					'vencimento' => date('d/m/Y', strtotime($Row->dt_vencimento))
				);
			}
		}
		$ret['vl_premio_total'] = $ret['vl_segurado_total'] + $ret['vl_subvencao_federal_total'] + $ret['vl_subvencao_estadual_total'];

		$select = $this->select();
		$select->distinct(true);
		$select->setIntegrityCheck(false);
		$select->from(array('b' => 'seguro.proposta_boletos'), array('fl_pago', 'nu_boleto'));
		$select->where('b.id_proposta = ?', $this->idProposta);
		$select->where('b.fl_ativo = true');
		$Row = $this->fetchRow($select);
		if ($Row) {
			$ret['boleto'] = $Row->toArray();
		}

		$select = $this->select();
		$select->distinct(true);
		$select->setIntegrityCheck(false);
		$select->from(array('b' => 'seguro.propostas_beneficiarios'), array('id as id_beneficiario', '*'));
		$select->where('b.id_proposta = ?', $this->idProposta);
		$Rs = $this->fetchAll($select);

		if ($Rs->count()) {
			$i = 0;
			foreach ($Rs as $Row) {
				$ret['beneficiarios'][$i] = $Row->toArray();
				$i++;
			}
		}

		$select = $this->select();
		$select->distinct(true);
		$select->setIntegrityCheck(false);
		$select->from(array('o' => 'seguro.propostas_observacoes'));
		$select->where('o.id_proposta = ?', $this->idProposta);
		$Row = $this->fetchRow($select);

		if ($Row) {
			$ret['dados']['observacao'] = $Row->ds_observacao;
		}

		return $ret;
	}
}
