<?php

class Seguro_Model_PropostaPrint extends Agro_Db_Table_Abstract {

	protected $_name = 'propostas';
	protected $_schema = 'seguro';
	protected $_primary = 'id';
	private $_proposta = '';

	public function getProposta(int $idProposta)
    {
        $this->_proposta = $idProposta;

        $proposta = $this->fetchProposta();
        $proposta['produto'] = $this->fetchProduto($proposta['id_produto']);
        $proposta['corretor'] = $this->fetchCorretor($proposta['id_corretor']);
        $proposta['proponente'] = $this->fetchPropostaProponente();
        $proposta['propriedade'] = $this->fetchPropostaPropriedade();
        $proposta['questionarios'] = $this->fetchPropostaQuestionarios();
        $proposta['unidades_seguradas'] = $this->fetchItensSegurados();
        $proposta['beneficiarios'] = $this->fetchPropostaBeneficiarios();
        $proposta['cobertura_principal'] = $this->fetchCoberturaPrincipal();
        $proposta['coberturas_adicionais'] = $this->fetchCoberturasAdicionais();
        $proposta['cobranca'] = $this->fetchPropostaCobranca();
        $proposta['croquis'] = $this->fetchPropostaCroquis();
        $proposta['carencia'] = $this->fetchCarencia($proposta['id_produto']);
        $proposta['atributos'] = $this->fetchAtributos($proposta);
        $proposta['vistoria'] = $this->fetchVistoria();

        if ($proposta['id_usuario_criacao'] != $proposta['corretor']['id_corretor']) {
            $proposta['preposto'] = $this->fetchPreposto($proposta['id_usuario_criacao']);
        }

        return $proposta;
    }

	public function fetchProposta() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p'=>'seguro.propostas'), array("dt_criacao", "dt_alteracao", "id_usuario_criacao", 'id','id_produto','nr_digito_verificador','id_proposta_renovada','nr_apolice','dt_vigencia_inicio','dt_vigencia_fim','id_status','vl_comissao', 'vl_custo_apolice', 'id_usuario_criacao'));
		$Select->join(array('pr'=>'produto.produtos'), 'p.id_produto = pr.id', array('id_seguradora'));
		$Select->join(array('pg'=>'produto.produtos_geral'), 'pr.id_produto_geral = pg.id', array('id_ramo','cd_produto_geral_seguradora'));
		$Select->join(array('s'=>'sistema.status'), 'p.id_status = s.id', array('ds_chave as status', 'ds_status', 'ds_cor'));
		$Select->joinLeft(array('po'=>'seguro.propostas_observacoes'), 'p.id = po.id_proposta and po.fl_principal=true', 'ds_observacao');
		$Select->where("p.id = ?", $this->_proposta);

