<?php

class Sinistro_TransmissaoavisosController extends Agro_Controller_Proposta {
	protected $_paginator = false;
	public $wsdl;
	public $propostas_erros = array();
	public $propostas_enviadas = array();

	public function getModel() {
		return new Sinistro_Model_TransmissaoAvisos();
	}

	public function init() {
	    ini_set('memory_limit','1024M');
		$this->view->title = 'Avisos » Transmissão';
		require_once(APPLICATION_PATH . "/../library/Agro/nusoap/nusoap.php");
		$this->wsdl = "http://ws.nobre.com.br/sinistro.asmx?WSDL";
		$this->client = new nusoap_client($this->wsdl);
	}

	/**
	 * Monta a tela de pesquisa de propostas
	 *
	 */
	public function indexAction() {
		$this->view->form = new Sinistro_Form_TransmissaoSearch();
	}

	public function getFilter() {
		$where = array();

		if ($this->getRequest()->getParam('id_safra')) {
			$where[] = array(
				'field' => 'pr.id_safra',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_safra')
			);
		}

		if ($this->getRequest()->getParam('id_produto')) {
			$where[] = array(
				'field' => 'p.id_produto',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_produto')
			);
		}

		if ($this->getRequest()->getParam('id_corretor')) {
			$where[] = array(
				'field' => 'u.id',
				'operator' => '=',
				'value' => $this->getRequest()->getParam('id_corretor')
			);
		}

		if ($this->getRequest()->getParam('vl_pesquisar_por')) {
			switch ($this->getRequest()->getParam('pesquisar_por')) {
				case 'ds_nome_proponente':
					$field = $this->getRequest()->getParam('pesquisar_por');
					$value = "%".$this->getRequest()->getParam('vl_pesquisar_por')."%";
					$operator = 'ilike';
				case 'ds_cpf_proponente':
					$field = 'pp.cpf_cnpj';
					$value = "%".$this->getRequest()->getParam('vl_pesquisar_por')."%";
					$operator = 'ilike';
					break;
				default:
					$field = "p.".$this->getRequest()->getParam('pesquisar_por');
					$value = $this->getRequest()->getParam('vl_pesquisar_por');
					$operator = '=';
					break;
			}

			$where[] = array (
				'field' => $field,
				'operator' => $operator,
				'value' => $value
			);
		}
		return $where;
	}

	public function transmitirAction(){
		$this->getHelper('ViewRenderer')->setNoRender();
		$this->getHelper('layout')->disableLayout();

		$result = array("status"=>true, "dados"=>"", "message"=>"");
		$arquivo_OK   = time()."_TRANSMISSAO_AVISOS_OK.txt";
		$arquivo_ERRO = time()."_TRANSMISSAO_AVISOS_ERRO.txt";

		$Processos = new Sinistro_Model_Processos();
		$Avisos = new Sinistro_Model_AvisosSinistro();

		$ListAvisos = $this->getRequest()->getParam("id_aviso");

		if ($this->getRequest()->getParam("id_aviso")){
			foreach($ListAvisos as $chave => $aviso){
				$xml = $this->montaXMLTransmissao($aviso);

				$idProcesso = $Processos->getProcessoByAviso($aviso);

				$soapaction = "http://ws.nobre.com.br/AvisarSinistroSeguroAgricola";
				$mysoapmsg = $this->client->serializeEnvelope($xml);
				$response = $this->client->send( $mysoapmsg, $soapaction );
				
				if($response['AvisarSinistroSeguroAgricolaResult']['avisoSinistro']['Codigo']){
					$id_processo_seguradora = $response['AvisarSinistroSeguroAgricolaResult']['avisoSinistro']['Codigo'];

					$Processos->update(array('id_processo_seguradora' => $id_processo_seguradora), "id = $idProcesso");
					$Avisos->update(array('fl_transmissao_seguradora' => true), "id = $aviso");
					$this->geraSalvaXml($aviso, $arquivo_OK, $aviso." - ".$id_processo_seguradora.chr(13).chr(10));
					$this->geraSalvaXml($aviso, $aviso."_aviso.xml", $this->client->request.chr(13).chr(10).chr(13).chr(10));

					$result['arquivo_ok']   = $arquivo_OK;
				} else {
					$this->propostas_erros[] = "definir o que irá aqui";
					$msg = "Aviso: ".$aviso."<br>".chr(13).chr(10).$response[faultcode]."<br>".chr(13).chr(10).$response[faultstring]."<br>".chr(13).chr(10).$response[detail]."<br>".chr(13).chr(10);
					$msg .= '<pre>'.print_r($response['AvisarSinistroSeguroAgricolaResult']['avisoSinistro']['itens'], true).'</pre>';
					$this->geraSalvaXml($aviso, $arquivo_ERRO, $msg);
					$this->geraSalvaXml($aviso, $aviso."_aviso.xml", $mysoapmsg);

					$result['arquivo_erro'] = $arquivo_ERRO;
				}
			}
			$result['status'] = true;
			$result['message'] = "Processamento concluído com sucesso.";
		} else {
			$result['status'] = false;
			$result['message'] = "Marque ao menos um aviso.";
		}

		$this->getResponse()->setBody(Zend_Json::encode($result));

	}

