<?php
session_start();

$opcaoDocumentoPaciente  = $_POST['opcaoDocumento'];
$numeroDocumentoPaciente = $_POST['numeroDocumento'];

switch($opcaoDocumentoPaciente){
   case "cns":
      $instalceDevisaBusca       = "CADSUS";
      $numeroIdentificadorRoot   = "236";
   break;

   case "cpf":
      $instalceDevisaBusca = "[SYSTEMCODE]";
      $numeroIdentificadorRoot   = "237";
   break;

}
class soap_client{

  public $xmlRequest;
  public $header;

  //Configuar cabeçalho com o token validado
  function set_header(){

   $this->header = array(
      'Content-Type: application/soap+xml',
      'Authorization: jwt eyJraWQiOiJvYXV0aDJrZXlwYWlyIiwiYWxnIjoiUlMyNTYifQ.eyJpYXQiOjE2OTYwMzA1MTcsImV4cCI6MTY5NjAzMjMxNywiaXNzIjoid3d3Lm9yYWNsZS5jb20iLCJzdWIiOiI2Nzg0ODI1NzU2OCIsIlJPTEVTIjoiIn0.N_Ud0XGoSFXVY7a2DEipMq8GKLc2eOuuzVRR0-Xv1RVhRalYLZRxJgSPDkQtZn0EL5MMjQdXs1BOgPJIwlcZ533a6dnIBP05vuq95-nPvvFLWjMaklL-fcHRV4elCIthG-Wkas6cUnA9Sz4tJOHNOXiUssz3r1u9Y0K1lYxecntQS9tC3rPrJzzrqtHM2N-phgb093QyzUaw6AbfU3aStU7AIXU_YNwBB2DWqmwT-DqBKXBrfP-E13-LK2bd1ZGg7QGxn4NtG0aUW615Wc9wrzPSvycSwM2FLmZuYPMOzOfrzPVmv_v8q1tMmB62wABy8DodxcxVhIqxKCO6_rm3qA',
      'Cookie: BIGipServercadastrohm.saude.gov.br=3298339008.20480.0000; TS01053ca6=01f6470b2f0ccfb08936be5818fc0c8f50ff8400843fe59d61276dfa75b935add1b5173920ca7ec0adbf976b1da5407892f43a62bdabb77c589016aa723afcee593946c39e'
    );

  }

  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);

    $resultadoSoap = curl_exec($soapCURL);
  
    if($resultadoSoap === false) {		
      $errSoap = 'Curl Error: ' . curl_error($soapCURL);
      $resultadoSoap = $errSoap;
    }
      
    curl_close($soapCURL);
    return $resultadoSoap;
  
  }

}

$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>$instalceDevisaBusca</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.$numeroIdentificadorRoot' extension='$numeroDocumentoPaciente'/>
                  <semanticsText>LivingSubject.id</semanticsText>
               </livingSubjectId>
            </parameterList>
         </queryByParameter>
      </controlActProcess>
   </PRPA_IN201305UV02>
</soap:Body>
</soap:Envelope>";

$objetoRetorno  =  new soap_client();
$objetoRetorno  -> xmlRequest = $xmlDataRequest;
$xmlRetorno     =  $objetoRetorno->send();
$setDocumento = new DOMDocument();
$setDocumento->loadXML($xmlRetorno);
$xpathXML = new DOMXPath($setDocumento);

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

foreach ($xmlNameSpace as $setPrefix => $nameSpaceReferencia) {
   $xpathXML->registerNamespace($setPrefix, $nameSpaceReferencia);
}

/*pegar dados pessoais do paciente*/
$elementoNome = $xpathXML->query('//hl7:patientPerson/hl7:name[@use="L"]/hl7:given');
$nomePaciente = $elementoNome->item(0)->nodeValue;

$elementoSexo = $xpathXML->query('//hl7:administrativeGenderCode')->item(0);
$sexoPaciente = $elementoSexo->getAttribute('code');
$sexoPaciente = $sexoPaciente == 'M' ? 'MARCULINO' : 'FEMININO';

$nomeSocialPaciente  = "";

$elementoNascimento = $xpathXML->query('//hl7:birthTime')->item(0);
$dataNascimento     = $elementoNascimento->getAttribute('value');
$dataNascimento     = DateTime::createFromFormat('YmdHis', $dataNascimento);
$dataNascimento     = $dataNascimento->format('Y-m-d');

/*pegar dados residenciais do paciente*/
$elementoCEP  = $xpathXML->query('//hl7:postalCode')->item(0);
$numeroCEP    = $elementoCEP->textContent;

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

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

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

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

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

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

$elementoMunicipioNascimento  = $xpathXML->query('//hl7:birthPlace')->item(0);
$municipioNascimento          = $xpathXML->query('hl7:addr/hl7:city', $elementoMunicipioNascimento)->item(0);
$municipioNascimento          = $municipioNascimento->textContent;
$paisNascimento               = $xpathXML->query('hl7:addr/hl7:country', $elementoMunicipioNascimento)->item(0);
$paisNascimento               = $paisNascimento->textContent;

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

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

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


/* pegar CNS do paciente */
$numeroCNSPaciente = '';
$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) {
        $numeroCNSPaciente  = $extensionElement->getAttribute('extension');
    }
}

$tipoCNSPaciente = '';
$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) {
        $tipoCNSPaciente = $extensionElement->getAttribute('extension');
    }
}

/* pegar CPF do paciente */
$numeroCPFPaciente  = '';
$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) {
        $numeroCPFPaciente = $extensionElement->getAttribute('extension');
    }
}

/* pegar dados dos pais do paciente */
$nomePaisPaciente = array();
$personalRelationships = $xpathXML->query('//hl7:personalRelationship');
foreach ($personalRelationships as $personalRelationship) {
    $nomeElement = $xpathXML->query('.//hl7:name/hl7:given', $personalRelationship);
    if ($nomeElement->length > 0) {
        $nomePaisPaciente[] = $nomeElement->item(0)->textContent;
    }
}
/////////////////////////////////////////

$arrayPaciente = array(
  'nomePaciente'              => $nomePaciente,
  'numeroCNSPaciente'         => $numeroCNSPaciente,
  'numeroCPFPaciente'         => $numeroCPFPaciente,
  'nomeSocialPaciente'        => $nomeSocialPaciente,
  'dataNascimentoPaciente'    => $dataNascimento,
  'generoSexoPaciente'        => $sexoPaciente,
  'nomeMaeResponsavel'        => $nomePaisPaciente[0],
  'nomePaiResponsavel'        => $nomePaisPaciente[1],
  'cepEnderecoPaciente'       => $numeroCEP,
  'nomeRuaResidencia'         => $nomeRuaEndereco,
  'numeroResidenciaPaciente'  => $numeroCasa,
  'bairroEnderecoPaciente'    => $nomeBairro,
  'cidadeResidenciaPaciente'  => $ibgeMunicipioResidencia,
  'telefonePaciente'          => $telefonePaciente
);

 echo json_encode($arrayPaciente);

?>