<?php
session_start();
$numeroCNS  = "";

$FormAction = $_SERVER['PHP_SELF'];
if (isset($_SERVER['QUERY_STRING'])) {
  $FormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
}

if ((isset($_POST["Enviar"])) && ($_POST["Enviar"] == "form1")) {
	
$numeroCNS = $_POST['cartao'];

class soap_client{ 

  public $xmlRequest;
  public $header;

  function set_header(){

    $this->header = array(
      'Content-Type: application/soap+xml',
      'Authorization: jwt eyJraWQiOiJvYXV0aDJrZXlwYWlyIiwiYWxnIjoiUlMyNTYifQ.eyJpYXQiOjE2OTYyOTU0MjYsImV4cCI6MTY5NjI5NzIyNiwiaXNzIjoid3d3Lm9yYWNsZS5jb20iLCJzdWIiOiI2Nzg0ODI1NzU2OCIsIlJPTEVTIjoiIn0.iVK4JRcbNQU7FE0fLTllBz6oXONgZfbssGRiyUNyEYqd6reRMDZjrOXI7ag5dbReX3dcKxADAVowEZF2JGeIsEbI_kl9Czb5pCGO2VaY1JpWzI4pc7WlcXOEU98cxxxwGxJdwlikIkBTjxDz6YZW8K1yOZn6OXfM-H5hk1QakZFArkau7tAulyKBdnRirghkrav_RVVlmffeh38J5NSqrDa3dbiqMbFywgRNAMDVcIPTCRAr_Uk2p3hQIwFhaGo1TpZ9J2Cs7p8UQnT815yvR6u5djnZD5b2Z8csHjTj1ArGfPCi-IHqKsusTATNCsj0g2xTvBUVTUcrRVgvADIWXw',
      'Cookie: BIGipServercadastrohm.saude.gov.br=3298339008.20480.0000; TS01053ca6=01f6470b2f58062de2fa5dffd7a97f50f3ce677860ada5efcfc85a5dff6bd84c409d73189534cea815a7e1eef6264740fc328acd7ca502a461a957f9bac4c9264123822ba8'
	);

  }

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

    $soapCURL = curl_init();             
    curl_setopt($soapCURL, CURLOPT_URL, "https://servicoshm.saude.gov.br/cadsus/v2/PDQSupplierJWT");
    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;
  
  }

}

$xmlDataRequest = "<soap:Envelope xmlns:soap='http://www.w3.org/2003/05/soap-envelope' xmlns:urn='urn:ihe:iti:xds-b:2007' xmlns:urn1='urn:oasis:names:tc:ebxml-regrep:xsd:lcm:3.0' xmlns:urn2='urn:oasis:names:tc:ebxml-regrep:xsd:rim:3.0' xmlns:urn3='urn:ihe:iti:xds-b:2007'>
<soap:Body>
   <PRPA_IN201305UV02 xsi:schemaLocation='urn:hl7-org:v3 ./schema/HL7V3/NE2008/multicacheschemas/PRPA_IN201305UV02.xsd' ITSVersion='XML_1.0' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns='urn:hl7-org:v3'>
      <id root='2.16.840.1.113883.4.714' extension='123456'/>
      <creationTime value='20070428150301'/>
      <interactionId root='2.16.840.1.113883.1.6' extension='PRPA_IN201305UV02'/>
      <processingCode code='T'/>
      <processingModeCode code='T'/>
      <acceptAckCode code='AL'/>
      <receiver typeCode='RCV'>
         <device classCode='DEV' determinerCode='INSTANCE'>
            <id root='2.16.840.1.113883.3.72.6.5.100.85'/>
         </device>
      </receiver>
      <sender typeCode='SND'>
         <device classCode='DEV' determinerCode='INSTANCE'>
            <id root='2.16.840.1.113883.3.72.6.2'/>
            <name>CADSUS</name>
         </device>
      </sender>
      <controlActProcess classCode='CACT' moodCode='EVN'>
         <code code='PRPA_TE201305UV02' codeSystem='2.16.840.1.113883.1.6'/>
         <queryByParameter>
            <queryId root='1.2.840.114350.1.13.28.1.18.5.999' extension='1840997084'/>
            <statusCode code='new'/>
            <responseModalityCode code='R'/>
            <responsePriorityCode code='I'/>
            <parameterList>
               <livingSubjectId>
                  <value root='2.16.840.1.113883.13.236' extension='$numeroCNS'/>
                  <semanticsText>LivingSubject.id</semanticsText>
               </livingSubjectId>
            </parameterList>
         </queryByParameter>
      </controlActProcess>
   </PRPA_IN201305UV02>
