<?php
namespace App\Controllers\Admin;

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

use \App\Controllers\Container;

class OrdersList extends Container
{
  // lista todos os pedidos de todos os sellers
  public function all(Request $request, Response $response, $args){
    $entityManager = $this->container->get('em');
    $orderRepository = $entityManager->getRepository('App\Models\Entity\Admin\OrderSeller');
    $orders = $orderRepository->findBy([], ['id'=>'DESC']);

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

  // pega pedido por parametro orderId
  public function get(Request $request, Response $response, $args){
    $route = $request->getAttribute('route');
    $id = $route->getArgument('id');

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

    foreach ($orders as $o) {
      if ($id == $o->getOrderId()) {
        $idOrder[] = $o->getId();
      }
    }

    if (empty($idOrder)) {
      throw new \Exception("Este pedido nao existe", 404);
    }

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

    if (empty($ord)) {
      throw new \Exception("Este pedido nao existe", 404);
    }

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