<?php
//397506

namespace App\Controller;

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

class InputClient
{
  public function register(Request $request, Response $response, $args){

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

    $docClient = $request->getParam('doc');
    $phone = $request->getParam('phone');
    $name = $request->getParam('name');
    $email = $request->getParam('email');
    $numberAddress = $request->getParam('numberAddress');
    $complementAddress = $request->getParam('complementAddress');
    $address = $request->getParam('address');
    $classCnpj = $request->getParam('ramo');
    $classificacao = '5';

    $cep = str_replace("-", "", $address['zipcode']);

    //limpar strings
    if (strlen($docClient) == 14 || strlen($docClient) == 18) {
      if (strlen($docClient) == 14) {
        $docCpf = str_replace(".", "", $docClient);
        $cliente = str_replace("-", "", $docCpf);
        $tipo = 'F';
        $tipoEndereco = '2';
      }else {
        $docCnpj = str_replace(".", "", $docClient);
        $BarraCnpj = str_replace("/", "", $docCnpj);
        $cliente = str_replace("-", "", $BarraCnpj);
        $tipo = 'J';
        $tipoEndereco = '1';
      }

      if (!empty($complementAddress)) {
        $complementoEndereco = preg_replace('/[`^~\'"]/', null, iconv('UTF-8', 'ASCII//TRANSLIT', $complementAddress));
      }else {
        $complementoEndereco = '';
      }

      if ($classCnpj == true) {
        $classificacao = '1';
      }

      $nome = preg_replace('/[`^~\'"]/', null, iconv('UTF-8', 'ASCII//TRANSLIT', $name));
      $endereco = preg_replace('/[`^~\'"]/', null, iconv('UTF-8', 'ASCII//TRANSLIT', $address['street']));
      $bairro = preg_replace('/[`^~\'"]/', null, iconv('UTF-8', 'ASCII//TRANSLIT', $address['neighborhood']));

      $bodyXmlCadastro = '<?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="inc" nr_cpfcnpj="'.$cliente.'" nm_pessoa="'.$nome.'" tp_pessoa="'.$tipo.'" cd_empresacad="1" >
      <endereco cd_tipoendereco="'.$tipoEndereco.'" cd_cep="'.$cep.'" nm_logradouro="'.$endereco.'"  ds_complemento="'.$complementoEndereco.'" ds_bairro="'.$bairro.'"  />
      <telefone cd_tipofone="1" in_padrao="T" nr_telefone="'.$phone.'" />
      <email cd_tipoemail="1" ds_email="'.$email.'" in_padrao="T" />
      <pessoaClas cd_tipoclas="1" cd_classificacao="'.$classificacao.'" />
      <pesInfo cd_emppadrao="1" />
      </pessoa>
      </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 => "POST",
        CURLOPT_POSTFIELDS => $bodyXmlCadastro,
        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 cadastro do cliente for ok, retorna cd_pessoa
        if ($arrXml->pessoa['cd_pessoa']) {
          $resposta = (string)$arrXml->pessoa['cd_pessoa'];
          return $response->withJson(['pessoa'=>$resposta] , 200)->withHeader('Content-Type','application/json');
        }else {
          return $response->withJson('Invalido' , 400)->withHeader('Content-Type','application/json');
        }

      }

    }

    //var_dump($bodyXmlCadastro);

  }
}
