<?php
/* função verifica se o cliente está cadastrado no bhan
  se sim, recupera o cd_pessoa e realiza as alterações
  se não, cadastra cliente
*/

include_once '../cron/config.php';
include_once './env.php';

use \App\Models\Entity\DataOrderSellerDb;

function clientBhan(){
  // env.php
  $cd_loginws = getenv('cd_loginws');
  $cd_senhaws = getenv('cd_senhaws');
  $url = getenv('url');

  global $entityManager;
  //var_dump($entityManager);

  $ordersRepository = $entityManager->getRepository('App\Models\Entity\DataOrderSellerDb');
  $orders = $ordersRepository->findAll();

  foreach ($orders as $key => $o) {
    if ($o->getCdPessoaBhan() == null) {
      $ordCpf[] = ([
        'id' => $o->getId(),
        'cpf' => $o->getClientCpf()
      ]);
    }
  }

  if (!empty($ordCpf)) {
    var_dump($ordCpf);
    foreach ($ordCpf as $key => $cpf) {
      //var_dump($cpf['cpf']);
      //var_dump($cpf['id']);

      $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="'.$cpf['cpf'].'" />
      </requisicao>
      </XML>
      </ns1:requisicao>
      </SOAP-ENV:Body>
      </SOAP-ENV:Envelope>';

      var_dump($bodyXmlConsulta);

      $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"
        ),
      ));
      $response = curl_exec($curl);
      $err = curl_error($curl);

      $curlClose = curl_close($curl);

      if ($err) {
        echo "cURL Error #: " . $err;
      } else {

        //limpa string
        $bXml = str_replace("&lt;", "<", $response);
        $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);

        $cdPessoa[] = ([
          'id' => $cpf['id'],
          'cpf' => $cpf['cpf'],
          //retorna string
          'cdPessoa' => (string)$arrXml->pessoa['cd_pessoa']
        ]);
      }

    }

    var_dump($cdPessoa);

    foreach ($cdPessoa as $key => $p) {
      if (!empty($p['cdPessoa'])) {
        // alterar endereço no bhan e adicionar o cd_pessoa na tabela dataordersellers
        $order = $ordersRepository->find($p['id']);

        // tira acento das palavras preg_replace('/[`^~\'"]/', null, iconv('UTF-8', 'ASCII//TRANSLIT', $string));
        $street = preg_replace('/[`^~\'"]/', null, iconv('UTF-8', 'ASCII//TRANSLIT', $order->getStreet()));
        $complementAdress = preg_replace('/[`^~\'"]/', null, iconv('UTF-8', 'ASCII//TRANSLIT', $order->getComplementAdress()));
        $neighborhood = preg_replace('/[`^~\'"]/', null, iconv('UTF-8', 'ASCII//TRANSLIT', $order->getNeighborhood()));
        $cep = str_replace("-", "", $order->getPostalCode());

        $bodyXmlAlteracao = '<?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="alt" nr_cpfcnpj="'.$p["cpf"].'">
        <endereco cd_tipoendereco="2" ds_siglalograd="AV" cd_cep="'.$cep.'" nm_logradouro="'.$street.'" nr_logradouro="'.$order->getNumberAdress().'" ds_complemento="'.$complementAdress.'" ds_bairro="'.$neighborhood.'" />
        </pessoa>
        </requisicao>
        </XML>
        </ns1:requisicao>
        </SOAP-ENV:Body>
        </SOAP-ENV:Envelope>';

        var_dump($bodyXmlAlteracao);

        $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 => "PUT",
          CURLOPT_POSTFIELDS => $bodyXmlAlteracao,
          CURLOPT_HTTPHEADER => array(
            "Content-Type: text/xml"
          ),
        ));
        $response = curl_exec($curl);
        $err = curl_error($curl);

        $curlClose = curl_close($curl);

        if ($err) {
          echo "cURL Error #: " . $err;
        }else {
          echo $response;
          $order->setCdPessoaBhan($p['cdPessoa']);
          $entityManager->persist($order);
          $entityManager->flush();
        }

      }else{
        $order = $ordersRepository->find($p['id']);

        // tira acento das palavras preg_replace('/[`^~\'"]/', null, iconv('UTF-8', 'ASCII//TRANSLIT', $string));
        $street = preg_replace('/[`^~\'"]/', null, iconv('UTF-8', 'ASCII//TRANSLIT', $order->getStreet()));
        $complementAdress = preg_replace('/[`^~\'"]/', null, iconv('UTF-8', 'ASCII//TRANSLIT', $order->getComplementAdress()));
        $neighborhood = preg_replace('/[`^~\'"]/', null, iconv('UTF-8', 'ASCII//TRANSLIT', $order->getNeighborhood()));
        $cep = str_replace("-", "", $order->getPostalCode());
        $clientFirstName = preg_replace('/[`^~\'"]/', null, iconv('UTF-8', 'ASCII//TRANSLIT', $order->getClientFirstName()));
        $clientLastName = preg_replace('/[`^~\'"]/', null, iconv('UTF-8', 'ASCII//TRANSLIT', $order->getClientLastName()));
        $phone = str_replace("+55", "", $order->getPhone());

        if (strlen($p['cpf']) == 11) {
          $tpPessoa = 'F';
        }else {
          $tpPessoa = 'J';
        }

        $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="'.$p['cpf'].'" nm_pessoa="'.$clientFirstName.' '. $clientLastName.'" tp_pessoa="'.$tpPessoa.'" cd_empresacad="1" >
        <pessoaCliente tp_formapgto="3" in_bloqueado="F" in_cnsrfinal="T" />
        <endereco cd_tipoendereco="2" ds_siglalograd="AV" cd_cep="'.$cep.'" nm_logradouro="'.$street.'" nr_logradouro="'.$order->getNumberAdress().'" ds_complemento="'.$complementAdress.'" ds_bairro="'.$neighborhood.'" />
        <telefone cd_tipofone="2" nr_telefone="'.$phone.'"  in_padrao="T"/>
        <pessoaClas cd_tipoclas="1" cd_classificacao="8" />
        <reprCliente cd_representant="218508" />
        <pesInfo cd_emppadrao="1" />
        </pessoa>
        </requisicao>
        </XML>
        </ns1:requisicao>
        </SOAP-ENV:Body>
        </SOAP-ENV:Envelope>';

        var_dump($bodyXmlCadastro);

        $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"
          ),
        ));
        $response = curl_exec($curl);
        $err = curl_error($curl);

        $curlClose = curl_close($curl);

        if ($err) {
          echo "cURL Error #:" . $err;
        }else {
          echo $response;
          $order->setCdPessoaBhan($p['cdPessoa']);
          $entityManager->persist($order);
          $entityManager->flush();
        }
      }
    }
  }
}

clientBhan();
