<?php

//Este cron ele pega todos as quantidades dos produtos das docas no banco de dados e envia para a Vtex

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
ini_set('memory_limit', '256M');
error_reporting(E_ALL);
include_once '/home/clubcvtocombr/public_html' . '/split/api/cron/config.php';
include_once '/home/clubcvtocombr/public_html' . '/split/api/env.php';
include_once '/home/clubcvtocombr/public_html' . '/split/api/cron/log.php';

use App\Models\Entity\StockDb;
use App\Models\Entity\StockDbNew;
use App\Models\Entity\Seller\UserSeller;
use App\Models\Entity\StockHasUserSeller;

function sobeStockParaVtexTwo() {

    $token = getenv('token');
    $keyVtex = getenv('appkey');

    global $entityManager;

    $stockRepository = $entityManager->getRepository('App\Models\Entity\StockDb');
    $stock = $stockRepository->findAll();
    $produtos = count($stock);

    $stockRepositoryNew = $entityManager->getRepository('App\Models\Entity\StockDbNew');
    $stockNew = $stockRepositoryNew->findAll();
    $produtosNew = count($stockNew);

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

    $userSellerNew = $entityManager->getRepository('App\Models\Entity\Seller\UserSeller');
    $userNew = $userSellerNew->findAll();
    $lojistasNew = count($userNew);
/*
    $teste = '4586';
    $idus = '2';

$query = $stockHasRepositoryNew->createQueryBuilder('t')->select('t.quantidade')->where("t.idStock = '".$teste."' and t.idUserSeller = '".$idus."'")->getQuery();
$usersdd = $query->getResult();
    
    echo $usersdd[0]['quantidade']." atestexxx<br>";

    exit;
    */

    //$produtos = 2; 

    for ($z = 0; $z < $produtosHasNew; $z++) {
        $idLojista = $stockHasNew[$z]->getIdUserSeller();
        $idProduto = $stockHasNew[$z]->getIdStock();
        $quantidadeProduto = $stockHasNew[$z]->getQuantidade();
        $userNewOne = $userSellerNew->find($idLojista);
        $skuVtexOne = $stockRepositoryNew->find($idProduto);
        $skuProduto = $skuVtexOne->getSkuVtex();
        $docaLojista = $userNewOne->getWarehouseId();

        linkSobeParaVtex($token, $keyVtex, $skuProduto, $quantidadeProduto, $docaLojista);
    }
}

function buscaNaVtexProdutoAtivo($token, $key, $skuVtex) {
    $curl = curl_init();
    curl_setopt_array($curl, array(
        CURLOPT_URL => 'https://arsdesign.vteximg.com.br/api/catalog_system/pvt/sku/stockkeepingunitbyid/' . $skuVtex,
        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; charset=utf-8",
            "X-VTEX-API-AppToken: {$token}",
            "X-VTEX-API-AppKey: {$key}"
        ),
    ));

    $response = curl_exec($curl);
    $respostaCurlOutput = json_decode($response, true);



    $err = curl_error($curl);

    curl_close($curl);

    if ($err) {
        //echo "cURL Error #:" . $err . " - " . $skuVtex . "<br>";
    } else {
        //echo "Ok " . $skuVtex . " - " . $response . "<br>";
        //echo "Ok " . "<br>";
        return $respostaCurlOutput["IsActive"];
    }
}

;

function linkSobeParaVtex($token, $key, $skuVtex, $quantidade, $doca) {

    $produtoAtivo = buscaNaVtexProdutoAtivo($token, $key, $skuVtex);

    if (empty($quantidade)) {
        $quantidade = 0;
    }

    if ($produtoAtivo == 1) {
        $url = "https://logistics.myvtex.com/api/logistics/pvt/inventory/skus/$skuVtex/warehouses/$doca?an=arsdesign";



        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 120,
            CURLOPT_FOLLOWLOCATION => false,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "PUT",
            CURLOPT_POSTFIELDS => "{\n    \"unlimitedQuantity\": false,\n    \"dateUtcOnBalanceSystem\": null,\n    \"quantity\": {$quantidade},\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: {$key}"
            ),
        ));

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

        curl_close($curl);

        if ($err) {
            //echo "cURL Error #:" . $err . " - " . $skuVtex . "<br>";
        } else {
            //echo "Ok " . $skuVtex . " - " . $response . "<br>";
            //echo date('h:i:s') . '<br />';
        }
    }
}

