<?php

class Agro_Controller_Proposta extends Agro_Controller_Action {

	public function getFilter() {

		$User = Zend_Auth::getInstance()->getIdentity();
		$Status = new Sistema_Model_Status();
		$where = array();

		if ($this->getRequest()->getParam('nr_apolice')) {
			$where[] = array(
					'field' => 'spr.nr_apolice',
					'operator' => '=',
					'value' => trim($this->getRequest()->getParam('nr_apolice'))
			);
		
		} elseif ($this->getRequest()->getParam('id')) {
			$tmp = explode(" ", trim($this->getRequest()->getParam('id')));
			$ids = implode(',', $tmp);
		
			if (count($tmp) > 1) {
				$where[] = "spe.id_endosso in (select id_endosso from seguro.propostas where id in ($ids))";
			} else {
				$where[] = "spe.id_endosso = (select id_endosso from seguro.propostas where id = ($ids))";
			}

			//recupera as safras das propostas informadas no filtro para utilizar na consulta principal
			$Safras = new Produto_Model_Safras();
			$safras = implode(',',array_unique(explode(',',$Safras->getSafrasByPropostas($ids))));
			
			if (!empty($safras)) {
				$where[] = array(
					'field' => 'ppr.id_safra',
					'operator' => 'in',
					'value' => '('.$safras.')'
				);
			}

		}else{		

			if ($this->getRequest()->getParam('fl_parcela_paga') == '1') {
				$where[] = array(
						'field' => 'spa.fl_pago',
						'operator' => '=',
						'value' => $this->getRequest()->getParam('fl_parcela_paga')
				);
			}
			
			if ($this->getRequest()->getParam('ds_coordenadas')) {
				$where[] = array(
						'field' => 'spd.ds_coordenadas',
						'operator' => '=',
						'value' => $this->getRequest()->getParam('ds_coordenadas')
				);
			}
			
			if ($this->getRequest()->getParam('id_corretor')) {
				$where[] = array(
						'field' => 'scr.id_usuario',
						'operator' => '=',
						'value' => $this->getRequest()->getParam('id_corretor')
				);
			}
			
			if ($this->getRequest()->getParam('id_preposto')) {
				$where[] = array(
						'field' => 'spr.id_usuario_criacao',
						'operator' => '=',
						'value' => $this->getRequest()->getParam('id_preposto')
				);
			}
			
			if ($this->getRequest()->getParam('ds_sigla_propriedade')) {
				$where[] = array(
						'field' => 'suf.ds_sigla',
						'operator' => '=',
						'value' => $this->getRequest()->getParam('ds_sigla_propriedade')
				);
			}
			
			if (is_array($this->getRequest()->getParam('id_municipio_propriedade'))) {
				$where[] = array(
					'field' => 'spd.id_municipio',
					'operator' => 'in',
					'value' => '('.implode(',', $this->getRequest()->getParam('id_municipio_propriedade')).')'
				);
			} else if ($this->getRequest()->getParam('id_municipio_propriedade')) {
				$where[] = array(
						'field' => 'spd.id_municipio',
						'operator' => '=',
						'value' => $this->getRequest()->getParam('id_municipio_propriedade')
				);
			}
			
			if ($this->getRequest()->getParam('dt_inicio') && $this->getRequest()->getParam('dt_fim')) {
				$where[] = "to_date(spr.dt_transmissao::varchar, 'yyyy-mm-dd') between to_date('".$this->getRequest()->getParam('dt_inicio')."', 'dd/mm/yyyy') and to_date('".$this->getRequest()->getParam('dt_fim')."', 'dd/mm/yyyy')";
			}
			
			if ($this->getRequest()->getParam('dt_inicio') && !$this->getRequest()->getParam('dt_fim')) {
				$inicio = Agro_Util::formatDate($this->getRequest()->getParam('dt_inicio'), Zend_Date::W3C);
				$where[] = "spr.dt_transmissao >= '$inicio'";
			}
			
			if ($this->getRequest()->getParam('id_status') > 0) {
				if (is_array($this->getRequest()->getParam('id_status'))) {
					$where[] = array(
							'field' => 'spr.id_status',
							'operator' => 'in',
							'value' => '('.implode(',',$this->getRequest()->getParam('id_status')).')'
					);
				} else  {
					$where[] = array(
							'field' => 'spr.id_status',
							'operator' => 'in',
							'value' => '('.$this->getRequest()->getParam('id_status').')'
					);
				}
			}
			
			if ($this->getRequest()->getParam('safras')) {
				$where[] = array(
						'field' => 'ppr.id_safra',
						'operator' => '>=',
						'value' => $this->getRequest()->getParam('safras')
				);
			} elseif ($this->getRequest()->getParam('id_safra')) {
				$where[] = array(
						'field' => 'ppr.id_safra',
						'operator' => '=',
						'value' => $this->getRequest()->getParam('id_safra')
				);
			}

			//validação para o multiselect
			if (is_array($this->getRequest()->getParam('id_produto'))) {
				$where[] = array(
					'field' => 'spr.id_produto',
					'operator' => 'in',
					'value' => '('.implode(',', $this->getRequest()->getParam('id_produto')).')'
			);
			} else if ($this->getRequest()->getParam('id_produto')) {
				$where[] = array(
						'field' => 'spr.id_produto',
						'operator' => '=',
						'value' => $this->getRequest()->getParam('id_produto')
				);
			}
			
			if ($this->getRequest()->getParam('ds_nome_proponente')) {
				$where[] = array(
						'field' => 'spt.ds_nome_proponente',
						'operator' => 'ilike',
						'value' => '%'.$this->getRequest()->getParam('ds_nome_proponente').'%'
				);
			}
			
			if ($this->getRequest()->getParam('ds_cpf_proponente')) {
				$where[] = array(
						'field' => 'spt.cpf_cnpj',
						'operator' => '=',
						'value' => $this->getRequest()->getParam('ds_cpf_proponente')
				);
			}
			
			if ($this->getRequest()->getParam('id_pendencia')) {
				$where[] = array(
						'field' => 'id_pendencia',
						'operator' => '=',
						'value' => $this->getRequest()->getParam('id_pendencia')
				);
			}
			
			if ($this->getRequest()->getParam('id_endosso')){
				$where[] = array(
						'field' => 'spr.id_endosso',
						'operator' => '=',
						'value' => $this->getRequest()->getParam('id_endosso')
				);
			}
			
			if ($this->getRequest()->getParam('fl_proposta_vigente') == '0'){
				$where[] = array(
						'field' => 'spe.fl_proposta_vigente',
						'operator' => '=',
						'value' => $this->getRequest()->getParam('fl_proposta_vigente')
				);
			}
			
			if ($this->getRequest()->getParam('id_cultura')) {
				$where[] = array(
					'field' => 'pcul.id',
					'operator' => '=',
					'value' => $this->getRequest()->getParam('id_cultura')
				);
			}
		
		}

		if ($User->tp_usuario == 'C') {
			$where[] = array(
					'field' => 'scr.id_usuario',
					'operator' => '=',
					'value' => $User->id
			);
		}
		
		if ($User->tp_usuario == 'P') {
			$where[] = array(
					'field' => 'spr.id_usuario_criacao',
					'operator' => '=',
					'value' => $User->id
			);
		}		

		if ($this->getRequest()->getParam('tp_assinatura')) {

			$condicao = " (sptad.tipo_assinatura in (" . $this->getRequest()->getParam('tp_assinatura') . ") AND sptad.fl_ativo is true) ";
			if (!empty(strstr($this->getRequest()->getParam('tp_assinatura'), (string)Seguro_Model_PropostasTipoAssinaturaDocumento::NAO_INFORMADA))) {
				$condicao .= " OR sptad.id is null ";
			}

			if (!empty($this->getRequest()->getParam('id'))) {
				$condicao = "sptad.fl_ativo is true OR sptad.id is null";
			}

			$where[] = $condicao;
		} else {
			$moduleName = Zend_Controller_Front::getInstance()->getRequest()->getModuleName();
			if (
                ($moduleName == 'atendimento' || $moduleName == 'seguro')
                && $this->getRequest()->getParam('fl_proposta_vigente') <> '0'
                && !$this->getRequest()->has('pendenciasChamados')
            ) {
				$where[] = array(
						'field' => 'spe.fl_proposta_vigente',
						'operator' => '=',
						'value' => '1'
				);
			}
		}

 		return $where;
	}

