<?php

namespace App\Controller;

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;

class SearchClient
{
  public function search(Request $request, Response $response, $args){

    $cd_loginws = getenv('cd_loginws');
    $cd_senhaws = getenv('cd_senhaws');
    $url = getenv('url');

    $docClient = $request->getParam('doc');
    //$docClient = "873.792.360-91"; //invalido
    //$docClient = "394.047.458-47"; // valido
    //$docClient = "35.742.323/0001-35"; // invalido
    //$docClient = "04.975.712/0001-87"; // valido

    if (strlen($docClient) == 14 || strlen($docClient) == 18) {

      if (strlen($docClient) == 14) {
        $docCpf = str_replace(".", "", $docClient);
        $cliente = str_replace("-", "", $docCpf);
      }else {
        $docCnpj = str_replace(".", "", $docClient);
        $BarraCnpj = str_replace("/", "", $docCnpj);
        $cliente = str_replace("-", "", $BarraCnpj);
      }

      $bodyXmlConsulta = '<?xml version="1.0" encoding="utf-8" ?>
      <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="urn:udmDados-IdmDados" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
      <SOAP-ENV:Body>
      <ns1:requisicao>
      <XML xsi:type="xsd:string">
      <requisicao in_schema="F" >
      <loginws cd_loginws="'.$cd_loginws.'" cd_senhaws="'.$cd_senhaws.'" />
      <pessoa acao="con"  nr_cpfcnpj="'.$cliente.'" />
      </requisicao>
      </XML>
      </ns1:requisicao>
      </SOAP-ENV:Body>
      </SOAP-ENV:Envelope>';

      $curl = curl_init();

      curl_setopt_array($curl, array(
        CURLOPT_URL => $url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => "",
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => false,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => "GET",
        CURLOPT_POSTFIELDS => $bodyXmlConsulta,
        CURLOPT_HTTPHEADER => array(
          "Content-Type: text/xml"
        ),
      ));
      $responseCurl = curl_exec($curl);
      $err = curl_error($curl);

      $curlClose = curl_close($curl);

      if ($err) {
        throw new \Exception("Erro de requisicao ".$err , 404);
      } else {

        //limpa string
        $bXml = str_replace("&lt;", "<", $responseCurl);
        $xml = str_replace("&gt;", ">", $bXml);
        $xmlEnd = str_replace("</return></NS1:requisicaoResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>", "", $xml);
        $start = substr($xmlEnd, 429);

        //converte para array xml
        $arrXml = simplexml_load_string($start);

        // se cliente não existir retorna ds_resposta
        if ($arrXml->pessoa['ds_resposta']) {
          $resposta = (string)$arrXml->pessoa['ds_resposta'];
          return $response->withJson(['resp'=>$resposta, 'cliente'=>$docClient] , 404)->withHeader('Content-Type','application/json');
        }

        //se cliente já cadastrado retorna cd_pessoa
        if ($arrXml->pessoa['cd_pessoa']) {
          $xml = $arrXml->pessoa;
          return $response->withJson($xml, 200)->withHeader('Content-Type','application/json');
        }

      }

    }else {
      throw new \Exception("documento invalido", 404);
    }

  }
}