function stockProducts() {
    global $entityManager;

    $token = getenv('token');
    $keyApp = getenv('appkey');

    $stockDbAdminRepository = $entityManager->getRepository('App\Models\Entity\StockDb');
    $stockDbAdmin = $stockDbAdminRepository->findAll();


    if (!empty($stockDbAdmin)) {

        $stockDBAdminArraySkuVtex = retornarCodigoVtexPorTamanhoDoProduto($stockDbAdmin);

        foreach ($stockDBAdminArraySkuVtex as $stockDbAdminSkuVtexValue) {

            $arrayProductIdVtex = buscaProductIdVtexUsandoSkuVtexDoDbAdmin($entityManager, $stockDbAdminRepository, $stockDbAdmin, $stockDbAdminSkuVtexValue, $token, $keyApp);
        }
    }
}

function retornarCodigoVtexPorTamanhoDoProduto($stockDbAdmin) {
    foreach ($stockDbAdmin as $stockDbAdminValue) {

        $stockDBAdminArraySkuVtex[] = $stockDbAdminValue->getSkuVtex();
    }

    return $stockDBAdminArraySkuVtex;
}

function buscaProductIdVtexUsandoSkuVtexDoDbAdmin($entityManager, $stockDbAdminRepository, $stockDbAdmin, $stockDbAdminSkuVtexValue, $token, $keyApp) {


    foreach ($stockDbAdmin as $key => $valueStockDbAdmin) {
        $curl = curl_init();

        if (!empty($valueStockDbAdmin->getSkuVtex())) {

            curl_setopt_array($curl, array(
                CURLOPT_URL => 'https://arsdesign.vteximg.com.br/api/catalog_system/pvt/sku/stockkeepingunitbyid/' . $valueStockDbAdmin->getSkuVtex(),
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_ENCODING => "",
                CURLOPT_MAXREDIRS => 10,
                CURLOPT_TIMEOUT => 120,
                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: {$keyApp}"
                ),
            ));
            $respostaCurlInput = curl_exec($curl);

            $respostaCurlOutput = json_decode($respostaCurlInput, true);

            //echo json_encode($respostaCurlOutput);
            //echo json_encode($respostaCurlOutput['Id']);

            /* if((!empty($valueStockDbAdmin->getSkuVtex()))&&(empty($valueStockDbAdmin->getSizeProduct()))){ 

              $stockDBNew->setId($valueStockDbAdmin->getId());
              $stockDBNew->setSkuVtex($valueStockDbAdmin->getSkuVtex());
              $stockDBNew->setNameProduct($productNameVtexString);
              $stockDBNew->setSizeProduct($valueStockDbAdmin->getSizeProduct());
              $stockDBNew->setSkuBhan($valueStockDbAdmin->getSkuBhan());
              $stockDBNew->setCodGroup($valueStockDbAdmin->getCodGroup());
              $stockDBNew->setEan($valueStockDbAdmin->getEan());
              $stockDBNew->setImgProduct($valueStockDbAdmin->getImgProduct());
              $stockDBNew->setTotal($valueStockDbAdmin->getTotal());
              $stockDBNew->setAcreSergio($valueStockDbAdmin->getAcreSergio());
              $stockDBNew->setOutletCvto($valueStockDbAdmin->getOutletCvto());
              $stockDBNew->setForMen($valueStockDbAdmin->getForMen());
              $stockDBNew->setMaiusculo($valueStockDbAdmin->getMaiusculo());
              $stockDBNew->setLife($valueStockDbAdmin->getLife());
              $stockDBNew->setVestylle($valueStockDbAdmin->getVestylle());
              $stockDBNew->setHaut($valueStockDbAdmin->getHaut());
              $stockDBNew->setDimazzo($valueStockDbAdmin->getDimazzo());
              $stockDBNew->setBhPadilha($valueStockDbAdmin->getBhPadilha());
              $stockDBNew->setOrigem($valueStockDbAdmin->getOrigem());
              $stockDBNew->setEmporio($valueStockDbAdmin->getEmporio());
              $stockDBNew->setAbusiva($valueStockDbAdmin->getAbusiva());
              $stockDBNew->setSignoriOtto($valueStockDbAdmin->getSignoriOtto());

              $stockDBNew->setProductIdVtex($productIdVtexString);

              $entityManager->merge($stockDBNew);


              $entityManager->flush();
              //var_dump($stockDBNew);



              } */
        }

        curl_close($curl);
    }
}
