<?php
/* função para cadastrar pedidos no bhan */

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

use \App\Models\Entity\DataOrderSellerDb;

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

  global $entityManager;

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

  foreach ($orders as $o) {
    if ($o->getPedidoBhan() == null) {
      $orderBhan[] = ([
        'id' => $o->getId(),
        'pedido' => $o->getOrderId(),
        'cliente' => $o->getCdPessoaBhan()
      ]);
    }
  }

  if (!empty($orderBhan)) {
    $itemsRepository = $entityManager->getRepository('App\Models\Entity\ItemsOrderDb');
    $items = $itemsRepository->findAll();

    foreach ($orderBhan as $order) {
      //var_dump($order['pedido']);
      //var_dump($order['cliente']);

      $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.'" />
      <pedido acao="con"  nr_pedidocliente="'.$order['pedido'].'" />
      </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);

        $arrXml[] = simplexml_load_string($start);
      }
    }
    //var_dump($arrXml);

    foreach ($arrXml as $pedidoXml) {
      if (isset($pedidoXml->pedido['ds_resposta']) && $pedidoXml->pedido['ds_resposta'] == 'pedido nao encontrado(a)') {
        foreach ($orders as $o) {
          if ((string)$pedidoXml->pedido['nr_pedidocliente'] == $o->getOrderId()) {
            $orderId = array(
              'id' => $o->getId(),
              'idOrder' => $o->getOrderId(),
              'cdPessoa' => $o->getCdPessoaBhan(),
              'data' => $o->getCreationDate()
            );
            foreach ($items as $key => $i) {
                //$itemArray = array();
              if ($o->getOrderId() == $i->getOrderId()) {
                $price = (float)$i->getPrice();
                $discountPrice = (float)$i->getDiscountPrice();
                $valorProduto = ($price + ($discountPrice)) / 100 ;
                array_push($orderId, [
                  'xml' => '<pedidoItem cd_barraprd="'.$i->getEan().'" qt_solicitada="'.$i->getQuantity().'" vl_unitario="'.$valorProduto.'" />'
                  ]);
              }
            }
            $pedidoArray[] = $orderId;
          }
        }

      }
    }
    $contador = count($pedidoArray);

    //var_dump($pedidoArray[0]);
    //var_dump(array_column($pedidoArray[0], 'xml'));

    for ($i=0; $i < $contador ; $i++) {

      $itemsXml = array_column($pedidoArray[$i], 'xml');
      $itemPedido = implode($itemsXml);

      $dataPedido = $pedidoArray[$i]['data'];
      $dataFormat = substr($dataPedido, 0 , 10);
      $noveDias = date('Y-m-d', strtotime($dataFormat . "+9 days"));

      $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.'" />
      <pedido acao="inc" cd_cliente="'.$pedidoArray[$i]['cdPessoa'].'" nr_pedidocliente="'.$pedidoArray[$i]['idOrder'].'"  cd_representant="218508"  cd_condpgto="009" dt_pedido="'.$dataFormat.'" tp_frete="1" pr_desconto="0" dt_chegada="'.$noveDias.'" tp_cobranca="0">
      '.$itemPedido.'
      </pedido>
      </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 {
        //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);

        $retorno = (string)$arrXml->pedido['ds_resposta'];

        if ($retorno == 'Registro gravado com sucesso') {
          $pedidoDb = $ordersRepository->find($pedidoArray[$i]['id']);
          $pedidoDb->setPedidoBhan($retorno);
          $entityManager->persist($pedidoDb);
          $entityManager->flush();
        }
        //var_dump($pedidoDb);
      }

      die;


    }

  }


}

orderBhan();
