<?php
namespace App\Controllers\Admin;

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

use \App\Controllers\Container;

class ItemsList extends Container
{
  public function get(Request $request, Response $response, $args){
    $route = $request->getAttribute('route');
    $order = $route->getArgument('order');

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

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

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

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

    if (empty($ord)) {
      throw new \Exception("Erro ao listar itens", 404);
    }

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