<?php

namespace App\Controllers\Seller\Warehouse;

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use \App\Controllers\Container;
use App\Models\Entity\StockHasUserSeller;
use App\Models\Entity\Seller\UserSeller;

class UpdateItemsDock extends Container {

    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();

        $userSellerNew = $entityManager->getRepository('App\Models\Entity\Seller\UserSeller');

        $stockHasRepositoryNew = $entityManager->getRepository('App\Models\Entity\StockHasUserSeller');

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

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

        if ($cvto == 0 || $cvto == null) {
            $cvto = 0;
        }

        $params = $request->getParam('stock'); //grava na tabela do estoque

        $idItem = $stockRepository->find($idStock);

        $stockCvto = intval($cvto);
        $quantStock = intval($params);
        $newStock = $quantStock; //vai pra vtex

        $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\": {$newStock},\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 {

            $valor = $idItem->getTotal();

            if ($newStock > $params) {
                $restante = $params - $newStock;
                $valorRestante = - ($restante);
                $novoValor = $valor - $valorRestante;

                $newQuantity = $idItem->setTotal($novoValor);
                $entityManager->persist($newQuantity);
                $entityManager->flush();
            }

            if ($newStock < $params) {
                $restante = $params - $newStock;
                $novoValor = $valor + $restante;

                $newQuantity = $idItem->setTotal($novoValor);
                $entityManager->persist($newQuantity);
                $entityManager->flush();
            }

            $queryIdUserSellerNew = $userSellerNew->createQueryBuilder('t')->select('t.id')->where("t.warehouseId = '" . $dock . "'")->getQuery();
            $idUserSellerNew = $queryIdUserSellerNew->getResult();

            $queryIdStockNew = $stockHasRepositoryNew->createQueryBuilder('t')->select('t.id')->where("t.idStock = '" . $idItem->getId() . "' and t.idUserSeller = '" . $idUserSellerNew[0]['id'] . "'")->getQuery();
            $idStockNew = $queryIdStockNew->getResult();

            //inserir as colunas de docas do seller da tabela stock e add os metodos setters

            $executaUpdate = $stockHasRepositoryNew->createQueryBuilder('ud')->update()
                            ->set('ud.quantidade', $newStock)
                            ->where('ud.id = :userId')
                            ->setParameter('userId', $idStockNew[0]['id'])
                            ->getQuery()->execute();

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

    public function somaFabricaLojista($quantStock, $stockCvto) {
        return $quantStock + $stockCvto;
    }

}