</soap:Body>
</soap:Envelope>";

$objetoRetorno  =  new soap_client();
$objetoRetorno  -> xmlRequest = $xmlDataRequest;
$xmlRetorno     =  $objetoRetorno->send();

$getDocumento = new DOMDocument();
$getDocumento->loadXML($xmlRetorno);
$xpathXML = new DOMXPath($getDocumento);

$xmlns = array(
   'hl7' => 'urn:hl7-org:v3',
);

foreach ($xmlns as $prefix => $namespace) {
   $xpathXML->registerNamespace($prefix, $namespace);
}


$nomeElement = $xpathXML->query('//hl7:patientPerson/hl7:name[@use="L"]/hl7:given');
$nome = $nomeElement->item(0)->nodeValue;

$generoElement = $xpathXML->query('//hl7:administrativeGenderCode')->item(0);
$genero = $generoElement->getAttribute('code');

$generoFormatado = $genero == 'M' ? 'Masculino' : 'Feminino';

$dataNascimentoElement = $xpathXML->query('//hl7:birthTime')->item(0);
$dataNascimento = $dataNascimentoElement->getAttribute('value');

$dataNascimentoFormatada = DateTime::createFromFormat('YmdHis', $dataNascimento);
$dataNascimentoFormatada = $dataNascimentoFormatada->format('d/m/Y');

$cepElement = $xpathXML->query('//hl7:postalCode')->item(0);
$cep = $cepElement->textContent;

$numeroCasaElement = $xpathXML->query('//hl7:houseNumber')->item(0);
$numeroCasa = $numeroCasaElement->textContent;

$nomeDaRuaElement = $xpathXML->query('//hl7:streetName')->item(0);
$nomeDaRua = $nomeDaRuaElement->textContent;

$tipoDeRuaElement = $xpathXML->query('//hl7:streetNameType')->item(0);
$tipoDeRua = $tipoDeRuaElement->textContent;

$localizadorAdicionalElement = $xpathXML->query('//hl7:additionalLocator')->item(0);
$localizadorAdicional = $localizadorAdicionalElement->textContent;

$cidadeElement = $xpathXML->query('//hl7:city')->item(0);
$cidade = $cidadeElement->textContent;

$paisElement = $xpathXML->query('//hl7:country')->item(0);
$pais = $paisElement->textContent;

$localAondeNasceuElement = $xpathXML->query('//hl7:birthPlace')->item(0);

$cidadeAondeNasceuElement = $xpathXML->query('hl7:addr/hl7:city', $localAondeNasceuElement)->item(0);
$cidadeAondeNasceu = $cidadeAondeNasceuElement->textContent;

$paisAondeNasceuElement = $xpathXML->query('hl7:addr/hl7:country', $localAondeNasceuElement)->item(0);
$paisAondeNasceu = $paisAondeNasceuElement->textContent;

$codigoDeRacaElement = $xpathXML->query('//hl7:raceCode')->item(0);
$codigoDeRaca = $codigoDeRacaElement->getAttribute('code');

$emailElement = $xpathXML->query('//hl7:telecom[@use="NET"]')->item(0);
$email = $emailElement->getAttribute('value');

$telefoneElement = $xpathXML->query('//hl7:telecom[@use="ASN"]')->item(0);
$telefone = $telefoneElement->getAttribute('value');


$root236 = '';
// Root '2.16.840.1.113883.13.236'
$asOtherIDsElements1 = $xpathXML->query('//hl7:asOtherIDs[hl7:id/@root="2.16.840.1.113883.13.236"]');
foreach ($asOtherIDsElements1 as $asOtherIDsElement) {
    $extensionElement = $xpathXML->query('hl7:id[@root="2.16.840.1.113883.13.236"]', $asOtherIDsElement)->item(0);
    if ($extensionElement) {
        $root236 = $extensionElement->getAttribute('extension');
    }
}

