<?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 UpdateItemsDockCod 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');
        $codigoDeBarras = $route->getArgument('codigoDeBarras');
        $valorLocalizado = '';

        $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 ($codigoDeBarras == $s->getEan()) {
                $idStock = $s->getId();
                $skuVtex = $s->getSkuVtex();
                $cvto = $s->getOutletCvto();
                $valorLocalizado = 1;
                $valorDock = UpdateItemsDockCod::recebeValorStockDock($s, $dock);
            }
        }

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

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

        if ($valorLocalizado == 1) {
            $params = 1;
        }

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

        $stockCvto = intval($cvto);
        $resultadoParams = $valorDock + $params;
        $quantStock = intval($resultadoParams);
        $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 {

            $TotalProdutos = $idItem->getTotal();

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

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

            $novoValor = $TotalProdutos + $resultadoParams;
                    $newQuantity = $idItem->setTotal($novoValor);
                    $entityManager->persist($newQuantity);
                    $entityManager->flush();

            $executaUpdate = $stockHasRepositoryNew->createQueryBuilder('ud')->update()
                            ->set('ud.quantidade', $resultadoParams)
                            ->where('ud.id = :userId')
                            ->setParameter('userId', $idStockNew[0]['id'])
                            ->getQuery()->execute();
             return $response->withJson($responseCurl, 200)->withHeader('Content-type', 'application/json');               
            //inserir as colunas de docas do seller da tabela stock e add os metodos setters
            
        }
    }

    public function retirarProduto(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');
        $codigoDeBarras = $route->getArgument('codigoDeBarras');
        //$codigoDeBarras = '7909124212241';
        $valorLocalizado = '';

        $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 ($codigoDeBarras == $s->getEan()) {
                $idStock = $s->getId();
                $skuVtex = $s->getSkuVtex();
                $cvto = $s->getOutletCvto();
                $valorLocalizado = 1;
                $valorDock = UpdateItemsDockCod::recebeValorStockDock($s, $dock);
            }
        }

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

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

        if ($valorLocalizado == 1) {
            $params = 1;
        }

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

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

        $curl = curl_init();
        if ($newStock >= '0') {
            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}"
                ),
            ));
        } else if ($newStock < '1') {
            echo "Produto com estoque vazio";
        }
        $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 {
            $valorAbreExecucao = 1;
            $TotalProdutos = $idItem->getTotal();
            $novoValor = $TotalProdutos - $newStock;
            $newQuantity = $idItem->setTotal($novoValor);
            $entityManager->persist($newQuantity);
            $entityManager->flush();

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

            $queryIdStockNew = $stockHasRepositoryNew->createQueryBuilder('t')->select('t.id,t.quantidade')->where("t.idStock = '" . $idItem->getId() . "' and t.idUserSeller = '" . $idUserSellerNew[0]['id'] . "'")->getQuery();
            $idStockNew = $queryIdStockNew->getResult();
            $quantidadeStockMenor = $idStockNew[0]['quantidade'] - $params;
            $executaUpdate = $stockHasRepositoryNew->createQueryBuilder('ud')->update()
                            ->set('ud.quantidade', $quantidadeStockMenor)
                            ->where('ud.id = :userId')
                            ->setParameter('userId', $idStockNew[0]['id'])
                            ->getQuery()->execute();

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

    public function recebeValorStockDock($valorStockDock, $dock) {
        switch ($dock) {
            case 'acreSergio':
                return $valorStockDock->getAcreSergio();
                break;

            case 'outletCvto':
                return $valorStockDock->getOutletCvto();
                break;

            case 'forMen':
                return $valorStockDock->getForMen();
                break;

            case 'maiusculo':
                return $valorStockDock->getMaiusculo();
                break;

            case 'life':
                return $valorStockDock->getLife();
                break;

            case 'vestylle':
                return $valorStockDock->getVestylle();
                break;

            case 'haut':
                return $valorStockDock->getHaut();
                break;

            case 'dimazzo':
                return $valorStockDock->getDimazzo();
                break;

            case 'dimazzoArapongas':
                return $valorStockDock->getDimazzoArapongas();
                break;

            case 'bhPadilha':
                return $valorStockDock->getBhPadilha();
                break;

            case 'origem':
                return $valorStockDock->getOrigem();
                break;

            case 'emporio':
                return $valorStockDock->getEmporio();
                break;

            case 'abusiva':
                return $valorStockDock->getAbusiva();
                break;

            case 'signoriOtto':
                return $valorStockDock->getSignoriOtto();
                break;

            case 'gianottoModas':
                return $valorStockDock->getGianottoModas();
                break;

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

}
