<?php

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

function altStatusOrders(){

  global $entityManager;

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

  //conexão pedidos sem seller ->null
  $ordersRepository = $entityManager->getRepository('App\Models\Entity\OrdersDb');
  $order = $ordersRepository->findAll();

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

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

  //verifica se o seller está null e se já está na lista de pedidos
  foreach ($order as $ord) {
    if ($ord->getSellerId() == null && in_array($ord->getOrderId(), $pedidoArray)) {
      $results[] = $ord->getOrderId();
    }
  }

  //var_dump($results);

  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.'/start-handling';
      $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 => "POST",
      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]);

      if (empty($arrPedidoId)) {
        throw new \Exception("Erro pedido " .$id, 404);
      }else {
        var_dump($arrPedidoId);
      }
    }
    curl_multi_close($curl);
  }

}