    /**
     * Cancela ou transfere a vistoria prévia para a proposta vigente
     * Valida somente vistorias com status:
     *   => 66/AGUARDANDO_VISTORIA: Encaminhada
     *   => 70/ENC: Aguardando Vistoria
     *
     *   => 227: Cancelada
     *
     * @param int $idPropostaAtual
     * @return bool
     * @throws Exception
     */
    protected function cancelarVistoriaPrevia(int $idPropostaAtual): bool {
        $ModelVistoria = new Seguro_Model_VistoriaPrevia();
        $modelStatus = new Sistema_Model_Status();
        $modelPropostas = new Endosso_Model_Propostas();

        $idVistoria = $ModelVistoria->getIdVistoria($idPropostaAtual);

        if (empty($idVistoria)) {
            return true;
        }

        $vistoria = $ModelVistoria->getRow($idVistoria);
        $dsChaveStatus = $modelStatus->getChave($vistoria['id_status']);

        if (!in_array($dsChaveStatus, ['AGUARDANDO_VISTORIA', 'ENC'])) {
            return true;
        }

        $propostaVigente = $modelPropostas->getPropostaVigente($idPropostaAtual);

        if (!empty($propostaVigente) && $propostaVigente != $idPropostaAtual) {
			$vistoria['id_proposta'] = $propostaVigente;
			$vistoria->save();
			return true;
        }

        $vistoria['id_status'] = '227';

        if ($vistoria->save()) {
			$ModelVistoriaEmpresas = new Sistema_Model_VistoriasEmpresas();
			$idEmpresa = $ModelVistoriaEmpresas->getEmpresaByVistoria($idVistoria);

	        $dados = array();
			$dados['id_proposta_vistoria'] = $vistoria['id'];
			$dados['id_status'] = $vistoria['id_status'];
			$dados['id_status_analise'] = $vistoria['id_status_analise'];
			$dados['id_empresa_historico'] = $idEmpresa;
			$dados['ds_motivo'] = "Cancelada automaticamente por consequência de cancelamento da proposta e/ou apólice.";

			$ModelVistoriasHistorico = new Seguro_Model_VistoriaPreviaHistorico();
			$ModelVistoriasHistorico->save($dados);
        }

        return true;
    }
}
