<?php
namespace App\Controllers\Seller;

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

use \App\Controllers\Container;

class SellerInvoiceNotification extends Container
{
  public function post(Request $request, Response $response, $args){
    // env.php define variaveis
    $token = getenv('token');
    $keyApp = getenv('appkey');

    $route = $request->getAttribute('route');
    $order = $route->getArgument('order');

    $entityManager = $this->container->get('em');
    $itemsRepository = $entityManager->getRepository('App\Models\Entity\ItemsOrderDb');
    $items = $itemsRepository->findAll();

    // lista o id dos itens
    foreach ($items as $i) {
      if ($order == $i->getOrderId()) {
        $idItem[] = $i->getId();
      }
    }

    if (empty($idItem)) {
      throw new \Exception("Nao foi possivel obter a lista de itens", 404);
    }

    // consulta db
    foreach ($idItem as $key => $i) {
      $itemDb[] = $itemsRepository->find($i);
    }
    // define informações dos itens para corpo do post vtex
    foreach ($itemDb as $i) {
      $arrItem[] = [
        'id' => $i->getSkuVtex(),
        'price' => $i->getPrice(),
        'quantity' => $i->getQuantity()
      ];
    }
    $itemsOrder = json_encode($arrItem);

    // transformando data do post
    date_default_timezone_set('America/Sao_Paulo');
    $dateTime = new \DateTime();
    $dia = $dateTime->format('Y-m-d\TH:i:s.u');

    //nf, código de rastreo e valor total
    $params = (object) $request->getParams();
    $invoiceNumber = $params->nf;
    $trackingNumber = $params->rastreio;
    $value = $params->value;

    $fetchURL = 'https://arsdesign.myvtex.com/api/oms/pvt/orders/'.$order.'/invoice';
    //var_dump($params->nf);
    //var_dump($params->rastreio);
    var_dump($dia);
    //var_dump($idItem);
    //var_dump($fetchURL);
    var_dump($value);
    var_dump(json_encode($arrItem));

    $curl = curl_init();

    curl_setopt_array($curl, array(
      CURLOPT_URL => $fetchURL,
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => false,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS =>"{\n\t\"invoiceNumber\":\"{$invoiceNumber}\",\n\t\"invoiceValue\":{$value},\n\t\"issuanceDate\":\"{$dia}\",\n\t\"invoiceUrl\":\"\",\n\t\"invoiceKey\":\"\",\n\t\"trackingNumber\":\"{$trackingNumber}\",\n\t\"trackingUrl\":\"\",\n\t\"courier\":\"Todos os CEPS\",\n\t\"items\": {$itemsOrder}",
      CURLOPT_HTTPHEADER => array(
        "Accept: application/json",
        "Content-Type: application/json",
        "X-VTEX-API-AppToken: {$token}",
        "X-VTEX-API-AppKey: {$keyApp}"
      ),
    ));

    $responseCurl = curl_exec($curl);
    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
      throw new \Exception("Nao foi possivel faturar pedido ".$err, 404);
    }

    //echo $responseCurl;
    $ordersRepository = $entityManager->getRepository('App\Models\Entity\DataOrderSellerDb');
    $ordersDB = $ordersRepository->findAll();

    foreach ($ordersDB as $key => $o) {
      if ($order == $o->getOrderId()) {
        $idOrder = $o->getId();
      }
    }

    $idOrderRepository = $ordersRepository->find($idOrder);

    var_dump($responseCurl);


    $idOrderRepository->setStatus('invoiced')
                      ->setStatusDescription('Faturado');

    $entityManager->persist($idOrderRepository);
    $entityManager->flush();

    var_dump($idOrderRepository);

    return $response->withStatus(201);
  }
}
