<?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\ItemsOrderDb;
use \App\Controllers\Container;

class ItemsOrderDBController 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');
    $ordSellerRepository = $entityManager->getRepository('App\Models\Entity\OrdersDb');
    $orderSeller = $ordSellerRepository->findAll();

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

    //item de cada pedidos
    $itemsRepository = $entityManager->getRepository('App\Models\Entity\ItemsOrderDb');
    $items = $itemsRepository->findAll();

    foreach ($items as $it) {
      $itemsArray[] = $it->getOrderId();
    }

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

    //var_dump($results);

    if (!empty($results)) {
      $stockRepository = $entityManager->getRepository('App\Models\Entity\StockDb');
      $stock = $stockRepository->findAll();

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

      foreach ($results as $result => $id) {
        $fetchURL = 'https://arsdesign.myvtex.com/api/oms/pvt/orders/'.$id;
        //$fetchURL = 'https://arsdesign.myvtex.com/api/oms/pvt/orders/959160993202-01';
        $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]);

        if (!$arrPedidoId == null) {
          foreach ($arrPedidoId->items as $key => $item) {
            //var_dump($arrPedidoId->items[$key]->price);
            //var_dump($arrPedidoId->items[$key]->priceTags[0]->value);

            //$priceTags = $arrPedidoId->items[$key]->priceTags[0];


            if (empty($arrPedidoId->items[$key]->priceTags[0])) {
              $notDiscount = 0;
              $itemsId = (new ItemsOrderDb())->setOrderId($arrPedidoId->orderId)
                                             ->setSkuVtex($arrPedidoId->items[$key]->id)
                                             ->setEan($arrPedidoId->items[$key]->ean)
                                             ->setProductName($arrPedidoId->items[$key]->name)
                                             ->setQuantity($arrPedidoId->items[$key]->quantity)
                                             ->setPrice($arrPedidoId->items[$key]->price)
                                             ->setDiscountPrice($notDiscount)
                                             ->setRefId($arrPedidoId->items[$key]->refId)
                                             ->setImageUrl($arrPedidoId->items[$key]->imageUrl)
                                             ->setDetailUrl($arrPedidoId->items[$key]->detailUrl);

            }else {
              $itemsId = (new ItemsOrderDb())->setOrderId($arrPedidoId->orderId)
                                           ->setSkuVtex($arrPedidoId->items[$key]->id)
                                           ->setEan($arrPedidoId->items[$key]->ean)
                                           ->setProductName($arrPedidoId->items[$key]->name)
                                           ->setQuantity($arrPedidoId->items[$key]->quantity)
                                           ->setPrice($arrPedidoId->items[$key]->price)
                                           ->setDiscountPrice($arrPedidoId->items[$key]->priceTags[0]->value)
                                           ->setRefId($arrPedidoId->items[$key]->refId)
                                           ->setImageUrl($arrPedidoId->items[$key]->imageUrl)
                                           ->setDetailUrl($arrPedidoId->items[$key]->detailUrl);
        }

             $entityManager->persist($itemsId);
             $entityManager->flush();
          }

        }else {
          throw new \Exception("Sem item no pedido " .$id, 404);
        }

      curl_multi_close($curl);
      }

    }

  }
}