$root2361 = '';
// Root '2.16.840.1.113883.13.236.1'
$asOtherIDsElements2 = $xpathXML->query('//hl7:asOtherIDs[hl7:id/@root="2.16.840.1.113883.13.236.1"]');
foreach ($asOtherIDsElements2 as $asOtherIDsElement) {
    $extensionElement = $xpathXML->query('hl7:id[@root="2.16.840.1.113883.13.236.1"]', $asOtherIDsElement)->item(0);
    if ($extensionElement) {
        $root2361 = $extensionElement->getAttribute('extension');
    }
}

$root237 = '';
// Root '2.16.840.1.113883.13.237'
$asOtherIDsElements3 = $xpathXML->query('//hl7:asOtherIDs[hl7:id/@root="2.16.840.1.113883.13.237"]');
foreach ($asOtherIDsElements3 as $asOtherIDsElement) {
    $extensionElement = $xpathXML->query('hl7:id[@root="2.16.840.1.113883.13.237"]', $asOtherIDsElement)->item(0);
    if ($extensionElement) {
        $root237 = $extensionElement->getAttribute('extension');
    }
}


$nomePais = array();

$personalRelationships = $xpathXML->query('//hl7:personalRelationship');

foreach ($personalRelationships as $personalRelationship) {
    $nomeElement = $xpathXML->query('.//hl7:name/hl7:given', $personalRelationship);

    if ($nomeElement->length > 0) {
        $nomePais[] = $nomeElement->item(0)->textContent;
    }
}
/////////////////////////////////////////

echo '<hr>';
echo 'Cartao: ' . $numeroCNS . '<br>';
echo 'Nome: ' . $nome . PHP_EOL . '<br>';
echo 'Gênero: ' . $generoFormatado . '<br>';
echo 'Data de Nascimento: ' . $dataNascimentoFormatada . '<br>';

echo '<hr>';
echo 'Cidade: ' . $cidade . '<br>';
echo 'País: ' . $pais . '<br>';
echo 'CEP: ' . $cep . '<br>';
echo 'Nome da Rua: ' . $nomeDaRua . '<br>';
echo 'Número da Casa: ' . $numeroCasa . '<br>';
echo 'Tipo de Rua: ' . $tipoDeRua . '<br>';
echo 'Localizador Adicional: ' . $localizadorAdicional . '<br>';

echo '<hr>';

echo 'Local de Nascimento:<br>';
echo 'Cidade: ' . $cidadeAondeNasceu . '<br>';
echo 'País: ' . $paisAondeNasceu;

echo '<hr>';

echo 'Código de Raça: ' . $codigoDeRaca . '<br>';

echo '<hr>';

echo 'E-mail: ' . $email . '<br>';
echo 'Telefone: ' . $telefone;

echo '<hr>';

echo 'Extensões:<br>';
echo 'Root final 236: ' . $root236 . '<br>';
echo 'Root final 236.1: ' . $root2361 . '<br>';
echo 'Root final 237: ' . $root237 . '<br>';

echo '<hr>';

foreach ($nomePais as $nome) {
    echo 'Nome dos pais: ' . $nome . '<br>';
}
echo '<hr>';
}else{
?>
<form  action="<?php echo $FormAction; ?>" method="post" name="Entrada" id="Entrada">
<input type="hidden" name="Enviar" value="form1">
<table width="765" border="1">
  <tr>
    <th scope="row">CONSULTA CARTAO</th>
  </tr>
</table>
<table width="765" border="1" align="left"  id="Entrada">
<tr valign="baseline">
  <td align="right" nowrap><div align="left">Cartao:</div></td>
  <td>
    <label for="cartao"></label>
    <input name="cartao" type="text" id="cartao" size="20" />
  </td>
</tr>
<tr>
  <td>&nbsp;</td>
  <td>
    <input name="Consultar" type="submit" class="button_adicionar" id="Consultar" value="Consultar">
  </td>
</tr>
</table>
</form>
<?php
}
?>
