<?php

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

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


function orders()
{
  global $entityManager;

  $token = getenv('token');
  $key = getenv('appkey');

  $curl = curl_init();

  curl_setopt_array($curl, array(
    //CURLOPT_URL => "https://arsdesign.myvtex.com/api/oms/pvt/orders/956060093856-01",
    //CURLOPT_URL => "https://arsdesign.myvtex.com/api/oms/pvt/orders?f_sellerNames=Convicto",
    //CURLOPT_URL => "https://arsdesign.myvtex.com/api/oms/pvt/orders",
    CURLOPT_URL => "https://arsdesign.myvtex.com/api/oms/pvt/orders?f_creationDate=creationDate:[2017-08-16T00:00:00.000Z+TO+2050-08-16T23:59:59.999Z]",
    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_HTTPHEADER => array(
      "Accept: application/json",
      "Content-Type: application/json",
      "X-VTEX-API-AppToken: {$token}",
      "X-VTEX-API-AppKey: {$key}"
    ),
  ));

  $responseCurl = curl_exec($curl);

  $err = curl_error($curl);

  curl_close($curl);

  if ($err) {
    throw new \Exception($err, 404);
    exit;
  }

  $arrJson = json_decode($responseCurl);

  $listaPedidosVtexInteira = $arrJson->list;

  $quarentaDiasAtras = date('Y-m-d', strtotime("-40 days"));

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

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

  $listaIdPedidosVtexAtuais = listaIdPedidosVtexAtuaisCondicao($listaPedidosVtexInteira, $quarentaDiasAtras);

  $idOrder = listaIdPedidosBancoAdmin($order);
  
  if (!empty($listaIdPedidosVtexAtuais)) {
    $result = array_diff($listaIdPedidosVtexAtuais, $idOrder);
    $chaveArray = array_keys($result);
  } else {
    $result = null;
  }

  atualizarPedidosBancoAdmin($orderSellerDB,$ordersRepositorySellerDB, $listaPedidosVtexInteira, $entityManager);
  inserirPedidosBancoAdmin($result, $chaveArray, $entityManager);
}

function atualizarPedidosBancoAdmin($orderSellerDB,$ordersRepositorySellerDB, $listaPedidosVtexInteira, $entityManager)
{
  
  
  foreach ($listaPedidosVtexInteira as $valueVtex) {
    foreach ($orderSellerDB as $valueSellerDb) {

      updateStatusAndStatusDescription($entityManager,$ordersRepositorySellerDB,$valueVtex,$valueSellerDb);

    }

  }
}

function updateStatusAndStatusDescription($entityManager,$ordersRepositorySellerDB,$valueVtex,$valueSellerDb){
  if (($valueSellerDb->getOrderId() == $valueVtex->{"orderId"}) && ($valueSellerDb->getStatus() != $valueVtex->{"status"})) {
        $orderSellerDBOneId = $ordersRepositorySellerDB->find($valueSellerDb->getId());

        $orderSellerDBOneId->setStatus($valueVtex->{"status"});
        $orderSellerDBOneId->setStatusDescription($valueVtex->{"statusDescription"});

        $entityManager->merge($orderSellerDBOneId);

        $entityManager->flush();
      }
}

function inserirPedidosBancoAdmin($result, $chaveArray, $entityManager)
{
  if (!empty($result)) {
    foreach ($chaveArray as $key) {
    
      $pedido = (new OrdersDb())->setOrderId($result[$key]);
      $entityManager->persist($pedido);
    
    }
    $entityManager->flush();
    return true;
  }
}


function listaIdPedidosBancoAdmin($order)
{

  foreach ($order as $banco) {
    $idOrder[] = $banco->getOrderId();
  }

  return $idOrder;
}

function listaIdPedidosVtexAtuaisCondicao($listaPedidosVtexInteira, $quarentaDiasAtras)
{
  foreach ($listaPedidosVtexInteira as $ord) {
    if ($ord->creationDate > $quarentaDiasAtras) {
      $listaIdPedidosVtexAtuais[] = $ord->orderId;
    }
  }

  if (!empty($listaIdPedidosVtexAtuais)) {
    return $listaIdPedidosVtexAtuais;
  }
}
