<?php
session_start();

	ini_set('xdebug.var_display_max_depth', -1);
	ini_set('xdebug.var_display_max_children', -1);
	ini_set('xdebug.var_display_max_data', -1);

	class soap_client{

    public $xmlRequest;
    public $header;

function set_header(){
	
  $this->header = array(
    "Content-type: text/xml;charset=\"utf-8\"",
    "Accept: text/xml",
    "Cache-Control: no-cache",
    "Pragma: no-cache",
    "SOAPAction: \"\"",
    "Content-length: ".strlen($this->xmlRequest)
  );

}

function send(){
		
   $this->set_header();

        $soapCURL = curl_init();             
        curl_setopt($soapCURL, CURLOPT_URL, "https://servicos.saude.gov.br/cadsus/CadsusService/v5r0");
        curl_setopt($soapCURL, CURLOPT_CONNECTTIMEOUT, 100);
        curl_setopt($soapCURL, CURLOPT_TIMEOUT,        1000);
        curl_setopt($soapCURL, CURLOPT_RETURNTRANSFER, true );
        curl_setopt($soapCURL, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($soapCURL, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($soapCURL, CURLOPT_POST,           true );
        curl_setopt($soapCURL, CURLOPT_POSTFIELDS,     $this->xmlRequest);
        curl_setopt($soapCURL, CURLOPT_HTTPHEADER,     $this->header);

        $result = curl_exec($soapCURL);
		
        if($result === false) {		
          $err = 'Curl error: ' . curl_error($soapCURL);
          $result = $err;
        }
        
		curl_close($soapCURL);
        return $result;
		
    }

}

function BuscarCNS($cns){
	include("configWS.php");
	$data = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/' xmlns:cad='http://servicos.saude.gov.br/cadsus/v5r0/cadsusservice' xmlns:cnes='http://servicos.saude.gov.br/wsdl/mensageria/v5r0/cnesusuario' xmlns:cns='http://servicos.saude.gov.br/schema/cadsus/v5r0/cns'>
	<soapenv:Header>
	<wsse:Security soapenv:mustUnderstand='1' xmlns:wsse='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd' xmlns:wsu='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd'>
	 <wsse:UsernameToken wsu:Id='".$UsernameToken."'>
		<wsse:Username>".$Username."</wsse:Username>
		<wsse:Password Type='http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText'>".$SenhaWS."</wsse:Password>
	 </wsse:UsernameToken>
	</wsse:Security>
 </soapenv:Header>
 <soapenv:Body>
	<cad:requestConsultar>
	 <cnes:CNESUsuario>
	 <cnes:CNES>".$CodCNES."</cnes:CNES>
	 <cnes:Usuario>".$UsuarioCNES."</cnes:Usuario>
	 </cnes:CNESUsuario>
	 <cns:CNS>
		<cns:numeroCNS>" . $cns . "</cns:numeroCNS>
	 </cns:CNS>
	</cad:requestConsultar>
 </soapenv:Body>
</soapenv:Envelope>";


	$obj = new soap_client();
	$obj->xmlRequest = $data;
	$resultad_xml=$obj->send();

	$xml = simplexml_load_string($resultad_xml);
	
	$xml->registerXPathNamespace('cns', 'http://servicos.saude.gov.br/schema/cadsus/v5r0/cns');
	$xml->registerXPathNamespace('nom', 'http://servicos.saude.gov.br/schema/cadsus/v5r0/usuariosus');
	$xml->registerXPathNamespace('mae', 'http://servicos.saude.gov.br/schema/corporativo/pessoafisica/v1r2/nomecompleto');
	$xml->registerXPathNamespace('sexo','http://servicos.saude.gov.br/schema/corporativo/pessoafisica/v1r1/sexo');
	$xml->registerXPathNamespace('rac', 'http://servicos.saude.gov.br/schema/corporativo/pessoafisica/v1r2/racacor');
	$xml->registerXPathNamespace('end', 'http://servicos.saude.gov.br/schema/corporativo/endereco/v1r2/endereco');
	$xml->registerXPathNamespace('end', 'http://servicos.saude.gov.br/schema/corporativo/endereco/v1r2/endereco');
	$xml->registerXPathNamespace('cep', 'http://servicos.saude.gov.br/schema/corporativo/endereco/v1r1/cep');
	$xml->registerXPathNamespace('bai', 'http://servicos.saude.gov.br/schema/corporativo/endereco/v1r1/bairro');
	$xml->registerXPathNamespace('tip', 'http://servicos.saude.gov.br/schema/corporativo/endereco/v1r1/tipologradouro');
	$xml->registerXPathNamespace('tel', 'http://servicos.saude.gov.br/schema/corporativo/telefone/v1r2/telefone');
	$xml->registerXPathNamespace('mun', 'http://servicos.saude.gov.br/schema/corporativo/v1r2/municipio');
	$xml->registerXPathNamespace('uf', 	'http://servicos.saude.gov.br/schema/corporativo/v1r1/uf');
	$xml->registerXPathNamespace('cpf', 'http://servicos.saude.gov.br/schema/corporativo/documento/v1r2/cpf');
	
	
	$cartoesSUS        				= $xml->xpath('//cns:numeroCNS');
	$itemNomeCompleto  				= $xml->xpath('//nom:Nome');
	$itemDataNasc      				= $xml->xpath('//nom:dataNascimento');
	$itemNomeCompleto  				= $xml->xpath('//mae:Nome');
	$itemSexo          				= $xml->xpath('//sexo:codigoSexo');
	$itemcodigoRacaCor 				= $xml->xpath('//rac:codigoRacaCor');
	$itemcodigoTipoLogradouro = $xml->xpath('//tip:codigoTipoLogradouro');
	$itemnomeLogradouroo 			= $xml->xpath('//end:nomeLogradouro');
	$itemnroLogradouroo  			= $xml->xpath('//end:numero');
	$itemcep             			= $xml->xpath('//cep:numeroCEP');
	$itemnomebairro      			= $xml->xpath('//bai:descricaoBairro');
	$itemtelefone        			= $xml->xpath('//tel:numeroTelefone');
	$itemcodigomunic     			= $xml->xpath('//mun:codigoMunicipio');
	$itemMunicipio       			= $xml->xpath('//mun:nomeMunicipio');
	$itemcodigoUF        			= $xml->xpath('//uf:codigoUF');
	$itemcpf             			= $xml->xpath('//cpf:numeroCPF');
	$cartoesSUS        = $xml->xpath('//cns:numeroCNS');
	$itemNomeCompleto  = $xml->xpath('//nom:Nome');
	$itemDataNasc      = $xml->xpath('//nom:dataNascimento');
	$itemNomeCompleto  = $xml->xpath('//mae:Nome');
	$itemSexo          = $xml->xpath('//sexo:codigoSexo');
	$itemcodigoRacaCor = $xml->xpath('//rac:codigoRacaCor');
	$itemcodigoTipoLogradouro = $xml->xpath('//tip:codigoTipoLogradouro');
	$itemnomeLogradouroo = $xml->xpath('//end:nomeLogradouro');
	$itemnroLogradouroo  = $xml->xpath('//end:numero');
	$itemcep             = $xml->xpath('//cep:numeroCEP');
	$itemnomebairro      = $xml->xpath('//bai:descricaoBairro');
	$itemtelefone        = $xml->xpath('//tel:numeroTelefone');
	$itemcodigomunic     = $xml->xpath('//mun:codigoMunicipio');
	$itemMunicipio       = $xml->xpath('//mun:nomeMunicipio');
	$itemcodigoUF        = $xml->xpath('//uf:codigoUF');
	$itemcpf             = $xml->xpath('//cpf:numeroCPF');	

	if(isset($cartoesSUS[0])){
		$numero_cns = $cartoesSUS[0];
		for ($i = 1; $i <= count($cartoesSUS); $i++) {
	 		if(substr($cartoesSUS[$i-1],0,1)=="7"){
				$numero_cns   = $cartoesSUS[$i-1];
	 		}	 
		}		
	}else{
		$numero_cns = "";
	}
	if(isset($itemNomeCompleto[0])){
		$nome_usuario = $itemNomeCompleto[0];
	}else{
		$nome_usuario = "";
	}
	if(isset($itemDataNasc[0])){
		$data_nascimento = $itemDataNasc[0];
	}else{
		$data_nascimento = "";
	}
	if(isset($itemcpf[0])){
		$numero_cpf = $itemcpf[0];
	}else{
		$numero_cpf = "";
	}
	if(isset($itemNomeCompleto[1])){
		$nome_mae = $itemNomeCompleto[1];
	}else{
		$nome_mae = "";
	}
	if(isset($itemSexo[0])){
		$sexo_usuario = $itemSexo[0];
	}else{
		$sexo_usuario = "";
	}
	if(isset($itemcodigoRacaCor[0])){
		$raca_cor	 = $itemcodigoRacaCor[0];
	}else{
		$raca_cor = "";
	}
	if(isset($itemcodigoTipoLogradouro[0])){
		$tipo_logradouro = $itemcodigoTipoLogradouro[0];
	}else{
		$tipo_logradouro = "";
	}
	if(isset($itemnomeLogradouroo[0])){
		$nome_logradouro = $itemnomeLogradouroo[0];
	}else{
		$nome_logradouro = "";
	}
	if(isset($itemnroLogradouroo[0]) && $itemnroLogradouroo[0]!="S/N"){
		$numero_residencia = $itemnroLogradouroo[0];
	}else{
		$numero_residencia = "SN";
	}
	if($numero_residencia==""){
	    $numero_residencia = "SN";
	}else{
	    $numero_residencia = $numero_residencia;
	}
	
	if(isset($itemcep[0])){
		$numero_cep = $itemcep[0];
	}else{
		$numero_cep = "";
	}
	if(isset($itemnomebairro[0])){
		$nome_bairro = $itemnomebairro[0];
	}else{
		$nome_bairro = "";
	}
	if(isset($itemtelefone[0])){
		$telefone = $itemtelefone[0];
	}else{
		$telefone = "0";
	}	
	if(isset($itemcodigomunic[1])){
		$codigo_municipio = $itemcodigomunic[1];
	}else{
		$codigo_municipio = "";
	}
	if(isset($itemMunicipio[1])){
		$nome_municipio = $itemMunicipio[1];
	}else{
		$nome_municipio = "";
	}
	if(isset($itemcodigoUF[0])){
		$sigla_uf = $itemcodigoUF[0];
	}else{
		$sigla_uf = "";
	}
	if(isset($itemNomeCompleto[2][0])){
		$nome_pai = $itemNomeCompleto[2][0];
	}else{
		$nome_pai = "";
	}

	//if($cartoesSUS){

		$obj = array(
		"numero_cns" 				=> $numero_cns,
		"nome_usuario"			=> $nome_usuario,
		"data_nascimento" 	=> $data_nascimento,
		"numero_cpf"				=> $numero_cpf,
		"nome_mae"					=> $nome_mae,
		"sexo_usuario"			=> $sexo_usuario,
		"raca_cor"					=> $raca_cor,
		"tipo_logradouro"		=> $tipo_logradouro,
		"nome_logradouro"		=> $nome_logradouro,
		"numero_residencia"	=> $numero_residencia,
		"numero_cep"				=> $numero_cep,
		"nome_bairro"				=> $nome_bairro,
		"telefone"					=> $telefone,
		"codigo_municipio"	=> $codigo_municipio,
		"nome_municipio"		=> $nome_municipio,
		"sigla_uf"					=> $sigla_uf,
		"nome_pai"					=> $nome_pai
		);
		$lista_json = array("array_cns" => array());
		array_push($lista_json["array_cns"], $obj);
		$json_retorno = str_replace('"},"','","',json_encode($lista_json));
		$json_retorno = str_replace('{"0":"','"',$json_retorno);
		$json_retorno = str_replace('}}]}',']}',$json_retorno);
		$json_retorno = str_replace('","','"},{"',$json_retorno);
		$json_retorno = str_replace(']}','}]}',$json_retorno);
	
		echo $json_retorno;
}

if($_SESSION["opcaoBusca"]=="cns"){

	$num_cns = $_SESSION["codigoBusca"];
	BuscarCNS($num_cns);

}else if($_SESSION["opcaoBusca"]=="cpf"){
	include("configWS.php");
	$num_cpf = $_SESSION["codigoBusca"];
	$data ='
	<soap:Envelope xmlns:soap="http://www.w3.org/2003/05/soap-envelope" xmlns:cad="http://servicos.saude.gov.br/cadsus/v5r0/cadsusservice" xmlns:cnes="http://servicos.saude.gov.br/wsdl/mensageria/v5r0/cnesusuario" xmlns:fil="http://servicos.saude.gov.br/wsdl/mensageria/v5r0/filtropesquisa" xmlns:nom="http://servicos.saude.gov.br/schema/corporativo/pessoafisica/v1r2/nomecompleto" xmlns:nom1="http://servicos.saude.gov.br/schema/corporativo/pessoafisica/v1r0/nomefamilia" xmlns:cpf="http://servicos.saude.gov.br/schema/corporativo/documento/v1r2/cpf" xmlns:mun="http://servicos.saude.gov.br/schema/corporativo/v1r2/municipio" xmlns:uf="http://servicos.saude.gov.br/schema/corporativo/v1r1/uf" xmlns:tip="http://servicos.saude.gov.br/schema/corporativo/documento/v5r0/tipodocumento">
	<soap:Header>
		<wsse:Security soap:mustUnderstand="1" 
		xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" 
		xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
		<wsse:UsernameToken wsu:Id="' . $UsernameToken . '">
		<wsse:Username>' . $Username . '</wsse:Username>
		<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">'. $SenhaWS . '</wsse:Password>
		<wsu:Created>2015-04-29T15:10:14.659Z</wsu:Created>
		</wsse:UsernameToken>
		</wsse:Security>
	 </soap:Header>
	 <soap:Body>
		<cad:requestPesquisar>
		 <cnes:CNESUsuario>
		 <cnes:CNES>'. $CodCNES . '</cnes:CNES>
		 <cnes:Usuario>'. $UsuarioCNES . '</cnes:Usuario>
			<!--Optional:-->
			<cnes:Senha>?</cnes:Senha>
		 </cnes:CNESUsuario>
		 <fil:FiltroPesquisa>
			<fil:CPF>
				 <cpf:numeroCPF>' . $num_cpf . '</cpf:numeroCPF>
			</fil:CPF>
			<fil:tipoPesquisa>IDENTICA</fil:tipoPesquisa>
		 </fil:FiltroPesquisa>
		 <cad:higienizar>0</cad:higienizar>
		</cad:requestPesquisar>
	</soap:Body>
	</soap:Envelope>';

	$obj = new soap_client();
	$obj->xmlRequest = $data;
	$resultad_xml=$obj->send();
	$xml = simplexml_load_string($resultad_xml);	

	$xml->registerXPathNamespace('cns', 'http://servicos.saude.gov.br/schema/cadsus/v5r0/cns');
	$cartoesSUS  = $xml->xpath('//cns:numeroCNS');

	if($cartoesSUS){
		BuscarCNS($cartoesSUS[0]);
	}else{		
		echo '{"array_cns":[{"Paciente n&atilde;o encontrato."}]}';			
	}
	
}else if($_SESSION["opcaoBusca"]=="nome"){

	include("configWS.php");
	$nomepac = $_GET['nomepac'];
	$dtnasc = $_GET['nomepac'];
	$frmt_dtnasc	= explode("-",$_GET['dtnasc']);
	$data_nasc		= $frmt_dtnasc[2].'-'.$frmt_dtnasc[1].'-'.$frmt_dtnasc[0];
	
	$data ='<soap:Envelope 
	xmlns:soap="http://www.w3.org/2003/05/soap-envelope" 
	xmlns:cad="http://servicos.saude.gov.br/cadsus/v5r0/cadsusservice" 
	xmlns:cnes="http://servicos.saude.gov.br/wsdl/mensageria/v5r0/cnesusuario" 
	xmlns:fil="http://servicos.saude.gov.br/wsdl/mensageria/v5r0/filtropesquisa" 
	xmlns:nom="http://servicos.saude.gov.br/schema/corporativo/pessoafisica/v1r2/nomecompleto" 
	xmlns:nom1="http://servicos.saude.gov.br/schema/corporativo/pessoafisica/v1r0/nomefamilia" 
	xmlns:cpf="http://servicos.saude.gov.br/schema/corporativo/documento/v1r2/cpf" 
	xmlns:mun="http://servicos.saude.gov.br/schema/corporativo/v1r2/municipio" 
	xmlns:uf="http://servicos.saude.gov.br/schema/corporativo/v1r1/uf" 
	xmlns:tip="http://servicos.saude.gov.br/schema/corporativo/documento/v5r0/tipodocumento">
		<soap:Header>
		<wsse:Security soap:mustUnderstand="1" 
		xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" 
		xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
		<wsse:UsernameToken wsu:Id="' . $UsernameToken . '">
		<wsse:Username>' . $Username . '</wsse:Username>
		<wsse:Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText">'. $SenhaWS . '</wsse:Password>
		<wsu:Created>2015-04-29T15:10:14.659Z</wsu:Created>
		</wsse:UsernameToken>
		</wsse:Security>
	 </soap:Header>
	 <soap:Body>
		<cad:requestPesquisar>
			<cnes:CNESUsuario>
				<cnes:CNES>'. $CodCNES . '</cnes:CNES>
				<cnes:Usuario>'. $UsuarioCNES . '</cnes:Usuario>
				<!--Optional:-->
				<cnes:Senha>?</cnes:Senha>
			</cnes:CNESUsuario>
		
			 <fil:FiltroPesquisa>           
				<fil:nomeCompleto>
				 <nom:Nome>' . $nomepac . '</nom:Nome>
				</fil:nomeCompleto>   
				<fil:dataNascimento>'.$data_nasc.'</fil:dataNascimento>
				<fil:tipoPesquisa>IDENTICA</fil:tipoPesquisa>
			 </fil:FiltroPesquisa>
			 <cad:higienizar>0</cad:higienizar>
		</cad:requestPesquisar>
	 </soap:Body>
	</soap:Envelope>';

	$obj = new soap_client();
	$obj->xmlRequest = $data;
	$resultad_xml=$obj->send();
	$xml = simplexml_load_string($resultad_xml);	
	$xml->registerXPathNamespace('ns4', 'http://servicos.saude.gov.br/schema/cadsus/v5r0/cns');
	$cartoesSUS  = $xml->xpath('//ns4:numeroCNS');
	if($cartoesSUS){
		BuscarCNS($cartoesSUS[0]);
	}else{		
		echo '{"array_cns":[{"Paciente n&atilde;o encontrato."}]}';			
	}
	
}


?>