		return $this->fetchRow($Select)->toArray();
	}

	public function fetchProduto($produto) {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p'=>'produto.produtos'), array('nr_susep','ds_nome_produto','cd_produto_seguradora','ar_condicoes_gerais', 'ar_condicoes_gerais','id_safra','id_produto_geral','ds_chave_produto'));
		$Select->join(array('s'=>'produto.safras'), 'p.id_safra = s.id', array('ds_nome_safra', 'dt_inicio', 'dt_termino', 'ds_chave'));
		$Select->join(array('se'=>'sistema.empresas'), 'p.id_seguradora = se.id', array('ds_nome_fantasia', 'cpf_cnpj'));
		$Select->join(array('pg'=>'produto.produtos_geral'), 'p.id_produto_geral = pg.id', array('ds_nome_produto_geral','cd_produto_geral_seguradora'));
		$Select->join(array('tp'=>'produto.tipo_produto'), 'pg.id_tipo_produto = tp.id', array('ds_tipo_produto', 'ds_chave_rn'));
		$Select->join(array('c'=>'produto.culturas'), 'pg.id_cultura = c.id', array('ds_nome_cultura', 'nr_ibge', 'cd_cultura_seguradora', "lpad(cast(c.cd_bacen as text), 10, '0') as cd_bacen"));
		$Select->join(array('n'=>'produto.nomenclaturas'), 'c.id_nomenclatura = n.id', array('ds_nomenclatura', 'ds_descricao_nomenclatura'));
		$Select->join(array('r'=>'produto.ramos'), 'pg.id_ramo = r.id', array('ds_nome_ramo'));
		$Select->joinLeft(array('pv'=>'produto.produtos_validacoes'), 'p.id = pv.id_produto', 'id_validacao');
		$Select->joinLeft(array('v'=>'produto.validacoes'), "pv.id_validacao = v.id and v.ds_chave = 'VALIDACAO_ZONEAMENTO'", false);
		$Select->where("p.id = ?", $produto);

		return $this->fetchRow($Select)->toArray();
	}

	public function fetchCorretor($corretor) {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p'=>'seguro.propostas_corretores'));
		$Select->join(array('c'=>'sistema.corretores'), 'p.id_usuario = c.id_usuario', array('id_usuario as id_corretor', 'nr_susep','tp_pessoa','cpf_cnpj','ds_nome_corretor','ds_nome_fantasia','ds_nome_responsavel','cd_corretor_seguradora','ds_email','ds_email_2','ds_homepage','ds_observacao'));
		$Select->joinLeft(array('t'=>'sistema.telefone'), 'c.id_usuario = t.id_usuario', array('ds_numero','ds_ramal'));
		$Select->where("p.id_proposta = ?", $this->_proposta);
		return $this->fetchRow($Select)->toArray();
	}

	public function fetchPreposto($preposto) {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p'=>'sistema.prepostos'), array('id', 'ds_nome_preposto', 'ds_email'));
		$Select->where("p.id = ?", $preposto);
		$Select->where("p.fl_ativo = true");
		//return $this->fetchRow($Select)->toArray();
		return $this->fetchRow($Select);
	}

	public function fetchPropostaProponente() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p'=>'seguro.propostas_proponentes'), array('cpf_cnpj','tp_pessoa','ds_nome_proponente','ds_email_proponente','ds_sexo',"dt_nascimento",'ds_documento_natureza','ds_documento_numero',"dt_documento_exp",'ds_endereco_rua','ds_endereco_nro','ds_endereco_complem','ds_endereco_bairro','ds_endereco_cep','ds_tel_residencia','ds_tel_propriedade','ds_tel_celular','tp_segurado'));
		$Select->joinLeft(array('c'=>'sistema.estado_civil'), 'p.id_estado_civil = c.id', array('id as id_estado_civil','ds_nome_estado_civil'));
		$Select->joinLeft(array('o'=>'sistema.orgao_expedidor'), 'p.id_orgao_expedidor = o.id', array('id as id_orgao_expedidor','ds_nome_orgao'));
		$Select->joinLeft(array('a'=>'sistema.atividades_economicas'), 'a.id = p.id_atividade_economica', array('id as id_atividade_economica', 'ds_nome_atividade_economica'));
		$Select->join(array('m'=>'sistema.municipios'), 'p.id_municipio = m.id', array('ds_nome_municipio', 'id as id_municipio_proponente'));
		$Select->join(array('e'=>'sistema.estados'), 'm.id_estado = e.id', array('ds_nome_estado', 'ds_sigla', 'id as id_estado_proponente'));
		$Select->where("p.id_proposta = ?", $this->_proposta);
		$Row = $this->fetchRow($Select);

		if ($Row) {
			return $Row->toArray();
		}

		return;
	}

	public function fetchPropostaPropriedade() {
		$Select = $this->select();
		$Select->setIntegrityCheck(false);
		$Select->from(array('p'=>'seguro.propostas_propriedades'));
		$Select->join(array('m'=>'sistema.municipios'), 'p.id_municipio = m.id', array('ds_nome_municipio', 'cd_bacen', 'id as id_municipio_propriedade'));
		$Select->join(array('e'=>'sistema.estados'), 'm.id_estado = e.id', array('ds_nome_estado', 'ds_sigla', 'id as id_estado_propriedade'));
		$Select->where("p.id_proposta = ?", $this->_proposta);
		return $this->fetchRow($Select)->toArray();
	}

	public function fetchPropostaQuestionarios($idParent=0) {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p'=>'seguro.propostas_questionario'), array('ds_resposta'));
		$Select->join(array('a'=>'produto.atributos_rn'), 'p.id_atributo_rn = a.id and a.fl_ativo = true', array('id', 'ds_descricao_atributo', 'ds_valores_opcoes', 'ds_chave_rn'));
		$Select->where("p.id_proposta = ?", $this->_proposta);
		$Select->where("a.id_parent = ?", $idParent);
		$Select->where("p.ds_resposta != ''");
		$Select->where("p.fl_ativo = true");
		$Select->order("ds_ordem");

		$Rs = $this->fetchAll($Select);

		$return = array();
		if ($Rs->count()) {
			$i = 0;
			foreach ($Rs as $Row) {
				$return[$Row->ds_chave_rn] = array('ds_descricao_atributo' => $Row->ds_descricao_atributo, 'ds_valores_opcoes' => $Row->ds_valores_opcoes, 'resposta' => $Row->ds_resposta);
				$return[$Row->ds_chave_rn]['chields'] = $this->fetchPropostaQuestionarios($Row->id);

				$i++;
			}
		}

		return $return;
	}

	public function fetchItensSegurados() {
		$Select = $this->select();
		$Select->setIntegrityCheck(false);
		$Select->from(array('i'=>'seguro.v_unidades_seguradas'));
		$Select->where("id_proposta = ?", $this->_proposta);

		return $this->fetchAll($Select)->toArray();
	}

	public function fetchPropostaBeneficiarios() {
		$Select = $this->select();
		$Select->setIntegrityCheck(false);
		$Select->from(array('p'=>'seguro.propostas_beneficiarios'), array('id as id_beneficiario', 'ds_nome_beneficiarios','ds_qualidade_beneficiario','vl_limite_beneficio','nr_cpf_cnpj','id_banco','ds_agencia','ds_conta','ds_observacao','ds_tipo_conta'));
		$Select->joinLeft(array('b'=>'sistema.bancos'), 'p.id_banco = b.id and b.fl_ativo = true', array('ds_nome_banco', 'nr_banco'));
		$Select->where("p.id_proposta = ?", $this->_proposta);
		$Select->where("p.fl_ativo = true");
		return $this->fetchAll($Select)->toArray();
	}

	public function fetchCoberturaPrincipal() {
		$ret = array();

		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p'=>'seguro.propostas_coberturas'));
		$Select->join(array('c'=>'produto.coberturas'), 'p.id_cobertura = c.id and c.fl_ativo = true', array('ds_nome_cobertura', 'ds_chave_cobertura'));
		$Select->where("p.id_proposta = ?", $this->_proposta);
		$Select->where("p.fl_principal = true");
		$Select->where("p.fl_ativo = true");
		$ret = $this->fetchRow($Select);
		if ($ret) $ret = $ret->toArray();

		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('i'=>'seguro.itens_segurados'), array('count(id) as total', 'sum(vl_lmga) as lmga', 'sum(vl_area) as area'));
		$Select->where("i.id_proposta = ?", $this->_proposta);
		$Select->where("i.fl_ativo = true");
		$Unidades = $this->fetchRow($Select);

		$ret['IS']['total'] = $Unidades->total;
		$ret['IS']['area'] = $Unidades->area;
		$ret['IS']['lmga'] = $Unidades->lmga;

		return $ret;
	}

	public function fetchCoberturasAdicionais() {
		$Rs = array();

		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p'=>'seguro.propostas_coberturas'), array('vl_franquia','vl_taxa','vl_premio', 'vl_lmi'));
		$Select->join(array('c'=>'produto.coberturas'), 'p.id_cobertura = c.id and c.fl_ativo = true', array('ds_nome_cobertura', 'ds_chave_cobertura', 'id'));
		$Select->join(array('pr'=>'seguro.propostas'), 'pr.id = p.id_proposta', array('id_produto'));
		$Select->where("p.id_proposta = ?", $this->_proposta);
		$Select->where("p.fl_principal = false");
		$Select->where("p.fl_ativo = true");
		$Select->order("c.ds_nome_cobertura");
		$Rs = $this->fetchAll($Select)->toArray();

		$return = array();
		$i = 0;
		foreach ($Rs as $Row) {
			$Select = $this->select()->setIntegrityCheck(false);
			$Select->from(array('p'=>'produto.produtos_coberturas'), array('fl_exibir_franquia', 'fl_contratacao_automatica'));
			$Select->where("p.id_produto = ?", $Row['id_produto']);
			$Select->where("p.id_cobertura = ?", $Row['id']);
			$RsCob = $this->fetchRow($Select);

			$return[$i]['vl_franquia']        = $Row['vl_franquia'];
			$return[$i]['vl_taxa']            = $Row['vl_taxa'];
			$return[$i]['vl_premio']          = $Row['vl_premio'];
			$return[$i]['vl_lmi']             = $Row['vl_lmi'];
			$return[$i]['ds_nome_cobertura']  = $Row['ds_nome_cobertura'];
			$return[$i]['ds_chave_cobertura'] = $Row['ds_chave_cobertura'];
			$return[$i]['fl_exibir_franquia'] = $RsCob['fl_exibir_franquia'];
			$return[$i]['fl_contratacao_automatica'] = $RsCob['fl_contratacao_automatica'];
			$i++;
		}
		return $return;
	}

	public function fetchPropostaCroquis() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p'=>'seguro.propostas_arquivos'), array('ds_nome_arquivo'));
		$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->_proposta);
		return $this->fetchAll($Select)->toArray();
	}

	public function fetchPropostaCobranca() {
		$Select = $this->select()->setIntegrityCheck(false);
		$Select->from(array('p'=>'seguro.propostas_parcelas'), array("count(*) as total", "sum(vl_total) as liquido"));
		$Select->where("p.id_proposta = ?", $this->_proposta);
		$Select->where("p.fl_ativo = true");

		$Row = $this->fetchRow($Select);

		$ret['condicao_comercial'] = $Row->total;
		$ret['premio_liquido'] = $Row->liquido;
		$ret['iof'] = 'isento';

		$Select = $this->select()->setIntegrityCheck(false)->distinct();
		$Select->from(array('p'=>'seguro.propostas_parcelas'), array('nr_parcela', 'vl_total', 'vl_segurado', 'vl_subvencao_federal', 'vl_subvencao_estadual', "dt_vencimento"));
		$Select->where("p.id_proposta = ?", $this->_proposta);
		$Select->where("p.fl_ativo = true");
		$Rs = $this->fetchAll($Select);

		if ($Rs->count()) {
			foreach ($Rs as $Row) {
				$Boleto = $this->getBoletoParcela($this->_proposta, $Row->nr_parcela);

				$ret['parcelamento'][$Row->nr_parcela] = $Row->toArray();
				$ret['parcelamento'][$Row->nr_parcela]['nu_boleto'] = $Boleto->nu_boleto;
				$ret['parcelamento'][$Row->nr_parcela]['fl_pago'] = $Boleto->fl_pago;
			}
		}

		return $ret;
	}

	public function getBoletoParcela($idProposta, $nrParcela) {
		$Select = $this->select()->setIntegrityCheck(false)->distinct();
		$Select->from('seguro.proposta_boletos');
		$Select->where('id_proposta = ?', $idProposta);
		$Select->where('nr_parcela = ?', $nrParcela);
		$Select->where('fl_ativo = true');
		return $this->fetchRow($Select);
	}

	public function fetchCarencia($produto) {
		$dateTime = (new Seguro_Model_Propostas())->getDataTransmissaoPropostaMae($this->_proposta);
		
		$configuracoesCondicaoEspecial = (new Produto_Model_CondicaoEspecialConfiguracao())->getConfiguracoesPorProdutoData(
			$produto,
			$dateTime
		);
		
		if (empty($configuracoesCondicaoEspecial)) {
			return [];
		}

		$idsConfiguracoesCondicoesEspeciais = array_column($configuracoesCondicaoEspecial, 'id');

		$select = $this->select()->setIntegrityCheck(false)->distinct(true);
		$select->from(array('pc' => 'produto.produtos_coberturas'), 'fl_cobertura_principal');
		$select->join(array('ce' => 'produto.condicoes_especiais'), 'pc.id_condicao_especial = ce.id', array('ds_titulo', 'ar_condicoes_adicionais'));
		$select->join(array('sc' => 'seguro.propostas_coberturas'), 'sc.id_cobertura = pc.id_cobertura', null);
		$select->join(
			array('configcond' => 'produto.condicao_especial_configuracao'),
			'configcond.id_condicao_especial = ce.id',
			'ds_condicao_especial'
		);
		$select->where('sc.id_proposta = ?', $this->_proposta);
		$select->where('pc.id_produto = ?', $produto);
		$select->where('pc.fl_contratacao_automatica = false');
		$select->where('configcond.id IN (?)', $idsConfiguracoesCondicoesEspeciais);
		$select->order('fl_cobertura_principal DESC');

		return $this->fetchAll($select)->toArray();
	}

	public function fetchAtributos($proposta) {
		$Atributos = new Produto_Model_Atributos();

		$return = array();
		$return['questionario'] = $Atributos->getGrupoAtributo($proposta['id_produto'], 'QUESTIONARIO', $proposta['id_corretor'], $proposta['id_usuario_criacao'], $proposta['proponente']['cpf_cnpj']);
		$return['propriedades'] = $Atributos->getGrupoAtributo($proposta['id_produto'], 'PROPRIEDADE', $proposta['id_corretor'], $proposta['id_usuario_criacao'], $proposta['proponente']['cpf_cnpj']);
		$return['unidades_seguradas'] = $Atributos->getGrupoAtributo($proposta['id_produto'], 'UNIDADE_SEGURADA', $proposta['id_corretor'], $proposta['id_usuario_criacao'], $proposta['proponente']['cpf_cnpj']);

		return $return;
	}

	public function fetchVistoria() {
		$select = $this->select()->setIntegrityCheck(false)->distinct(true);
		$select->from(array('pvp' => 'seguro.propostas_vistorias_previas'), 'emp.ds_nome_fantasia');
		$select->joinLeft(array('prop' => 'seguro.propostas'), 'pvp.id_proposta = prop.id', null);
		$select->joinLeft(array('vis' => 'sistema.vistorias'), 'vis.id= pvp.id_vistoria', null);
		$select->joinLeft(array('vemp' => 'sistema.vistorias_empresas'), 'vemp.id_vistoria= pvp.id_vistoria', null);
		$select->joinLeft(array('emp' => 'sistema.empresas'), 'emp.id= vemp.id_empresa', null);
		$select->where('prop.id = ?', $this->_proposta);
		$Row = $this->fetchRow($select);

		if ($Row) return $Row->toArray();

		return;
	}

}
