<?php
// verifica novos pedidos e cadastra no db
namespace App\Controllers\DB;

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

use \App\Models\Entity\OrdersDb;
use \App\Models\Entity\DataOrderSellerDb;
use \App\Controllers\Container;


class DataOrderSellerDBController extends Container
{
  public function get(Request $request, Response $response, $args){

    // env.php define variaveis
    $token = getenv('token');
    $keyApp = getenv('appkey');

    //conexão da lista
    $entityManager = $this->container->get('em');
    $ordersRepository = $entityManager->getRepository('App\Models\Entity\OrdersDb');
    $order = $ordersRepository->findAll();

    //lista os que estão com null
    foreach ($order as $ord) {
      if ($ord->getSellerId() == null) {
        $array[] = $ord->getOrderId();
      }
    }

    //var_dump($array);
    //die;

    //conexão dos pedidos
    $pedidoRepository = $entityManager->getRepository('App\Models\Entity\DataOrderSellerDb');
    $pedido = $pedidoRepository->findAll();

    foreach ($pedido as $p) {
      $pedidoArray[] = $p->getOrderId();
    }

    $results = array_diff($array, $pedidoArray);

    //$chaveArray = array_keys($results);
    //$resultJson = json_encode($results, true);

    if (!empty($results)) {

        $multCurl = array();
        $res = array();
        $curl = curl_multi_init();

        foreach ($results as $result => $id) {
          $fetchURL = 'https://arsdesign.myvtex.com/api/oms/pvt/orders/'.$id;
          $multCurl[$result] = curl_init();

        curl_setopt_array($multCurl[$result], array(
          CURLOPT_URL => $fetchURL,
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => "",
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 120,
          CURLOPT_FOLLOWLOCATION => false,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => "GET",
          CURLOPT_HTTPHEADER => array(
            "Accept: application/json",
            "Content-Type: application/json",
            "X-VTEX-API-AppToken: {$token}",
            "X-VTEX-API-AppKey: {$keyApp}"
          ),
        ));
        curl_multi_add_handle($curl, $multCurl[$result]);
        }

        $index = null;
        do {
          curl_multi_exec($curl,$index);
        } while ($index > 0);

        foreach ($multCurl as $k => $ch) {
          $res[$k] = curl_multi_getcontent($ch);
          curl_multi_remove_handle($curl, $ch);
          $arrPedidoId = json_decode($res[$k]);

          //var_dump($arrPedidoId->items);

          // confere se o array contem informações
          if ($arrPedidoId != null && $arrPedidoId->status != 'window-to-cancel') {

            //var_dump($arrPedidoId->paymentData->transactions[0]->isActive);
            //die;

            $pedidoId = (new DataOrderSellerDb())->setOrderId($arrPedidoId->orderId)
                                      ->setSequence($arrPedidoId->sequence)
                                      ->setStatus($arrPedidoId->status)
                                      ->setStatusDescription($arrPedidoId->statusDescription)
                                      ->setValue($arrPedidoId->value)
                                      ->setCreationDate($arrPedidoId->creationDate)
                                      ->setTotalValue($arrPedidoId->totals[0]->value)
                                      ->setDescountValue($arrPedidoId->totals[1]->value)
                                      ->setShippingValue($arrPedidoId->totals[2]->value)
                                      ->setClientFirstName($arrPedidoId->clientProfileData->firstName)
                                      ->setClientLastName($arrPedidoId->clientProfileData->lastName)
                                      ->setClientCpf($arrPedidoId->clientProfileData->document)
                                      ->setPhone($arrPedidoId->clientProfileData->phone)
                                      ->setAdressReceiverName($arrPedidoId->shippingData->address->receiverName)
                                      ->setPostalCode($arrPedidoId->shippingData->address->postalCode)
                                      ->setCity($arrPedidoId->shippingData->address->city)
                                      ->setState($arrPedidoId->shippingData->address->state)
                                      ->setStreet($arrPedidoId->shippingData->address->street)
                                      ->setNumberAdress($arrPedidoId->shippingData->address->number)
                                      ->setNeighborhood($arrPedidoId->shippingData->address->neighborhood)
                                      ->setComplementAdress($arrPedidoId->shippingData->address->complement)
                                      ->setDockId($arrPedidoId->shippingData->logisticsInfo[0]->deliveryIds[0]->dockId)
                                      ->setWarehouseId($arrPedidoId->shippingData->logisticsInfo[0]->deliveryIds[0]->warehouseId)
                                      ->setTransactionActive($arrPedidoId->paymentData->transactions[0]->isActive);


            $entityManager->persist($pedidoId);
            $entityManager->flush();

          }else {
            throw new \Exception("Pedido " .$id. " sem status para faturar", 404);
            //echo "<br>Erro pedido " .$id;
          }

        }
        curl_multi_close($curl);
    }

  }
}
