<?php

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

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

function orderSeller()
{
  global $entityManager;

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

  //conexão da lista
  $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();
  }

  if (!empty($array)) {
    $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]);

      insertComparacaoStatusDataOrderSellers($arrPedidoId, $entityManager, $id);
    }
    curl_multi_close($curl);
  }
}

function insertComparacaoStatusDataOrderSellers($arrPedidoId, $entityManager, $id)
{
  if ($arrPedidoId != null && $arrPedidoId->status != 'window-to-cancel' && $arrPedidoId->status != 'handling' && $arrPedidoId->status != 'payment-pending') {
    insertTableDataOrderSellers($arrPedidoId, $entityManager, $id);
  } else {
    echo "Pedido " . $id . " sem status para faturar";
  }
}

function insertTableDataOrderSellers($arrPedidoId, $entityManager, $id)
{

  $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();
}
