<?php

namespace App\Controllers\DB;

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

//use \App\Models\Entity\StockDb;
use \App\Models\Entity\ItemsOrderDb;

use \App\Controllers\Container;

class StatusStockDBController extends Container
{
  public function get(Request $request, Response $response, $args){
    $entityManager = $this->container->get('em');

    $itemsOrderRepository = $entityManager->getRepository('App\Models\Entity\ItemsOrderDb');
    $itemsOrder = $itemsOrderRepository->findAll();

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

    $ordersRepository = $entityManager->getRepository('App\Models\Entity\DataOrderSellerDb');
    $ord = $ordersRepository->findAll();

    // lista os itens sem status de estoque
    foreach ($itemsOrder as $i) {
      if ($i->getStatusStock() == null) {
        $skuVtex[] = $i->getSkuVtex();
        $orderId[] = $i->getOrderId();
        $idItemsOrder[] = $i->getId();
      }
    }

    if (empty($skuVtex)) {
      throw new \Exception("Sem itens para inserir", 404);
    }

    //var_dump($skuVtex);

    // compara as duas tabelas de produtos
    foreach ($skuVtex as $sku) {
      foreach ($stock as $s) {
        if ($sku == $s->getSkuVtex()) {
          $id[] = $s->getId();
        }
      }
    }
    //var_dump($id);

    //consulta por id
    foreach ($id as $key => $i) {
      $idItem[] = $stockRepository->find($i);
    }

    //var_dump($idItem);

    //compara as tabelas
    foreach ($orderId as $o) {
      foreach ($ord as $od) {
        if ($o == $od->getOrderId()) {
          $idOrder[] = $od->getId();
        }
      }
    }

    if (empty($idOrder)) {
      throw new \Exception("Sem pedidos", 404);
    }

    //consulta nome da doca
    foreach ($idOrder as $key => $iO) {
      $idOrd[] = $ordersRepository->find($iO);
    }

    //var_dump($idOrd);

    foreach ($idOrd as $key => $i) {
      switch ($i->getWarehouseId()) {
        case 'acreSergio':
        $stockDock = $idItem[$key]->getAcreSergio();
        $statusStock = $idItemsOrder[$key];
        $newStatus = $itemsOrderRepository->find($statusStock);

        $newStatus->setStatusStock($stockDock);

        var_dump($stockDock);

        $entityManager->persist($newStatus);
        $entityManager->flush();
          break;

        case 'Etq_Cmaleao':
        $stockDock = $idItem[$key]->getQuantitySeller();
        $statusStock = $idItemsOrder[$key];
        $newStatus = $itemsOrderRepository->find($statusStock);

        $newStatus->setStatusStock($stockDock);

        var_dump($stockDock);

        $entityManager->persist($newStatus);
        $entityManager->flush();
          break;

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

  }
}