	public function montaXMLTransmissao($id_aviso) {

		$Model = $this->getModel();
		$where[] = array('field' => 'sinistro.v_avisos_transmissao.id', 'operator' => '=','value' => $id_aviso);
		$rsAviso = $Model->fetchRow($Model->getData($where));

		$ModelPropostas = new Seguro_Model_Propostas();
		$Proposta       = $ModelPropostas->get($rsAviso->id_proposta);

		switch ($rsAviso->id_cultura){
			case 6:
			case 28:
			case 80:
			case 81:
			case 36: $vlIntensidade = 15; break;
			case 43:
			case 67:
			case 75: $vlIntensidade = 20; break;
			case 7:
			case 26:
			case 40:
			case 53:
			case 54:
			case 62:
			case 68:
			case 69:
			case 74: $vlIntensidade = 30; break;
			default: $vlIntensidade = 15;
		}

		$xml ='
		  <AvisarSinistroSeguroAgricola xmlns="http://ws.nobre.com.br/">
		    <avisoSinistro xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
		      <comunicacao>
			  <codigo>'.$rsAviso->id.'</codigo>
		      </comunicacao>
		      <ocorrencia>
			<data>'.$this->formataData($rsAviso->dt_sinistro).'</data>
			<causa>
			  <codigo>'.$rsAviso->cd_evento_seguradora.'</codigo>
			</causa>
		      </ocorrencia>
		      <apolice>
			<orgaoProdutor>
			  <codigo>2001</codigo>
			</orgaoProdutor>
		      </apolice>
		      <percentualDano>'.$vlIntensidade.'</percentualDano>
		      <emissao xsi:type="Apolice">
			<orgaoProdutor>
			  <codigo>2001</codigo>
			</orgaoProdutor>
			<numero>'.$rsAviso->nr_apolice.'</numero>
			<contrato>
			  <produto>
			    <ramo>
			      <codigo>1</codigo>
			    </ramo>
			  </produto>
			  <itens>
			  ';
				foreach($Proposta->unidades(false) as $item) {
				    if($item[IS_LMGA_PARCIAL] > 0){
    					$xml .='<item xsi:type="ItemAgricola">
    				      <numero>'.$item[IS_ITEM].'</numero>
    				      <percentualDano>'.$vlIntensidade.'</percentualDano>
    				    </item>';
				    } 
				}

			$xml .='
			  </itens>
			</contrato>
		      </emissao>
		    </avisoSinistro>
		  </AvisarSinistroSeguroAgricola>';

		return $xml;
	}

	public function marcapropostasAction() {
		$this->isAjax();

		$Adapter = new Zend_File_Transfer_Adapter_Http();
		$Adapter->setDestination(APPLICATION_PATH.'/upload_files/temp/');

		$file = $Adapter->getFileInfo();
		if(!$Adapter->receive($file['propostas']['name'])){
			$result['status'] = false;
		} else {
			$dados = file_get_contents(APPLICATION_PATH.'/upload_files/temp/' . $file['propostas']['name']);
			$dados = str_replace("\r\n", ",", $dados);
			$result['propostas'] = $dados;
			$result['status'] = true;
		}
		$this->getResponse()->setBody(Zend_Json::encode($result));
	}

	public function geraSalvaXml($idAviso, $nomeArquivo, $msg) {
		$file = fopen(APPLICATION_PATH."/upload_files/xml_transmissao_error/{$nomeArquivo}", "a+");
	    fwrite($file, $msg);
	    fclose($file);
	}

	public function formataData( $dtData ){
	 	$arData = explode( "-", $dtData );

		$ano = substr( $dtData, 0, 4 );
		$mes = substr( $dtData, 5, 2 );
		$dia = substr( $dtData, 8, 2 );
	    $dtDataFormatada = $ano.'-'.$mes.'-'.$dia;
	    return $dtDataFormatada;
	}
}