<?php
namespace App\Controllers\Seller;

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

//use Doctrine\ORM\Tools\Pagination\Paginator;

use \App\Controllers\Container;

class SellerWarehouse extends Container
{
  // lista todos os  produtos
  public function all(Request $request, Response $response, $args){
    //$route = $request->getAttribute('route');
    //$id = $route->getArgument('id');

    $entityManager = $this->container->get('em');
    $stockRepository = $entityManager->getRepository('App\Models\Entity\StockDb');
    $products = $stockRepository->findAll();

    /*
    $dql = "SELECT cid FROM App\Models\Entity\StockDb cid";
    $query = $entityManager->createQuery($dql)
                          ->setFirstResult($id)//passar variavel por url inicia com 0
                          ->setMaxResults(20);

    $paginator = new Paginator($query, $fetchJoinCollection = true);

    $c = count($paginator);
    foreach ($paginator as $p) {
      $products[] = $p;
    }
*/
    if (empty($products)) {
      throw new \Exception("Sem itens", 404);
    }


    $return = $response->withJson($products, 200)->withHeader('Content-type', 'application/json');
    return $return;

  }

  public function get(Request $request, Response $response, $args){

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

    $entityManager = $this->container->get('em');
    $stockRepository = $entityManager->getRepository('App\Models\Entity\StockDb');
    $stock = $stockRepository->findAll();

    foreach ($stock as $s) {
      if ($item == $s->getEan()) {
        $idStock = $s->getId();
      }
    }

    if (empty($idStock)) {
      throw new \Exception("Item nao cadastrado na base", 404);
    }

    switch ($dock) {
      case 'acreSergio':
        $idItem = $stockRepository->find($idStock);
        return $response->withJson($idItem, 200)->withHeader('Content-type', 'application/json');
        break;

      case 'Etq_Cmaleao':
        $idItem = $stockRepository->find($idStock);
        return $response->withJson($idItem, 200)->withHeader('Content-type', 'application/json');
        break;

      default:
        throw new \Exception("Nao existe doca", 404);
        break;
    }
  }

  //envia estoque para o mysql do seller
  public function up(Request $request, Response $response, $args){

    // env.php define variaveis
    $token = getenv('token');
    $appKey = getenv('appkey');

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

    $entityManager = $this->container->get('em');
    $stockRepository = $entityManager->getRepository('App\Models\Entity\StockDb');
    $stock = $stockRepository->findAll();

    foreach ($stock as $s) {
      if ($item == $s->getEan()) {
        $idStock = $s->getId();
        $skuVtex = $s->getSkuVtex();
      }
    }

    if (empty($idStock)) {
      throw new \Exception("Item nao cadastrado na base", 404);
    }

    $params = $request->getParam('stock');

    //inserir as colunas de docas do seller da tabela stock e add os metodos setters
    switch ($dock) {
      case 'acreSergio':
        $idItem = $stockRepository->find($idStock);
        $quantity = $idItem->setAcreSergio($params); //pegar do front
        $quant = $params;//pegar do front

        $curl = curl_init();

        curl_setopt_array($curl, array(
          CURLOPT_URL => "https://logistics.myvtex.com/api/logistics/pvt/inventory/skus/$skuVtex/warehouses/$dock?an=arsdesign",
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => "",
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => false,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => "PUT",
          CURLOPT_POSTFIELDS =>"{\n    \"unlimitedQuantity\": false,\n    \"dateUtcOnBalanceSystem\": null,\n    \"quantity\": {$quant},\n    \"timeToRefill\": 0\n}",
          CURLOPT_HTTPHEADER => array(
            "Content-Type: application/json; charset=utf-8",
            "Accept: application/json",
            "X-VTEX-API-AppToken: {$token}",
            "X-VTEX-API-AppKey: {$appKey}"
          ),
        ));

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

        curl_close($curl);

        if ($err) {
          throw new \Exception("Nao foi possivel atualizar o item {$err}", 404);
        } else {
          $entityManager->persist($quantity);
          $entityManager->flush();
          $return = $response->withJson($responseCurl, 200)->withHeader('Content-type', 'application/json');
          return $return;
        }

        break;

      case 'Etq_Cmaleao':
        $idItem = $stockRepository->find($idStock);
        $quantity = $idItem->setQuantitySeller($params); //pegar do front
        $quant = $params;//pegar do front

        $curl = curl_init();

        curl_setopt_array($curl, array(
          CURLOPT_URL => "https://logistics.myvtex.com/api/logistics/pvt/inventory/skus/$skuVtex/warehouses/$dock?an=arsdesign",
          CURLOPT_RETURNTRANSFER => true,
          CURLOPT_ENCODING => "",
          CURLOPT_MAXREDIRS => 10,
          CURLOPT_TIMEOUT => 0,
          CURLOPT_FOLLOWLOCATION => false,
          CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
          CURLOPT_CUSTOMREQUEST => "PUT",
          CURLOPT_POSTFIELDS =>"{\n    \"unlimitedQuantity\": false,\n    \"dateUtcOnBalanceSystem\": null,\n    \"quantity\": {$quant},\n    \"timeToRefill\": 0\n}",
          CURLOPT_HTTPHEADER => array(
            "Content-Type: application/json; charset=utf-8",
            "Accept: application/json",
            "X-VTEX-API-AppToken: {$token}",
            "X-VTEX-API-AppKey: {$appKey}"
          ),
        ));

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

        curl_close($curl);

        if ($err) {
          throw new \Exception("Nao foi possivel atualizar o item {$err}", 404);
        } else {
          $entityManager->persist($quantity);
          $entityManager->flush();
          $return = $response->withJson($responseCurl, 200)->withHeader('Content-type', 'application/json');
          return $return;
        }

        break;


      default:
        throw new \Exception("Nao existe doca", 404);
        break;
    }

  }
}
