<?php
namespace App\Controllers\Seller;

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

use \App\Controllers\Container;

class SellerOrderList extends Container
{
  //lista pedidos com parametro do seller get{warehouserId}
  public function get(Request $request, Response $response, $args){
    $route = $request->getAttribute('route');
    $id = $route->getArgument('id');

    //var_dump($id);

    $entityManager = $this->container->get('em');
    $ordersRepository = $entityManager->getRepository('App\Models\Entity\DataOrderSellerDb');
    $order = $ordersRepository->findAll();

    foreach ($order as $key => $ord) {
      if ($id == $ord->getWarehouseId()) {
        $orderSeller[] = $ord->getId();
      }
    }
    //var_dump($orderSeller);
    if (empty($orderSeller)) {
      throw new \Exception("Sem pedidos", 404);
    }

    foreach ($orderSeller as $key => $o) {
      $idOrder[] = $ordersRepository->find($o);
    }

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

  }
  
  //lista pedido expecifico com parametro order{id}
  public function order(Request $request, Response $response, $args){
    $route = $request->getAttribute('route');
    $dock = $route->getArgument('id');
    $idOrder = $route->getArgument('order');

    $entityManager = $this->container->get('em');
    $orderSellerRepository = $entityManager->getRepository('App\Models\Entity\DataOrderSellerDb');
    $ordSeller = $orderSellerRepository->findAll();

    foreach ($ordSeller as $ord) {
      if ($dock == $ord->getWarehouseId() && $idOrder == $ord->getOrderId()) {
        $idDB = $ord->getId();
      }
    }

    if (empty($idDB)) {
      throw new \Exception("Nao existe este pedido", 404);
    }

    $idSellerOrder = $orderSellerRepository->find($idDB);

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

//lista itens com orderId como parametro items{orderId}
  public function items(Request $request, Response $response, $args){
    $route = $request->getAttribute('route');
    $idOrder = $route->getArgument('order');

    $entityManager = $this->container->get('em');
    $itemsRepository = $entityManager->getRepository('App\Models\Entity\ItemsOrderDb');
    $items = $itemsRepository->findAll();

    foreach ($items as $i) {
      if ($idOrder == $i->getOrderId()) {
        $idOrderItem[] = $i->getId();
      }
    }

    if (empty($idOrderItem)) {
      throw new \Exception("Nao existe item no pedido", 404);
    }

    foreach ($idOrderItem as $key => $item) {
      $idItem[] = $itemsRepository->find($item);
    }

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