<?php
	date_default_timezone_set('America/Sao_Paulo');
	
	header('Access-Control-Allow-Origin: *');
	header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

	session_start();
	
	include_once "/var/www/desktop/php/datapacket.php";
	include_once "/var/www/desktop/php/TParams.class.php";
	
	// print_r
	function debug($data){
		echo "<pre>";
		print_r($data);
		echo "</pre>";
	}

	class CTe extends TParams{
	
		public $xml='<?xml version="1.0" encoding="UTF-8"?>';
		public $key='';
		public $cDV='';
		public $anomes='';
		public $cte_nct=0;
		public $TParams;
		public $tpAmb='homologacao';
		public $dirAguardando = '';
		public $dirAutorizada = '';
		public $dirCancelada = '';
		public $dirDenegada = '';
		public $dirTemporaria = '';

		private $company='';
		private $rowdata='';
		
		public function __construct($cte_nct,$emp_codigo){
		
			$this->TParams = new TParams();

			$filtroCompany = '{"cod":"500890","params":[{"name":"emp_codigo","value":"'.$emp_codigo.'","type":"string"}]}';

			$datapacket = new Datapacket();
			$datapacket->debug(true);
			$datapacket->setHost($this->TParams->getHost("empresas"));
			$datapacket->add($filtroCompany);
			$ret = $datapacket->open(true);
			$datapacket->clear();
			$this->company = $ret[0];

			$filtroRowdata = '{"cod":"500891","params":[{"name":"database","value":"'.$this->company->{'emp_db_comum'}.'","type":"other"},{"name":"cte_nct","value":"'.$cte_nct.'","type":"string"}]}';
			
			$datapacket->setHost($this->TParams->getHost($this->TParams->getDbSge()));
			$datapacket->add($filtroRowdata);
			$ret = $datapacket->open(true);
			// echo $datapacket->getLastQuery();
			$datapacket->clear();
			$this->rowdata = $ret[0];

			$this->anomes = substr(date("Y",strtotime($this->rowdata->cte_data)),2,2).date("m",strtotime($this->rowdata->cte_data));
			$this->cte_nct=$cte_nct;

			$this->tpAmb = 'producao';
			
			if($this->company->emp_ambcte==1){
			}else{
				$this->tpAmb = 'homologacao';
			}
			
			// estrutura de pastas para armazenamento da cte
			$this->dirAguardando = $this->TParams->getUploads().$this->company->emp_codigo.'/cte/'.$this->tpAmb.'/aguardando/';
			$this->dirAutorizada = $this->TParams->getUploads().$this->company->emp_codigo.'/cte/'.$this->tpAmb.'/autorizadas/';
			$this->dirCancelada  = $this->TParams->getUploads().$this->company->emp_codigo.'/cte/'.$this->tpAmb.'/canceladas/';
			$this->dirDenegada 	 = $this->TParams->getUploads().$this->company->emp_codigo.'/cte/'.$this->tpAmb.'/denegadas/';
			$this->dirTemporaria = $this->TParams->getUploads().$this->company->emp_codigo.'/cte/'.$this->tpAmb.'/temporarias/';
			$this->dirCartaCorrecao = $this->TParams->getUploads().$this->company->emp_codigo.'/cte/'.$this->tpAmb.'/cartaCorrecao/';
			if(!is_dir($this->dirAguardando.$this->anomes)){
				@mkdir($this->dirAguardando.$this->anomes, 0777, true);
			}
			if(!is_dir($this->dirAutorizada.$this->anomes)){
				@mkdir($this->dirAutorizada.$this->anomes, 0777, true);
			}
			if(!is_dir($this->dirCancelada.$this->anomes)){
				@mkdir($this->dirCancelada.$this->anomes, 0777, true);
			}
			if(!is_dir($this->dirDenegada.$this->anomes)){
				@mkdir($this->dirDenegada.$this->anomes, 0777, true);
			}
			if(!is_dir($this->dirTemporaria.$this->anomes)){
				@mkdir($this->dirTemporaria.$this->anomes, 0777, true);
			}
			if(!is_dir($this->dirCartaCorrecao.$this->anomes)){
				@mkdir($this->dirCartaCorrecao.$this->anomes, 0777, true);
			}
			
		}
		
		public function getKeyDv($chave) {
			$soma_ponderada = 0;
			$multiplicadores = array(2,3,4,5,6,7,8,9);
			$i = 42;
			while ($i >= 0) {
				for ($m=0; $m<count($multiplicadores) && $i>=0; $m++) {
					$soma_ponderada+= $chave[$i] * $multiplicadores[$m];
					$i--;
				}
			}
			$resto = $soma_ponderada % 11;
			if ($resto == '0' || $resto == '1') {
				return 0;
			} else {
				return (11 - $resto);
		   }
		}		

		public function getKey($params='') {

			/*
			  · cUF - Código da UF do emitente do Documento Fiscal   2
			  · AAMM - Ano e Mês de emissão do CT-e 4
			  · CNPJ - CNPJ do emitente 14
			  · mod - Modelo do Documento Fiscal 2
			  · serie - Série do Documento Fiscal 3
			  · nCT - Número do Documento Fiscal 9
			  · tpEmis ? Forma de emissão do CT-e 1
			  · cCT - Código Numérico que compõe a Chave de Acesso 8
			  · cDV - Dígito Verificador da Chave de Acesso 1
			*/

			if($params){

				$obj 	= json_decode(base64_decode($params));
				$cUF	= $obj->cUF;
				$AAMM	= $obj->AAMM;
				$CNPJ	= $obj->CNPJ;
				$mod	= 57;
				$serie	= 1;
				$nCT	= $obj->nCT;
				$tpEmis	= $obj->tpEmis;
				$cCT	= $obj->cCT;

			}else{

				$cUF	= substr($this->company->emp_codmun,0,2);
				$AAMM	= substr($this->rowdata->cte_data,2,2).substr($this->rowdata->cte_data,5,2);
				$CNPJ	= $this->company->emp_cpfcnpj;
				$mod	= 57;
				$serie	= 1;
				$nCT	= $this->rowdata->cte_nct;
				$tpEmis	= 1;
				$cCT	= $this->rowdata->cte_codigo;
				
			}

			// 02 - cUF  - código da UF do emitente do Documento Fiscal
			$chave = sprintf("%02d", $cUF);

			// 04 - AAMM - Ano e Mes de emissão da NF-e
			$chave.= sprintf("%04s", $AAMM);

			// 14 - CNPJ - CNPJ do emitente
			$chave.= sprintf("%014s", $CNPJ);

			// 02 - mod  - Modelo do Documento Fiscal
			$chave.= sprintf("%02d", $mod);

			// 03 - serie - Série do Documento Fiscal
			$chave.= sprintf("%03d", $serie);

			// 09 - nCT  - Número do Documento Fiscal
			$chave.= sprintf("%09d", $nCT);

			// 01 - tpEmis  - Tipo emissão 
			$chave.= sprintf("%01d", $tpEmis);

			// 08 - cCT  - Código Numérico que compõe a Chave de Acesso // diminui 1 digito na versão 2.0
			$chave.= sprintf("%08d", $cCT);

			// 01 - cDV  - Dígito Verificador da Chave de Acesso
			$chave.= $this->getKeyDv($chave);

			return $chave;
		}
		
		public function getAliqIcms($uf){
			if($uf=='PR' || $uf=='SC' || $uf=='RS' || $uf=='MG' || $uf=='RJ' || $uf=='SP'){
				return 12;
			}else{
				return 7;
			}
		}
		
		public function getPFCPUFFim($uf){
			if($uf=='AC'){
				return "0";
			}
			if($uf=='AL'){
				return "0";
			}
			if($uf=='AP'){
				return "0";
			}
			if($uf=='AM'){
				return "0";
			}
			if($uf=='BA'){
				return "0";
			}
			if($uf=='CE'){
				return "0";
			}
			if($uf=='DF'){
				return "0";
			}
			if($uf=='ES'){
				return "0";
			}
			if($uf=='GO'){
				return "0";
			}
			if($uf=='MA'){
				return "0";
			}
			if($uf=='MT'){
				return "0";
			}
			if($uf=='MS'){
				return "0";
			}
			if($uf=='MG'){
				return "0";
			}
			if($uf=='PR'){
				return "0";
			}
			if($uf=='PB'){
				return "0";
			}
			if($uf=='PA'){
				return "0";
			}
			if($uf=='PE'){
				return "0";
			}
			if($uf=='PI'){
				return "0";
			}
			if($uf=='RJ'){
				return "1";
			}
			if($uf=='RN'){
				return "0";
			}
			if($uf=='RS'){
				return "0";
			}
			if($uf=='RO'){
				return "0";
			}
			if($uf=='RR'){
				return "0";
			}
			if($uf=='SC'){
				return "0";
			}
			if($uf=='SE'){
				return "0";
			}
			if($uf=='SP'){
				return "1";
			}
			if($uf=='TO'){
				return "0";
			}
		}
		
		private function fusohorario($hora){
			
			$hora = explode("-",$this->rowdata->cte_hora);
			
			$novaHora = $hora[0]+$this->company->emp_gmt;
			
			if($novaHora==24){
				$novaHora = 0;
			}elseif($novaHora==25){
				$novaHora = 1;
			}elseif($novaHora==-1){
				$novaHora = 23;
			}elseif($novaHora==-2){
				$novaHora = 22;
			}

			$novaHora = str_pad($novaHora,2,'0',STR_PAD_LEFT).':'.str_pad($hora[1],2,'0',STR_PAD_LEFT).':'.str_pad($hora[2],2,'0',STR_PAD_LEFT);
			return $novaHora;
		}
		
		public function getXML(){
			// if (!this.empresa) throw 'Dados da empresa não está definido';
			
			$items = json_decode(base64_decode($this->rowdata->cte_itens));
			$infNFe='';
			$infOutros='';
			$infDoc='';
			foreach($items as $item){
				if(strlen($item[0]) == 44){
					$infNFe .= '<infNFe><chave>'.$item[0].'</chave></infNFe>';
				}else if(strlen($item[0]) == 11 || strlen($item[0]) == 14){
					$infOutros .= '<infOutros>';
						$infOutros .= '<tpDoc>99</tpDoc>';
						$infOutros .= '<descOutros>Outros</descOutros>';
						$infOutros .= '<nDoc>'.$item[0].'</nDoc>';
					$infOutros .= '</infOutros>';
				}
			}
			
			if(!empty($infNFe)){
				$infDoc = $infNFe;
			}else if(!empty($infOutros)){
				$infDoc = $infOutros;
			}

			$novaHora = $this->fusohorario($this->rowdata->cte_hora);
			
			$foneRem =  $this->rowdata->rem_tel_ddd.$this->rowdata->rem_tel_prefixo.$this->rowdata->rem_tel_numero;
			$foneDest = $this->rowdata->dest_tel_ddd.$this->rowdata->dest_tel_prefixo.$this->rowdata->dest_tel_numero;
			
			// $this->xml .= '<cteProc versao="1.04" xmlns="http://www.portalfiscal.inf.br/cte">';
			$this->xml = '<CTe xmlns="http://www.portalfiscal.inf.br/cte">';
			$this->xml .= '<infCte versao="2.00" Id="CTe'.$this->getKey().'">';
			
			$this->xml.='<ide>';
				
				$this->xml.='<cUF>'.substr($this->company->emp_codmun,0,2).'</cUF>';
				$this->xml.='<cCT>'.str_pad($this->rowdata->cte_codigo,8,'0',STR_PAD_LEFT).'</cCT>';
				$this->xml.='<CFOP>'.$this->rowdata->cfo_codigo.'</CFOP>';
				$this->xml.='<natOp>'.substr($this->rowdata->cte_natop,0,60).'</natOp>';
				$this->xml.='<forPag>'.$this->rowdata->cdp_indpag.'</forPag>'; // 0-pago 1-a pagar ou 2-outros
				$this->xml.='<mod>57</mod>';
				$this->xml.='<serie>1</serie>';
				$this->xml.='<nCT>'.$this->rowdata->cte_nct.'</nCT>';
				$this->xml.='<dhEmi>'.$this->rowdata->cte_data.'T'.$novaHora.'</dhEmi>';
				$this->xml.='<tpImp>1</tpImp>';
				$this->xml.='<tpEmis>1</tpEmis>';
				$this->xml.='<cDV>'.$this->getKeyDv($this->getKey()).'</cDV>';
				//$this->xml.='<tpAmb>2</tpAmb>';
				$this->xml.='<tpAmb>'.$this->rowdata->cte_ambcte.'</tpAmb>';
				if($this->rowdata->cte_tpcte == 1){
					$this->xml.='<tpCTe>'.$this->rowdata->cte_tpcte.'</tpCTe>';
				}else{
					$this->xml.='<tpCTe>0</tpCTe>';
				}
				$this->xml.='<procEmi>0</procEmi>';
				$this->xml.='<verProc>1</verProc>';
				//$this->xml.='<refCTe_Opc>'.$this->rowdata->cte_key.'</refCTe_Opc>'; // 2.00 verificar obrigatoriedade
				$this->xml.='<cMunEnv>'.$this->company->emp_codmun.'</cMunEnv>';
				$this->xml.='<xMunEnv>'.$this->company->emp_cidade.'</xMunEnv>';
				$this->xml.='<UFEnv>'.$this->company->emp_uf.'</UFEnv>';
				$this->xml.='<modal>01</modal>'; //acrescentar pcao 6
				$this->xml.='<tpServ>'.$this->rowdata->cte_tpserv.'</tpServ>'; //2.00 acrescentar a opcao 4 servico vinculado a multimodal
				$this->xml.='<cMunIni>'.$this->rowdata->cte_cmunini.'</cMunIni>';
				$this->xml.='<xMunIni>'.$this->rowdata->cte_xmunini.'</xMunIni>';
				$this->xml.='<UFIni>'.$this->rowdata->cte_ufini.'</UFIni>';
				$this->xml.='<cMunFim>'.$this->rowdata->cte_cmunfim.'</cMunFim>';
				$this->xml.='<xMunFim>'.$this->rowdata->cte_xmunfim.'</xMunFim>';
				$this->xml.='<UFFim>'.$this->rowdata->cte_uffim.'</UFFim>';
				$this->xml.='<retira>1</retira>';
				$this->xml.='<xDetRetira>Sera entregue no endereço do destinatario</xDetRetira>';
				
				if($this->rowdata->cad_toma=='1') {
					
					$this->xml.='<toma03>';
						$this->xml.='<toma>'.$this->rowdata->cad_toma.'</toma>';					
					$this->xml.='</toma03>';
					
					$this->xml.='<enderToma>';
						$this->xml.='<xLgr>'.trim($this->rowdata->exp_end_nome).'</xLgr>';
						$this->xml.='<nro>'.$this->rowdata->exp_end_num.'</nro>';
						$this->xml.='<xBairro>'.trim($this->rowdata->exp_end_bairro).'</xBairro>';
						$this->xml.='<cMun>'.trim($this->rowdata->exp_cad_codmun).'</cMun>';
						$this->xml.='<xMun>'.trim($this->rowdata->exp_cad_cidade).'</xMun>';
						$this->xml.='<UF>'.trim($this->rowdata->exp_cad_uf).'</UF>';
						$this->xml.='<cPais>1058</cPais>';
						$this->xml.='<xPais>BRASIL</xPais>';
					$this->xml.='</enderToma>';

				}else if($this->rowdata->cad_toma=='4'){
					$this->xml.='<toma4>';
						$this->xml.='<toma>'.$this->rowdata->cad_toma.'</toma>';
						$this->xml.='<CNPJ>'.$this->rowdata->exp_cad_cnpjcpf.'</CNPJ>';
						$this->xml.='<IE>'.$this->rowdata->exp_cad_inscrg.'</IE>';
						$this->xml.='<xNome>'.$this->rowdata->exp_cad_nomeraz.'</xNome>';
						$this->xml.='<xFant>'.$this->rowdata->exp_cad_snomefant.'</xFant>';
						$this->xml.='<fone>'.$this->rowdata->exp_tel_ddd.$this->rowdata->exp_tel_prefixo.$this->rowdata->exp_tel_numero.'</fone>';
						$this->xml.='<enderToma>';
							$this->xml.='<xLgr>'.trim($this->rowdata->exp_end_nome).'</xLgr>';
							$this->xml.='<nro>'.$this->rowdata->exp_end_num.'</nro>';
							$this->xml.='<xBairro>'.trim($this->rowdata->exp_end_bairro).'</xBairro>';
							$this->xml.='<cMun>'.trim($this->rowdata->exp_cad_codmun).'</cMun>';
							$this->xml.='<xMun>'.trim($this->rowdata->exp_cad_cidade).'</xMun>';
							$this->xml.='<UF>'.trim($this->rowdata->exp_cad_uf).'</UF>';
							$this->xml.='<cPais>1058</cPais>';
							$this->xml.='<xPais>BRASIL</xPais>';
						$this->xml.='</enderToma>';
					$this->xml.='</toma4>';
				}else{
					$this->xml.='<toma03>';
						$this->xml.='<toma>'.$this->rowdata->cad_toma.'</toma>';
					$this->xml.='</toma03>';
				}

			$this->xml.='</ide>';

			$this->xml.='<compl>';
				$this->xml.='<fluxo/>'; 
			$this->xml.='</compl>';
			
			$this->xml.='<emit>';
				$this->xml.='<CNPJ>'.$this->company->emp_cpfcnpj.'</CNPJ>';
				$this->xml.='<IE>'.$this->company->emp_inscrg.'</IE>';
				$this->xml.='<xNome>'.str_replace("&","",$this->company->emp_razao).'</xNome>';
				$this->xml.='<xFant>'.str_replace("&","",$this->company->emp_fantasia).'</xFant>';
				$this->xml.='<enderEmit>';
					$this->xml.='<xLgr>'.trim($this->company->emp_endereco).'</xLgr>';
					$this->xml.='<nro>'.$this->company->emp_num.'</nro>';
					$this->xml.='<xBairro>'.trim($this->company->emp_bairro).'</xBairro>';
					$this->xml.='<cMun>'.trim($this->company->emp_codmun).'</cMun>';
					$this->xml.='<xMun>'.trim($this->company->emp_cidade).'</xMun>';
					$this->xml.='<CEP>'.$this->company->emp_cep.'</CEP>';
					$this->xml.='<UF>'.trim($this->company->emp_uf).'</UF>';
					$this->xml.='<fone>'.str_replace(array('-','(',')'),array('','',''),$this->company->emp_fone).'</fone>';	
					// $this->xml.='<cPais>1058</cPais>';
					// $this->xml.='<xPais>BRASIL</xPais>';
				$this->xml.='</enderEmit>';
			$this->xml.='</emit>';
			
			$this->xml.='<rem>';
				if(strlen($this->rowdata->rem_cad_cnpjcpf)==11){
					$this->xml.='<CPF>'.$this->rowdata->rem_cad_cnpjcpf.'</CPF>';
					$this->xml.='<IE></IE>';
				}else{
					$this->xml.='<CNPJ>'.$this->rowdata->rem_cad_cnpjcpf.'</CNPJ>';
					$this->xml.='<IE>'.$this->rowdata->rem_cad_inscrg.'</IE>';
				}				
				$this->xml.='<xNome>'.str_replace("&","",$this->rowdata->rem_cad_nomeraz).'</xNome>';
				// $this->xml.='<xFant>'.$this->rowdata->emp_fantasia.'</xFant>';
				//$this->xml.='<fone>'.$this->rowdata->rem_tel_ddd.$this->rowdata->rem_tel_prefixo.$this->rowdata->rem_tel_numero.'</fone>';
				if($foneRem!=''){
					$this->xml.='<fone>'.$this->rowdata->rem_tel_ddd.$this->rowdata->rem_tel_prefixo.$this->rowdata->rem_tel_numero.'</fone>';
				}else{
					$this->xml.='<fone>0000000000</fone>';
				}
				$this->xml.='<enderReme>';
					$this->xml.='<xLgr>'.trim($this->rowdata->rem_end_nome).'</xLgr>';
					$this->xml.='<nro>'.$this->rowdata->rem_end_num.'</nro>';
					$this->xml.='<xBairro>'.trim($this->rowdata->rem_end_bairro).'</xBairro>';
					$this->xml.='<cMun>'.trim($this->rowdata->rem_cad_codmun).'</cMun>';
					$this->xml.='<xMun>'.trim($this->rowdata->rem_cad_cidade).'</xMun>';
					$this->xml.='<UF>'.trim($this->rowdata->rem_cad_uf).'</UF>';
					// $this->xml.='<CEP>'.$this->rowdata->end_cep.'</CEP>';
					// $this->xml.='<fone>'.$this->rowdata->tel_ddd.$this->rowdata->tel_prefixo.$this->rowdata->tel_numero.'</fone>';
					$this->xml.='<cPais>1058</cPais>';
					$this->xml.='<xPais>BRASIL</xPais>';
				$this->xml.='</enderReme>';
				/*$this->xml.='<locColeta> informar somente quando for diferente do endereco do remetente
						<CNPJ>99999999000191</CNPJ>
						<xNome>DIAS e DIAS TENTANDO S/A</xNome>
						<xLgr>AV PRINCIPAL</xLgr>
						<nro>S/N</nro>
						<xCpl>10 andar</xCpl>
						<xBairro>CENTRO</xBairro>
						<cMun>3550308</cMun>
						<xMun>SAO PAULO</xMun>
						<UF>SP</UF>
					</locColeta>';*/
			$this->xml.='</rem>';

			if(isset($this->rowdata->exp_cad_nomeraz) && !empty($this->rowdata->exp_cad_nomeraz)){
				$this->xml.='<exped>';
					if(strlen($this->rowdata->exp_cad_cnpjcpf)==11){
						$this->xml.='<CPF>'.$this->rowdata->exp_cad_cnpjcpf.'</CPF>';
						$this->xml.='<IE></IE>';
					}else{
						$this->xml.='<CNPJ>'.$this->rowdata->exp_cad_cnpjcpf.'</CNPJ>';
						$this->xml.='<IE>'.$this->rowdata->exp_cad_inscrg.'</IE>';
					}				
					$this->xml.='<xNome>'.str_replace("&","",$this->rowdata->exp_cad_nomeraz).'</xNome>';
					
					$foneexp = $this->rowdata->exp_tel_ddd.$this->rowdata->exp_tel_prefixo.$this->rowdata->exp_tel_numero;
					if($foneexp!=''){
						$this->xml.='<fone>'.$foneexp.'</fone>';
					}else{
						$this->xml.='<fone>0000000000</fone>';
					}
					$this->xml.='<enderExped>';
						$this->xml.='<xLgr>'.trim($this->rowdata->exp_end_nome).'</xLgr>';
						$this->xml.='<nro>'.$this->rowdata->exp_end_num.'</nro>';
						$this->xml.='<xBairro>'.trim($this->rowdata->exp_end_bairro).'</xBairro>';
						$this->xml.='<cMun>'.trim($this->rowdata->exp_cad_codmun).'</cMun>';
						$this->xml.='<xMun>'.trim($this->rowdata->exp_cad_cidade).'</xMun>';
						$this->xml.='<UF>'.trim($this->rowdata->exp_cad_uf).'</UF>';
						$this->xml.='<cPais>1058</cPais>';
						$this->xml.='<xPais>BRASIL</xPais>';
					$this->xml.='</enderExped>';
				$this->xml.='</exped>';
			}

			if(isset($this->rowdata->rec_cad_nomeraz) && !empty($this->rowdata->rec_cad_nomeraz)){
				$this->xml.='<receb>';
					if(strlen($this->rowdata->rec_cad_cnpjcpf)==11){
						$this->xml.='<CPF>'.$this->rowdata->rec_cad_cnpjcpf.'</CPF>';
						$this->xml.='<IE></IE>';
					}else{
						$this->xml.='<CNPJ>'.$this->rowdata->rec_cad_cnpjcpf.'</CNPJ>';
						$this->xml.='<IE>'.$this->rowdata->rec_cad_inscrg.'</IE>';
					}				
					$this->xml.='<xNome>'.str_replace("&","",$this->rowdata->rec_cad_nomeraz).'</xNome>';
					
					$fonerec = $this->rowdata->rec_tel_ddd.$this->rowdata->rec_tel_prefixo.$this->rowdata->rec_tel_numero;
					if($fonerec!=''){
						$this->xml.='<fone>'.$fonerec.'</fone>';
					}else{
						$this->xml.='<fone>0000000000</fone>';
					}
					$this->xml.='<enderReceb>';
						$this->xml.='<xLgr>'.trim($this->rowdata->rec_end_nome).'</xLgr>';
						$this->xml.='<nro>'.$this->rowdata->rec_end_num.'</nro>';
						$this->xml.='<xBairro>'.trim($this->rowdata->rec_end_bairro).'</xBairro>';
						$this->xml.='<cMun>'.trim($this->rowdata->rec_cad_codmun).'</cMun>';
						$this->xml.='<xMun>'.trim($this->rowdata->rec_cad_cidade).'</xMun>';
						$this->xml.='<UF>'.trim($this->rowdata->rec_cad_uf).'</UF>';
						$this->xml.='<cPais>1058</cPais>';
						$this->xml.='<xPais>BRASIL</xPais>';
					$this->xml.='</enderReceb>';
				$this->xml.='</receb>';
			}
			
			$this->xml.='<dest>'; //destinatario nao e obrigatorio
				if(strlen($this->rowdata->dest_cad_cnpjcpf)==11){
					$this->xml.='<CPF>'.$this->rowdata->dest_cad_cnpjcpf.'</CPF>';
					$this->xml.='<IE></IE>';
				}else{
					$this->xml.='<CNPJ>'.$this->rowdata->dest_cad_cnpjcpf.'</CNPJ>';
					$this->xml.='<IE>'.$this->rowdata->dest_cad_inscrg.'</IE>';
				}
				$this->xml.='<xNome>'.str_replace("&","",$this->rowdata->dest_cad_nomeraz).'</xNome>';
				// $this->xml.='<xFant>'.$this->rowdata->emp_fantasia.'</xFant>';
				if($foneDest!=''){
					$this->xml.='<fone>'.$this->rowdata->dest_tel_ddd.$this->rowdata->dest_tel_prefixo.$this->rowdata->dest_tel_numero.'</fone>';
				}else{
					$this->xml.='<fone>0000000000</fone>';
				}
				$this->xml.='<enderDest>';
						$this->xml.='<xLgr>'.trim($this->rowdata->dest_end_nome).'</xLgr>';
						$this->xml.='<nro>'.$this->rowdata->dest_end_num.'</nro>';
						$this->xml.='<xBairro>'.trim($this->rowdata->dest_end_bairro).'</xBairro>';
						$this->xml.='<cMun>'.trim($this->rowdata->dest_cad_codmun).'</cMun>';
						$this->xml.='<xMun>'.trim($this->rowdata->dest_cad_cidade).'</xMun>';
						$this->xml.='<UF>'.trim($this->rowdata->dest_cad_uf).'</UF>';
						// $this->xml.='<CEP>'.$this->rowdata->dest_cad_cep.'</CEP>';
						// $this->xml.='<fone>'.$this->rowdata->emp_fone.'</fone>';
						$this->xml.='<cPais>1058</cPais>';
						$this->xml.='<xPais>BRASIL</xPais>';
				$this->xml.='</enderDest>';
			$this->xml.='</dest>';	
			
			$this->xml.='<vPrest>';
			
				$cte_vtprest = '0';
				if($this->rowdata->cte_vtprest>0){
					$cte_vtprest = number_format($this->rowdata->cte_vtprest,2,'.','');
				}
				
				$cte_vrec = '0';
				if($this->rowdata->cte_vrec>0){
					$cte_vrec = number_format($this->rowdata->cte_vrec,2,'.','');
				}

				$this->xml.='<vTPrest>'.$cte_vtprest.'</vTPrest>';				
				$this->xml.='<vRec>'.$cte_vrec.'</vRec>';
				
				if($this->rowdata->cte_valpedagio>0){
					$this->xml.='<Comp>';
						$cte_valpedagio = number_format($this->rowdata->cte_valpedagio,2,'.','');
						$this->xml.='<xNome>PEDAGIO</xNome>';
						$this->xml.='<vComp>'.$cte_valpedagio.'</vComp>';
					$this->xml.='</Comp>';
				}
				
				if($this->rowdata->cte_valseg>0){
					$this->xml.='<Comp>';
						$cte_valseg = number_format($this->rowdata->cte_valseg,2,'.','');
						$this->xml.='<xNome>SEGURO</xNome>';
						$this->xml.='<vComp>'.$cte_valseg.'</vComp>';
					$this->xml.='</Comp>';
				}
				
				if($this->rowdata->cte_valredesp>0){
					$this->xml.='<Comp>';
						$cte_valredesp = number_format($this->rowdata->cte_valredesp,2,'.','');
						$this->xml.='<xNome>REDESPACHO</xNome>';
						$this->xml.='<vComp>'.$cte_valredesp.'</vComp>';
					$this->xml.='</Comp>';
				}
				
				if($this->rowdata->cte_valadic>0){
					$this->xml.='<Comp>';
						$cte_valadic = number_format($this->rowdata->cte_valadic,2,'.','');
						$this->xml.='<xNome>ADICIONAL</xNome>';
						$this->xml.='<vComp>'.$cte_valadic.'</vComp>';
					$this->xml.='</Comp>';
				}
				
				if($this->rowdata->cte_valoutros>0){
					
					$this->xml.='<Comp>';				
						$cte_valoutros = number_format($this->rowdata->cte_valoutros,2,'.','');
						$this->xml.='<xNome>OUTROS</xNome>';
						$this->xml.='<vComp>'.$cte_valoutros.'</vComp>';
					$this->xml.='</Comp>';
				}
				
				if($this->rowdata->cte_valdesc>0){
					
					$this->xml.='<Comp>';				
						$cte_valdesc = number_format($this->rowdata->cte_valdesc,2,'.','');
						$this->xml.='<xNome>DESCONTOS</xNome>';
						$this->xml.='<vComp>'.$cte_valdesc.'</vComp>';
					$this->xml.='</Comp>';
				}
			$this->xml.='</vPrest>';
			
			$pIcms = 0;
			
			$this->xml.='<imp>';
				if($this->rowdata->cte_sitribu==='0'){
					$this->xml.='<ICMS>';
						$this->xml.='<ICMSSN>';
							$this->xml.='<indSN>1</indSN>';
						$this->xml.='</ICMSSN>';
					$this->xml.='</ICMS>';
				}else if($this->rowdata->cte_sitribu=='4540'){
					$this->xml.='<ICMS>';
						$this->xml.='<ICMS45>';
							$this->xml.='<CST>40</CST>';
						$this->xml.='</ICMS45>';
					$this->xml.='</ICMS>';
				}else if($this->rowdata->cte_sitribu=='4541'){
						$this->xml.='<ICMS>';
							$this->xml.='<ICMS45>';
								$this->xml.='<CST>41</CST>';
							$this->xml.='</ICMS45>';
						$this->xml.='</ICMS>';
				}else{
					$this->xml.='<ICMS>';
						if($this->rowdata->cte_icmssubs>0){
							$this->xml.='<ICMS60>';
								$this->xml.='<CST>60</CST>';
								$this->xml.='<vBCSTRet>'.$this->rowdata->cte_baseicms.'</vBCSTRet>';
								$this->xml.='<vICMSSTRet>'.($this->rowdata->cte_baseicms * ($this->rowdata->cte_aliqicms/100)).'</vICMSSTRet>';
								$this->xml.='<pICMSSTRet>'.$this->rowdata->cte_aliqicms.'</pICMSSTRet>';
								//$this->xml.='<vCred></vCred>';
							$this->xml.='</ICMS60>';
						}else{
							$this->xml.='<ICMS00>';
								$this->xml.='<CST>00</CST>';
								if($this->rowdata->cte_valfrete>0){
									$vBC = number_format($this->rowdata->cte_valfrete,2,'.','');
								}else{
									$vBC = '0';
								}
								$this->xml.='<vBC>'.$vBC.'</vBC>';

								if(substr($this->rowdata->cfo_codigo,0,1)==5){
									$pIcms=12;
								}else{
									$pIcms=$this->getAliqIcms($this->rowdata->dest_cad_uf);
								}

								$this->xml.='<pICMS>'.$pIcms.'</pICMS>';
								if($this->rowdata->cte_valoricms>0){
									$this->xml.='<vICMS>'. number_format($this->rowdata->cte_valoricms,2,'.','') .'</vICMS>';
								}else{
									$this->xml.='<vICMS>0</vICMS>';
								}

							$this->xml.='</ICMS00>';
						}
					$this->xml.='</ICMS>';
				}
				$vTottrib = ($this->rowdata->cte_valfrete*$pIcms);
				if($vTottrib>0){
					$vTottrib = number_format($vTottrib,2,'.','');
				}else{
					$vTottrib = '0';
				}
				$this->xml.='<vTotTrib>'.$vTottrib.'</vTotTrib>';
				
				if($this->rowdata->cte_tpcte == 1){
					/*
						complementar
					*/
					if(strlen($this->rowdata->cte_obs2)>0){
						$this->xml.='<infAdFisco>'.trim($this->rowdata->cte_obs2).'</infAdFisco>';
					}
				}else{
					/*
						normal
					*/
					if(strlen($this->rowdata->cte_obs)>0){
						$this->xml.='<infAdFisco>'.trim($this->rowdata->cte_obs).'</infAdFisco>';
					}
				}
				
				// <-- ICMS COM PARTILHA ENTRE ESTADOS
				
				$vBCUFFim = '0';
				if($this->rowdata->cte_valfrete>0){
					$vBCUFFim = number_format($this->rowdata->cte_valfrete,2,'.','');
				}
				
				$pFCPUFFim = $this->getPFCPUFFim($this->rowdata->dest_cad_uf);
				$vFCPUFFim = "0";
				
				if($pFCPUFFim>0){
					$vFCPUFFim = (((($vBCUFFim*$this->getAliqIcms($this->rowdata->dest_cad_uf))/100)*$pFCPUFFim)/100);

					if($vFCPUFFim>0){
						$vFCPUFFim=number_format($vFCPUFFim,2,'.','');
					}
				}

				$vICMSUFFim = (((($vBCUFFim*$this->getAliqIcms($this->rowdata->dest_cad_uf))/100)*40)/100);
				if($vICMSUFFim>0){
					$vICMSUFFim=number_format($vICMSUFFim,2,'.','');
				}
				
				$vICMSUfIni = (((($vBCUFFim*$this->getAliqIcms($this->rowdata->rem_cad_uf))/100)*40)/100);
				if($vICMSUfIni>0){
					$vICMSUfIni=number_format($vICMSUfIni,2,'.','');
				}
				
				
				$this->xml.='<ICMSUFFim>';
				
					$this->xml.='<vBCUFFim>'.$vBCUFFim.'</vBCUFFim>';
					$this->xml.='<pFCPUFFim>'.$pFCPUFFim.'</pFCPUFFim>';
					$this->xml.='<pICMSUFFim>'.$this->getAliqIcms($this->rowdata->dest_cad_uf).'</pICMSUFFim>';
					$this->xml.='<pICMSInter>'.$this->getAliqIcms($this->rowdata->dest_cad_uf).'</pICMSInter>';
					$this->xml.='<pICMSInterPart>40</pICMSInterPart>';
					$this->xml.='<vFCPUFFim>'.$vFCPUFFim.'</vFCPUFFim>';
					$this->xml.='<vICMSUFFim>'.$vICMSUFFim.'</vICMSUFFim>';
					$this->xml.='<vICMSUFIni>'.$vICMSUfIni.'</vICMSUFIni>';
				
				$this->xml.='</ICMSUFFim>';
				// ICMS COM PARTILHA ENTRE ESTADOS -->
			$this->xml.='</imp>';

			if($this->rowdata->cte_tpcte == 1){
				
				$this->xml.='<infCteComp>';
					
					$this->xml.='<chave>'.$this->rowdata->chave_pai.'</chave>';

				$this->xml.='</infCteComp>';

			}else{

				$this->xml.='<infCTeNorm>';
					
					$this->xml.='<infCarga>';
						
						$vCarga = '0';
						if($this->rowdata->cte_valcarga>0){
							$vCarga = number_format($this->rowdata->cte_valcarga,2,'.','');
						}

						$this->xml.='<vCarga>'.$vCarga.'</vCarga>';
						$this->xml.='<proPred>'.$this->rowdata->cte_prodpred.'</proPred>';
						$this->xml.='<infQ>';
							$this->xml.='<cUnid>'.str_pad($this->rowdata->cte_unimedida,2,'0',STR_PAD_LEFT).'</cUnid>';
							$this->xml.='<tpMed>'.$this->rowdata->cte_tpmedida.'</tpMed>';
							$this->xml.='<qCarga>'.number_format($this->rowdata->cte_totalpeso,4,'.','').'</qCarga>';
						$this->xml.='</infQ>';
					$this->xml.='</infCarga>';
					
					// infdoc => informacoes dos documentos da carga adicionada na versao 2.0
					if(!empty($infDoc)) $this->xml.='<infDoc>'.$infDoc.'</infDoc>';					

					// se houver seguradora
					$this->xml.='<seg>';

						$this->xml.='<respSeg>'.$this->rowdata->cte_respseg.'</respSeg>';

						if(!empty($this->rowdata->cte_xseg)) $this->xml.='<xSeg>'.$this->rowdata->cte_xseg.'</xSeg>';
						if(!empty($this->rowdata->cte_napol)) $this->xml.='<nApol>'.$this->rowdata->cte_napol.'</nApol>';
						if(!empty($this->rowdata->cte_naver)) $this->xml.='<nAver>'.$this->rowdata->cte_naver.'</nAver>';
						if(!empty($this->rowdata->cte_vcarga_aver) && $this->rowdata->cte_vcarga_aver > 0) $this->xml.='<vCarga>'.$this->rowdata->cte_vcarga_aver.'</vCarga>';

					$this->xml.='</seg>';

					$this->xml.='<infModal versaoModal="2.00">';
						
						$this->xml.='<rodo>';
						
							$this->xml.='<RNTRC>'.$this->company->emp_rntrc.'</RNTRC>';
							$this->xml.='<dPrev>'.$this->rowdata->cte_dtprev.'</dPrev>';
							$this->xml.='<lota>'.$this->rowdata->cte_lotacao.'</lota>';
							
							if($this->rowdata->cte_lotacao == 1){

								$this->xml.='<veic>';
									
									$this->xml.='<cInt>'.$this->rowdata->cte_automovel.'</cInt>';
									$this->xml.='<RENAVAM>'.$this->rowdata->vei_renavam.'</RENAVAM>';

									if($this->rowdata->vei_placa){
										$this->xml.='<placa>'.strtoupper(substr($this->rowdata->vei_placa, 0, 3)).substr($this->rowdata->vei_placa, 3, 4).'</placa>';
									}
									
									$this->xml.='<tara>'.$this->rowdata->vei_tara.'</tara>';
									$this->xml.='<capKG>'.$this->rowdata->vei_capkg.'</capKG>';
									$this->xml.='<capM3>'.$this->rowdata->vei_capm.'</capM3>';

									/* 0 - proprio; 1 - terceiro */
									if($this->rowdata->vei_proprietario == 0){
										$this->xml.='<tpProp>P</tpProp>';
									}else if($this->rowdata->vei_proprietario == 1){
										$this->xml.='<tpProp>T</tpProp>';
									}

									$this->xml.='<tpVeic>'.$this->rowdata->vei_tipo.'</tpVeic>';
									$this->xml.='<tpRod>'.$this->rowdata->vei_rodado.'</tpRod>';
									$this->xml.='<tpCar>'.$this->rowdata->vei_carroceria.'</tpCar>';
									$this->xml.='<UF>'.$this->rowdata->vei_uf.'</UF>';
									
									if($this->rowdata->vei_prop_nomeraz){
										
										$this->xml.='<prop>';
											/* 1 - fisica; 2- jutidica */
											if($this->rowdata->vei_prop_pessoa == 1){
												$this->xml.='<CPF>'.$this->rowdata->vei_prop_cnpjcpf.'</CPF>';
											}else if($this->rowdata->vei_prop_pessoa == 2){
												$this->xml.='<CNPJ>'.$this->rowdata->vei_prop_cnpjcpf.'</CNPJ>';
											}
											$this->xml.='<RNTRC>'.substr($this->rowdata->vei_prop_rntrc, 0, 8).'</RNTRC>';
											$this->xml.='<xNome>'.$this->rowdata->vei_prop_nomeraz.'</xNome>';
											
											/* 1 - fisica; 2- jutidica */
											if($this->rowdata->vei_prop_pessoa == 1){
												$this->xml.='<IE></IE>';
											}else if($this->rowdata->vei_prop_pessoa == 2){
												$this->xml.='<IE>'.$this->rowdata->vei_prop_inscrg.'</IE>';
											}

											$this->xml.='<UF>'.$this->rowdata->vei_prop_uf.'</UF>';
											$this->xml.='<tpProp>'.$this->rowdata->vei_prop_tipo.'</tpProp>';

										$this->xml.='</prop>';
									}


								$this->xml.='</veic>';
								
								$this->xml.='<moto>';
								
									$this->xml.='<xNome>'.$this->rowdata->moto_nome.'</xNome>';

									$this->xml.='<CPF>'.$this->rowdata->moto_cnpjcpf.'</CPF>';

								$this->xml.='</moto>';
							}

						$this->xml.='</rodo>';

					$this->xml.='</infModal>';

				$this->xml.='</infCTeNorm>';
			}

			$this->xml.='</infCte>';
			$this->xml.='</CTe>';
			return $this->xml;
		}
		
		public function getCompany(){
			return $this->company;
		}
		
		public function getRowdata(){
			return $this->rowdata;
		}
		
	}
	
	$code = base64_decode(substr($_REQUEST["p"],0,1).substr($_REQUEST["p"],2,strlen($_REQUEST["p"])));

	$datapacket = new Datapacket();
	
	$CTe = new CTe($_REQUEST['cte_codigo'], $code);
	
	$company = $CTe->getCompany();
	$rowdata = $CTe->getRowdata();
	
	include_once "../libs/CTeNFePHP.class.php";

	$acao  = (isset($_REQUEST['acao']))  ? $_REQUEST['acao']  : "";
	$param = (isset($_REQUEST['param'])) ? $_REQUEST['param'] : "";
	
	$CTeTools = new CTeNFePHP();

	if($acao=='transmitir'){

		if(is_dir($CTe->dirTemporaria.$CTe->anomes)){	

			$xml = $CTeTools->signXML($CTe->getXml(),'infCte');
			$variavel='';

			if( !$CTeTools->validXML($xml, '../schemes/PL_CTe_200/cteModalRodoviario_v2.00.xsd', $aErro) ){
				
				//XML inválido - erro
				$erro = 'Erro(s) na estrutura XML: <br>';
				foreach ($aErro as $er) {
					$erro.= $er .'<br>';
				}
				exit($erro);
			}
			
			$nomeArquivo = $CTe->dirTemporaria.$CTe->anomes.'/'.$CTe->getKey().'-cte.xml';
			$arquivoXML = fopen($nomeArquivo,'w+');
			fwrite($arquivoXML,$xml);
			fclose($arquivoXML);
			chmod($nomeArquivo, 0777);

			if($arquivoXML){

				$arrXML = Array();
				array_push($arrXML,$xml);

				$retorno = $CTeTools->sendLot($arrXML,$rowdata->cte_nct,'2');

				$dhRecbto = "";
				if($retorno['dhRecbto']!=""){
					$dhRecbto = str_replace(array("/","-"," ",":"), array("-","-","-","-"), $retorno['dhRecbto']);
					$dhRecbto = explode("-", $dhRecbto);
					$dhRecbto = $dhRecbto[2]."-".$dhRecbto[1]."-".$dhRecbto[0]." ".$dhRecbto[3].":".$dhRecbto[4].":00";
				}

				if($retorno){
					
					sleep(5);

					$getProt = $CTeTools->getProtocol($retorno['nRec'], "", $CTe->getCompany()->{'emp_ambcte'});

					if($retorno['bStat']==false) $retorno['bStat'] = 0;

					$nfefile = $nomeArquivo;
					$protfile = $CTe->dirTemporaria.$getProt['aProt'][0]['chCTe'].'-prot.xml';

					$addprot=0;
					
					if ($xml = $CTeTools->addProt($nfefile, $protfile)){
						$addprot=1;
						sleep(2);
						file_put_contents($nomeArquivo, $xml);
					}

					if(!$getProt['aProt'][0]['cStat']){
						if(!$retorno['cStat']){
							$getProt['aProt'][0]['cStat']=0;
						}else{
							$getProt['aProt'][0]['cStat']=$retorno['cStat'];
						}
					}

					$cte_status = 0;
					if($getProt['aProt'][0]['cStat'] == '100'){
						$cte_status = 2;
					}else if($getProt['aProt'][0]['cStat'] == '103'){
						$cte_status = 1;
					}else if($getProt['aProt'][0]['cStat'] == '999'){
						$cte_status = 1;
					}else if($getProt['aProt'][0]['cStat'] == '9998'){
						$cte_status = 1;
					}

					$keyatt = "cte_key";
					$keyatttipo = 'other';
					if(isset($getProt['aProt'][0]['chCTe'])){
						$keyatt = $getProt['aProt'][0]['chCTe'];
						$keyatttipo = 'string';
					}

					$nprotatttipo = 'other';
					$nprotatt = "cte_nprot";
					if(isset($getProt['aProt'][0]['nProt'])){
						$nprotatt = $getProt['aProt'][0]['nProt'];
						$nprotatttipo = 'string';
					}
					
					$datapacket->setHost($CTe->TParams->getHost($CTe->TParams->getDbSge()));
					$filtrolog = '{"cod":"700103","params":[
						{"name":"log_tipo","value":"3","type":"integer"},
						{"name":"log_nro","value":"'.$rowdata->cte_codigo.'","type":"string"},
						{"name":"log_serie","value":"1","type":"string"},';
					$filtrolog.= ( isset($_POST["usu_login"]) && $_POST["usu_login"]!="" ) ? '{"name":"log_usu_login","value":"'.$_POST["usu_login"].'","type":"string"},' : '{"name":"log_usu_login","value":"NULL","type":"other"},';
					$filtrolog.= '{"name":"log_acao_cod","value":"3","type":"integer"},
						{"name":"log_acao_descr","value":"transmissão","type":"string"},
						{"name":"log_data","value":"","type":"string"},
						{"name":"log_protocolo","value":"'.$nprotatt.'","type":"string"},
						{"name":"log_ret","value":"NULL","type":"other"},';
					$filtrolog.= ( $retorno["xMotivo"]!="Lote recebido com sucesso" ) ? '{"name":"log_outro","value":"'.base64_encode($retorno['xMotivo']).'","type":"string"}' : '{"name":"log_outro","value":"'.base64_encode($getProt['aProt'][0]["xMotivo"]).'","type":"string"}';
					$filtrolog.= ']}';
					$datapacket->add($filtrolog);
					$datapacket->open();
					$datapacket->clear();
					$filtroUpdt = '{"cod":"500892","params":[
						{"name":"cte_codigo","value":"'.$rowdata->cte_codigo.'","type":"string"},
						{"name":"cte_bstat","value":"'.$retorno['bStat'].'","type":"integer"},
						{"name":"cte_cstat","value":"'.$getProt['aProt'][0]['cStat'].'","type":"integer"},
						{"name":"cte_xmotivo","value":"'.base64_encode($retorno['xMotivo']).'","type":"string"},
						{"name":"cte_dhrecbto","value":"'.$dhRecbto.'","type":"string"},
						{"name":"cte_nrec","value":"'.$retorno['nRec'].'","type":"string"},
						{"name":"cte_key","value":"'.$keyatt.'","type":"'.$keyatttipo.'"},
						{"name":"cte_nprot","value":"'.$nprotatt.'","type":"'.$nprotatttipo.'"},
						{"name":"cte_status","value":"'.$cte_status.'","type":"integer"}
					]}';
					$datapacket->add($filtroUpdt);
					$ret = $datapacket->open();
					$datapacket->clear();

					$getProt['aProt'][0]['dvChCTe']=$CTe->getKeyDv($CTe->getKey());
					
					// retorno
					echo '{"CTe":'.json_encode($retorno).', "status":'.json_encode($getProt).', "debug":{"nfefile":"'.$nfefile.'","protfile":"'.$protfile.'","filtro":'.$filtroUpdt.'},"addProt":"'.$addprot.'"}';

					if($getProt['aProt'][0]['cStat'] == '100'){
						copy($CTe->dirTemporaria.$CTe->anomes.'/'.$getProt['aProt'][0]['chCTe'].'-cte.xml', $CTe->dirAutorizada.$CTe->anomes.'/'.$getProt['aProt'][0]['chCTe'].'-cte.xml');
						chmod($CTe->dirAutorizada.$CTe->anomes.'/'.$getProt['aProt'][0]['chCTe'].'-cte.xml', 0777);
						unlink($CTe->dirTemporaria.$CTe->anomes.'/'.$getProt['aProt'][0]['chCTe'].'-cte.xml');
					}else if($getProt['aProt'][0]['cStat'] == '110' || $getProt['aProt'][0]['cStat'] == '205'){
						copy($CTe->dirTemporaria.$CTe->anomes.'/'.$getProt['aProt'][0]['chCTe'].'-cte.xml', $CTe->dirDenegada.$CTe->anomes.'/'.$getProt['aProt'][0]['chCTe'].'-cte.xml');
						chmod($CTe->dirDenegada.$CTe->anomes.'/'.$getProt['aProt'][0]['chCTe'].'-cte.xml', 0777);
						unlink($CTe->dirTemporaria.$CTe->anomes.'/'.$getProt['aProt'][0]['chCTe'].'-cte.xml');
					}else if($getProt['aProt'][0]['cStat'] == '101' || $getProt['aProt'][0]['cStat'] == '218'){
						copy($CTe->dirTemporaria.$CTe->anomes.'/'.$getProt['aProt'][0]['chCTe'].'-cte.xml', $CTe->dirCancelada.$CTe->anomes.'/'.$getProt['aProt'][0]['chCTe'].'-cte.xml');
						chmod($CTe->dirCancelada.$CTe->anomes.'/'.$getProt['aProt'][0]['chCTe'].'-cte.xml', 0777);
						unlink($CTe->dirTemporaria.$CTe->anomes.'/'.$getProt['aProt'][0]['chCTe'].'-cte.xml');
					}

				}else{

					exit('Ocorreu um erro ao transmitir, possivelmente o certificado pode estar vencido ou nao obteve uma resposta da receita ao enviar o lote');
				}
			}
		}

	}else if($acao=='atualizar'){
		
		if( isset($_POST["param"]) && isset($_POST["cte_codigo"]) ){
			$retorno = $CTeTools->getProtocol("", $_POST["param"], $CTe->getCompany()->emp_ambcte);
			$cte_codigo = $_POST["cte_codigo"];
			$nrec = $_POST["nrec"];
			$cte_status = ( isset($retorno['aProt'][0]['cStat']) && $retorno['aProt'][0]['cStat']==100 ) ? 2 : 0;
		}else{
			$params = json_decode(base64_decode($param));
			$retorno = $CTeTools->getProtocol($params->nRec, "", $CTe->getCompany()->emp_ambcte);
			$cte_codigo = $params->cte_codigo;
			$nrec = $params->nRec;
			$cte_status = ( isset($retorno['aProt'][0]['cStat']) && $retorno['aProt'][0]['cStat']==100 ) ? 2 : 0;
		}
		
		/*
		$dhRecbto = str_replace(array(":","/"),array("-","-"),$retorno['aProt'][0]['dhRecbto']);
		$arrDhRecbto = explode("-",$dhRecbto);
		$dhRecbto = substr($arrDhRecbto[2],0,-3)."-".$arrDhRecbto[1]."-".$arrDhRecbto[0]." ".substr($arrDhRecbto[2],-2)."-".$arrDhRecbto[3];
		*/
		$dhRecbto="";
		
		//{"name":"cte_bstat","value":"'.$retorno['bStat'].'","type":"integer"},
		//{"name":"cte_nrec","value":"'.$retorno['nRec'].'","type":"string"},
		$filtroUpdt = '{"cod":"500892","params":[
			{"name":"cte_codigo","value":"'.$cte_codigo.'","type":"string"},
			{"name":"cte_bstat","value":"'.$retorno['bStat'].'","type":"integer"},
			{"name":"cte_cstat","value":"'.$retorno['aProt'][0]['cStat'].'","type":"integer"},
			{"name":"cte_xmotivo","value":"'.base64_encode($retorno['aProt'][0]['xMotivo']).'","type":"string"},
			{"name":"cte_dhrecbto","value":"'.$dhRecbto.'","type":"string"},
			{"name":"cte_nrec","value":"'.$nrec.'","type":"string"},
			{"name":"cte_key","value":"'.$retorno['aProt'][0]['chCTe'].'","type":"string"},
			{"name":"cte_status","value":"'.$cte_status.'","type":"integer"}';

			if(isset($retorno['aProt'][0]['nProt'])){
				$filtroUpdt .= ',{"name":"cte_nprot","value":"'.$retorno['aProt'][0]['nProt'].'","type":"string"}';
			}else{
				$filtroUpdt .= ',{"name":"cte_nprot","value":"","type":"null"}';
			}
		$filtroUpdt.=']}';
		$datapacket->setHost($CTe->TParams->getHost($CTe->TParams->getDbSge()));
		$datapacket->add($filtroUpdt);
		$datapacket->open();
		$datapacket->clear();

		echo '{"CTe":{"nRec":""},"status":'.json_encode($retorno).'}';
		
	}else if($acao=='status'){

		print_r($CTeTools->statusServico('PR', '1', '2'));

	}else if($acao=='dacte'){

		require_once('../libs/DacteNFePHP.class.php');

		$arq = $CTe->dirAutorizada.$CTe->anomes."/".$CTe->getKey().'-cte.xml';
		if(is_file($arq)){
			$docxml = file_get_contents($arq);
			$dacte 	= $dacte = new DacteNFePHP($docxml, "P", "A4", "", 'I');
			$id 	= $dacte->montaDACTE('P','A4','','');
			$teste 	= $dacte->printDACTE($CTe->dirAutorizada.$CTe->anomes."/".$id.'.pdf','F');
			$dir 	= "/uploads/".$CTe->getCompany()->emp_codigo."/cte/".$CTe->tpAmb."/autorizadas/".$CTe->anomes."/".$CTe->getKey().'.pdf';;
			echo '{"status":{"bStat":false, "cStat":"", "xMotivo":"Print", "aProt":[{"tpAmb":"","verAplic":"","chCTe":"'.$id.'","dhRecbto":"","nProt":"","digVal":"","cStat":"99999","xMotivo":"","dvChCTe":""}], "aCanc":"", "print":true, "dir":"'.$dir.'"}}';
		}else{
			echo '{"status":{"bStat":false,"cStat":"","xMotivo":"O arquivo '.$arq.' não existe.","aProt":[{"tpAmb":"","verAplic":"","chCTe":"","dhRecbto":"","nProt":"","digVal":"","cStat":"99999","dvChCTe":""}],"aCanc":"","print":true}}';
		}

	}else if($acao=='cancelar'){

		$params  = json_decode(base64_decode($param));
	
		$retorno = $CTeTools->cancelEvent($params->chCTe, $params->nProt, $params->justificativa, '2');
		$xml = simplexml_load_string($retorno);
		if($xml){
			$cte_codigo = $xml->eventoCTe->infEvento->chCTe;
			$bstat = 1;
			$cstat = $xml->retEventoCTe->infEvento->cStat;
			$xMotivo = $xml->retEventoCTe->infEvento->xMotivo;
			$dhRegEvento = str_replace("T", " ", $xml->retEventoCTe->infEvento->dhRegEvento);
			$nprot = $xml->retEventoCTe->infEvento->nProt;

			if($cstat != null && $cstat != ""){
				
				if($cstat == "101" || $cstat == "135"){
					
					$filtrolog = '{"cod":"700103","params":[
						{"name":"log_tipo","value":"3","type":"integer"},
						{"name":"log_nro","value":"'.$rowdata->cte_codigo.'","type":"string"},
						{"name":"log_serie","value":"1","type":"string"},';
					$filtrolog.= ( isset($params->usu_login) && $params->usu_login!="" ) ? '{"name":"log_usu_login","value":"'.$params->usu_login.'","type":"string"},' : '{"name":"log_usu_login","value":"NULL","type":"other"},';
					$filtrolog.= '{"name":"log_acao_cod","value":"5","type":"integer"},
						{"name":"log_acao_descr","value":"cancelamento","type":"string"},
						{"name":"log_data","value":"","type":"string"},
						{"name":"log_protocolo","value":"'.$nprot.'","type":"string"},
						{"name":"log_ret","value":"NULL","type":"other"},
						{"name":"log_outro","value":"'.base64_encode($params->justificativa).'","type":"string"}
					]}';
					$filtro = '{"cod":"500893","params":[
						{"name":"cte_codigo","value":"'.$params->cte_codigo.'","type":"string"},
						{"name":"cte_bstat","value":"'.$bstat.'","type":"integer"},
						{"name":"cte_cstat","value":"'.$cstat.'","type":"integer"},
						{"name":"cte_xmotivo","value":"'.base64_encode($xMotivo).'","type":"string"},
						{"name":"cte_dhrecbto","value":"'.$dhRegEvento.'","type":"string"},
						{"name":"cte_nprot","value":"'.$nprot.'","type":"string"},
						{"name":"cte_status","value":"3","type":"string"}
					]}';
					$datapacket->setHost($CTe->TParams->getHost($CTe->TParams->getDbSge()));
					$datapacket->add($filtro);
					$datapacket->add($filtrolog);
					$datapacket->open();
					$datapacket->clear();
				}
				
				echo '{"status":{"aProt":[{"bStat":"'.$bstat.'","cStat":"'.$cstat.'","xMotivo":"'.base64_encode($xMotivo).'","dhRecbto":"'.$dhRegEvento.'","nProt":"'.$nprot.'"}]},"erro":false}';

			}else{

				echo '{"CTe":{"nRec":""},"status":'.json_encode($retorno).',"erro":true}';
			}
		}else{

			echo '{"CTe":{"nRec":""},"status":'.json_encode($retorno).',"erro":true}';
		}
	
	}else if($acao=='imprimir'){
			
		$xml = $CTeTools->signXML($CTe->getXml(),'infCte');
		$validacao = $CTeTools->validXML($CTe->getXml(),'../schemes/PL_CTe_200/cteModalRodoviario_v2.00.xsd',$erro);
		$retorno = false;
		
		if(is_file($CTe->dirTemporaria.'/'.$CTe->getKey().'-recprot.xml')){

			require_once('../libs/DacteNFePHP.class.php');
			$arq = $CTe->dirTemporaria.'/'.$CTe->getKey().'-recprot.xml';
			if(is_file($arq)){
				$docxml = file_get_contents($arq);
				$dacte 	= $dacte = new DacteNFePHP($docxml, "P", "A4", "", 'I');
				$id 	= $dacte->montaDACTE('P','A4','','');
				$teste 	= $dacte->printDACTE($CTe->dirAutorizada.$CTe->anomes.'/'.$id.'.pdf','F');
				$dir 	= "/uploads/".$CTe->getCompany()->emp_codigo."/cte/".$CTe->tpAmb."/autorizadas/".$CTe->anomes."/".$CTe->getKey().'.pdf';
				$retorno = true;
			}

		}if(is_file($CTe->dirAutorizada.$CTe->anomes.'/'.$CTe->getKey().'-cte.xml')){

			require_once('../libs/DacteNFePHP.class.php');
			$arq = $CTe->dirAutorizada.$CTe->anomes.'/'.$CTe->getKey().'-cte.xml';
			if(is_file($arq)){
				$docxml = file_get_contents($arq);
				$dacte 	= $dacte = new DacteNFePHP($docxml, "P", "A4", "", 'I');
				$id 	= $dacte->montaDACTE('P','A4','','');
				$teste 	= $dacte->printDACTE($CTe->dirAutorizada.$CTe->anomes.'/'.$id.'.pdf','F');
				$dir 	= "/uploads/".$CTe->getCompany()->emp_codigo."/cte/".$CTe->tpAmb."/autorizadas/".$CTe->anomes."/".$CTe->getKey().'.pdf';
				$retorno = true;
			}

		}else{

			$nomeArquivo = $CTe->dirTemporaria.$CTe->anomes.'/'.$CTe->getKey().'-cte.xml';
			$arquivoXML = fopen($nomeArquivo,'w+');
			fwrite($arquivoXML,$xml);
			fclose($arquivoXML);
			chmod($nomeArquivo, 0777);

			if($arquivoXML){
				require_once('../libs/DacteNFePHP.class.php');
				$arq = $CTe->dirTemporaria.$CTe->anomes.'/'.$CTe->getKey().'-cte.xml';
				if(is_file($arq)){
					$docxml = file_get_contents($arq);
					$dacte 	= $dacte = new DacteNFePHP($docxml, "P", "A4", "", 'I');
					$id 	= $dacte->montaDACTE('P','A4','','');
					$teste 	= $dacte->printDACTE($CTe->dirTemporaria.$CTe->anomes.'/'.$id.'.pdf','F');
					$dir 	= "/uploads/".$CTe->getCompany()->emp_codigo."/cte/".$CTe->tpAmb."/temporarias/".$CTe->anomes."/".$CTe->getKey().'.pdf';
					$retorno = true;
				}
			}
		}
		
		$filtrolog = '{"cod":"700103","params":[
			{"name":"log_tipo","value":"3","type":"integer"},
			{"name":"log_nro","value":"'.$rowdata->cte_codigo.'","type":"string"},
			{"name":"log_serie","value":"1","type":"string"},';
		$filtrolog.= ( isset($_REQUEST["usu_login"]) && $_REQUEST["usu_login"]!="" ) ? '{"name":"log_usu_login","value":"'.$_REQUEST["usu_login"].'","type":"string"},' : '{"name":"log_usu_login","value":"NULL","type":"other"},';
		$filtrolog.= '{"name":"log_acao_cod","value":"4","type":"integer"},
			{"name":"log_acao_descr","value":"impressão","type":"string"},
			{"name":"log_data","value":"","type":"string"},
			{"name":"log_protocolo","value":"NULL","type":"other"},
			{"name":"log_ret","value":"NULL","type":"other"},
			{"name":"log_outro","value":"'.base64_encode("Impressão do DACTE").'","type":"string"}
		]}';
		$datapacket->setHost($CTe->TParams->getHost($CTe->TParams->getDbSge()));
		$datapacket->add($filtrolog);
		$datapacket->open();
		$datapacket->clear();

		if($retorno){
			echo '{"status":{ "bStat":false, "cStat":"", "xMotivo":"OK", "aProt":[{ "tpAmb":"", "verAplic":"", "chCTe":"'.$id.'", "dhRecbto":"", "nProt":"", "digVal":"", "cStat":"9998", "xMotivo":"", "dvChCTe":""}], "aCanc":"", "print":true, "dir":"'.$dir.'"}}';
		}else{
			echo '{"status":{"bStat":false,"cStat":"","xMotivo":"O arquivo '.$arq.' não existe.","aProt":[{"tpAmb":"","verAplic":"","chCTe":"","dhRecbto":"","nProt":"","digVal":"","cStat":"99999","dvChCTe":""}],"aCanc":"","print":false}}';
		}

	}else if($acao=='email'){

		//classe p/ envio
		include_once("../../../class/PHPMailer_v5.1/class.phpmailer.php");
		
		//dados de configuração de envio
		$data = explode("-", $CTe->getRowdata()->cte_data);
		$ano = substr($data[0],2,2);
		$mes = ($data[1]<10)?"0".$data[1]:$data[1];
		$arqpdf = $CTe->dirAutorizada.$CTe->anomes.'/'.$CTe->getRowdata()->cte_key.".pdf";
		$arqxml = $CTe->dirAutorizada.$CTe->anomes.'/'.$CTe->getRowdata()->cte_key."-cte.xml";
		$to = base64_decode($_REQUEST["email"]);
		$assunto = utf8_decode("Envio de CT-e N: ".$CTe->getRowdata()->cte_nct);
		
		if(number_format($CTe->getRowdata()->cte_total, 2, ',', '')){
			$cte_total = number_format($CTe->getRowdata()->cte_total, 2, '.', '');
		}else{
			$cte_total = str_replace($CTe->getRowdata()->cte_total, '.', ',');
		}

		//mensagem (corpo do e-mail)
		$msg = "<p><b>Prezado Sr(a) ".$CTe->getRowdata()->dest_cad_nomeraz.",</b></p>";
		$msg .= "<p>Você está recebendo o Conhecimento de Transporte Eletrônico ".$CTe->getRowdata()->cte_nct.", de ";
		$msg .= $CTe->getCompany()->emp_razao.", no valor de R$ ".$cte_total.". Junto com o arquivo xml, você receberá também um DACTE ";
		$msg .= "(Documento Auxiliar de Conhecimento  Eletrônica).</p>";
		$msg .= "<p>Podemos conceituar o Conhecimento de Transporte Eletrônico como sendo um documento de existência apenas digital, ";
		$msg .= "emitido e armazenado eletronicamente, com o intuito de documentar, para fins fiscais, ";
		$msg .= "uma prestação de serviço de transporte de cargas realizada por qualquer modal (Rodoviário, Aéreo, Ferroviário, Aquaviário e Dutoviário). ";
		$msg .= "Sua validade jurídica é garantida pela assinatura digital do emitente (garantia de autoria e de integridade) e pela recepção e autorização de uso, pelo Fisco</p>";
		$msg = utf8_decode($msg);

		$mail = new PHPMailer();
		$mail->Charset = 'UTF-8';
	    $assunto = utf8_decode("Envio de CT-e N: ".$CTe->getRowdata()->cte_nct);
	    $mail->IsHTML(true);
	    $mail->SetLanguage("br");
	    $mail->isSMTP();
	    $mail->Port = 587;
	    $mail->Host = strtolower($CTe->getCompany()->emp_hostsmtp);
	    $mail->SMTPAuth = true;
	    $mail->Username = strtolower($CTe->getCompany()->emp_emailremetente);
	    $mail->Password = $CTe->getCompany()->emp_pwdsmtp;
	    $mail->From = strtolower($CTe->getCompany()->emp_emailremetente);    
	    $mail->Subject = $assunto;
	    $mail->Body = $msg;
	    $mail->AddAddress($to);
	    $mail->AddAttachment($arqxml);
	    $mail->AddAttachment($arqpdf);

		if($mail->send()){
			exit('{"status":"Sucesso","resposta":"E-mail enviado com sucesso!"}');
		}else{
			exit('{"status":"Erro","resposta":"Erro ao tentar enviar e-mail, tente novamente mais tarde."}');
		}

	}else if($acao=='baixarXml'){

		if($CTe->getRowdata()->cte_cstat == '100'){
			$arqxml = $CTe->dirAutorizada.$CTe->anomes.'/'.$CTe->getRowdata()->cte_key."-cte.xml";
			$arqnome = $CTe->getRowdata()->cte_key."-cte.xml";
		}else if($CTe->getRowdata()->cte_cstat == '101' || $CTe->getRowdata()->cte_cstat == '218'){
			$arqxml = $CTe->dirCancelada.$CTe->anomes.'/'.$CTe->getRowdata()->cte_key."-cte.xml";
			$arqnome = $CTe->getRowdata()->cte_key."-cte.xml";
		}else{
		
			echo "O arquivo magnético não foi encontrado!";
		
			?>
				<script type="text/javascript">
				    setTimeout(function(){
				    	self.close();
				    },3000);
				</script>
			<?php
		
			exit();
		}

		header('Content-Description: File Transfer');
		header('Content-Type: application/octet-stream');
		header('Content-Transfer-Encoding: binary');
		header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
		header('Pragma: public');
		header('Expires: 0');
		
		// $zipDir = "/var/www/desktop/tmp/";
		// if(!is_dir($zipDir)){
		// 	mkdir($zipDir, 0777, true);
		// }

		// $zip_name = 'CTe-'.$CTe->getRowdata()->cte_key.'.zip';
		// if(is_file($zipDir.$zip_name)){
		// 	@unlink($zipDir.$zip_name);
		// }

		// $zip = "";
		// $zip = new ZipArchive();
		// $zip->open($zipDir.$zip_name, ZipArchive::CREATE);
		// $zip->addFile($arqxml, $CTe->getRowdata()->cte_key.".xml");
		// $zip->close();

		// sleep(1);
		
		// header('Content-Disposition: attachment; filename="'.$zip_name.'"');
		// header('Content-Length: '.filesize($zipDir.$zip_name));
		
		// while (ob_get_level()) {
		// 	ob_end_clean();
		// }
		// @readfile($zipDir.$zip_name);
		
		header('Content-Disposition: attachment; filename="'.$arqnome.'"');
		header('Content-Length: '.filesize($arqxml));
		
		while (ob_get_level()) {
			ob_end_clean();
		}
		@readfile($arqxml);
		exit();
		
	}else if($acao=='cartaCorrecao'){
		
		if(!isset($_REQUEST['dados'])||empty($_REQUEST['dados'])){
			exit("Os dados da carta de correção não foram passados!");
		}

		$dados = json_decode(base64_decode($_REQUEST['dados']));

		if(isset($_REQUEST['modo']) && $_REQUEST['modo'] == 'transmitir'){

			$cce_info = new stdClass();
			$cce_info->emp_cpfcnpj = $CTe->getCompany()->{'emp_cpfcnpj'};
			$cce_info->nSeqEvento = $dados->{'cco_numero'};
			$cce_info->inf_correcao = json_decode(base64_decode($dados->{'cco_info'}));

			$retorno = $CTeTools->cceCTeEvent($CTe->getRowdata()->{'cte_key'}, $CTe->getCompany()->{'emp_ambcte'}, $cce_info, 2);

			if(gettype($retorno) == "object"){
				
				if($retorno->{'cStat'} == 135){
					
					$filtrolog = '{"cod":"700103","params":[
						{"name":"log_tipo","value":"3","type":"integer"},
						{"name":"log_nro","value":"'.$dados->{'cte_codigo'}.'","type":"string"},
						{"name":"log_serie","value":"1","type":"string"},';
					$filtrolog.= ( isset($dados->{'usu_login'}) && $dados->{'usu_login'}!="" ) ? '{"name":"log_usu_login","value":"'.$dados->{'usu_login'}.'","type":"string"},' : '{"name":"log_usu_login","value":"NULL","type":"other"},';
					$filtrolog.= '{"name":"log_acao_cod","value":"6","type":"integer"},
						{"name":"log_acao_descr","value":"correção","type":"string"},
						{"name":"log_data","value":"","type":"string"},
						{"name":"log_protocolo","value":"'.$retorno->{'nProt'}.'","type":"string"},
						{"name":"log_ret","value":"NULL","type":"other"},
						{"name":"log_outro","value":"'.base64_encode($cce_info->inf_correcao).'","type":"string"}
					]}';
					$filtro = '{"cod":"500895","params":[
						{"name":"cco_status","value":"2","type":"integer"},
						{"name":"cco_cstat","value":"'.$retorno->{'cStat'}.'","type":"integer"},
						{"name":"cco_xmotivo","value":"'.base64_encode($retorno->{'xMotivo'}).'","type":"string"},
						{"name":"cco_nprot","value":"'.$retorno->{'nProt'}.'","type":"string"},
						{"name":"cco_dhregevent","value":"'.$retorno->{'cStat'}.'","type":"integer"},
						{"name":"cte_codigo","value":"'.$dados->{'cte_codigo'}.'","type":"string"},
						{"name":"cco_numero","value":"'.$dados->{'cco_numero'}.'","type":"integer"}
					]}';
					$datapacket->setHost($CTe->TParams->getHost($CTe->TParams->getDbSge()));
					$datapacket->add($filtro);
					$datapacket->add($filtrolog);
					$datapacket->open(true);
					$datapacket->clear();

				}else{
					$filtrolog = '{"cod":"700103","params":[
						{"name":"log_tipo","value":"3","type":"integer"},
						{"name":"log_nro","value":"'.$dados->{'cte_codigo'}.'","type":"string"},
						{"name":"log_serie","value":"1","type":"string"},';
					$filtrolog.= ( isset($dados->{'usu_login'}) && $dados->{'usu_login'}!="" ) ? '{"name":"log_usu_login","value":"'.$dados->{'usu_login'}.'","type":"string"},' : '{"name":"log_usu_login","value":"NULL","type":"other"},';
					$filtrolog.= '{"name":"log_acao_cod","value":"6","type":"integer"},
						{"name":"log_acao_descr","value":"correção","type":"string"},
						{"name":"log_data","value":"","type":"string"},
						{"name":"log_protocolo","value":"NULL","type":"other"},
						{"name":"log_ret","value":"NULL","type":"other"},
						{"name":"log_outro","value":"'.base64_encode($retorno->{'xMotivo'}).'","type":"string"}
					]}';
					$filtro = '{"cod":"500895","params":[
						{"name":"cco_status","value":"cco_status","type":"other"},
						{"name":"cco_cstat","value":"'.$retorno->{'cStat'}.'","type":"integer"},
						{"name":"cco_xmotivo","value":"'.base64_encode($retorno->{'xMotivo'}).'","type":"string"},
						{"name":"cco_nprot","value":"cco_nprot","type":"other"},
						{"name":"cco_dhregevent","value":"'.$retorno->{'cStat'}.'","type":"integer"},
						{"name":"cte_codigo","value":"'.$dados->{'cte_codigo'}.'","type":"string"},
						{"name":"cco_numero","value":"'.$dados->{'cco_numero'}.'","type":"integer"}
					]}';
					$datapacket->setHost($CTe->TParams->getHost($CTe->TParams->getDbSge()));
					$datapacket->add($filtro);
					$datapacket->add($filtrolog);
					$datapacket->open(true);
					$datapacket->clear();
				}

				print_r($retorno->{'xMotivo'});

			}else{

				print_r($retorno);
				$filtrolog = '{"cod":"700103","params":[
					{"name":"log_tipo","value":"3","type":"integer"},
					{"name":"log_nro","value":"'.$dados->{'cte_codigo'}.'","type":"string"},
					{"name":"log_serie","value":"1","type":"string"},';
				$filtrolog.= ( isset($dados->{'usu_login'}) && $dados->{'usu_login'}!="" ) ? '{"name":"log_usu_login","value":"'.$dados->{'usu_login'}.'","type":"string"},' : '{"name":"log_usu_login","value":"NULL","type":"other"},';
				$filtrolog.= '{"name":"log_acao_cod","value":"6","type":"integer"},
					{"name":"log_acao_descr","value":"correção","type":"string"},
					{"name":"log_data","value":"","type":"string"},
					{"name":"log_protocolo","value":"NULL","type":"other"},
					{"name":"log_ret","value":"NULL","type":"other"},
					{"name":"log_outro","value":"'.base64_encode($retorno).'","type":"string"}
				]}';
				$filtro = '{"cod":"500895","params":[
					{"name":"cco_status","value":"1","type":"other"},
					{"name":"cco_cstat","value":"cco_cstat","type":"other"},
					{"name":"cco_xmotivo","value":"'.base64_encode($retorno).'","type":"string"},
					{"name":"cco_nprot","value":"cco_nprot","type":"other"},
					{"name":"cco_dhregevent","value":"cco_dhregevent","type":"integer"},
					{"name":"cte_codigo","value":"'.$dados->{'cte_codigo'}.'","type":"string"},
					{"name":"cco_numero","value":"'.$dados->{'cco_numero'}.'","type":"integer"}
				]}';
				$datapacket->setHost($CTe->TParams->getHost($CTe->TParams->getDbSge()));
				$datapacket->add($filtro);
				$datapacket->add($filtrolog);
				$datapacket->open(true);
				$datapacket->clear();
			}

		}else if(isset($_REQUEST['modo']) && $_REQUEST['modo'] == "email"){

			//classe p/ envio
			include_once("../../../class/PHPMailer_v5.1/class.phpmailer.php");
			
			$arqxml = $CTe->dirCartaCorrecao . $CTe->{'anomes'} . '/' . $CTe->getRowdata()->{'cte_key'} . "-" . $dados->{'cco_numero'} . "-procCCe.xml";

			$mail = new PHPMailer();
		    $mail->Port = 587;
		    $mail->SMTPAuth = true;
			$mail->Charset = 'UTF-8';
		    $mail->IsHTML(true);
		    $mail->SetLanguage("br");
		    $mail->isSMTP();
		    $mail->Host = strtolower($CTe->getCompany()->emp_hostsmtp);
		    $mail->Username = strtolower($CTe->getCompany()->emp_emailremetente);
		    $mail->Password = $CTe->getCompany()->emp_pwdsmtp;
		    $mail->From = strtolower($CTe->getCompany()->emp_emailremetente);    
		    $mail->Subject = utf8_decode("Carta de correção CT-e " . $CTe->getRowdata()->{'cte_nct'});
		    $mail->Body = utf8_decode("<p>Segue em anexo o arquivo XML da carta de correção referente ao CT-e Nº " . $CTe->getRowdata()->{'cte_nct'} . "</p>");
		    $mail->AddAddress($dados->{"email"});
		    $mail->AddAttachment($arqxml);

			if($mail->send()){
				exit('ok');
			}else{
				exit('erro');
			}

		}else if(isset($_REQUEST['modo']) && $_REQUEST['modo'] == "baixarXml"){
			
			$arqxml = $CTe->dirCartaCorrecao . $CTe->{'anomes'} . '/' . $CTe->getRowdata()->{'cte_key'} . "-" . $dados->{'cco_numero'} . "-procCCe.xml";
			$arqNome = $CTe->getRowdata()->{'cte_key'} . "-" . $dados->{'cco_numero'} . "-procCCe.xml";

			header('Content-Disposition: attachment; filename="'.$arqNome.'"');
			header('Content-Length: '.filesize($arqxml));
			while (ob_get_level()) ob_end_clean();
			@readfile($arqxml);

		}
	}
?>