<?php
/*  Essa função lista os pedidos e deixa com status null no db.
    O que for null será buscado pela função OrdersDBController.
    Depois o seller é adcionado e o pedido não é mais buscado
*/
namespace App\Controllers\DB;

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

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

class OrdersDBController extends Container
{
  public function all(Request $request, Response $response, $args){

    //variaveis ->env.php
    $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?orderBy=orderId,desc",
      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);
    //var_dump($responseCurl);
    $err = curl_error($curl);

    curl_close($curl);

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

    $arrJson = json_decode($responseCurl);
    //var_dump($arrJson);

    $arr = $arrJson->list;

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

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


    //$idOrder = array_column($arr , 'orderId');
    //var_dump($arrJson);

    foreach ($arr as $ord) {
      if ($ord->creationDate > $menosDoisDias) {
        $array[] = $ord->orderId;
      }
    }


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

    $result = array_diff($array, $idOrder);


    $chaveArray = array_keys($result);
    //var_dump($result);
    //var_dump($chaveArray);

    //$contadorArray = count($result);
    //echo $contadorArray;

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

    $entityManager->flush();

  }
}
