<?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;
  }

  public function orderdata(Request $request, Response $response, $args){
    $route = $request->getAttribute('route');
    $start = $route->getArgument('start');
    $end = $route->getArgument('end');

    $today = new \DateTime();

    if ($end > $today->format('Y-m-d')) {
      throw new \Exception("data final maior que a data de hoje", 404);
    }

    if ($end < $start) {
      throw new \Exception("data final e menor que data inicial", 404);
    }
    
    //se data final for igual hoje, adiciona um dia para BETWEEN executar a query
    if ($end == $today->format('Y-m-d')) {
      $end = date('Y-m-d', strtotime($end . "+1 days"));
    }

    $dql = "SELECT u FROM App\Models\Entity\DataOrderSellerDb u WHERE u.creationDate BETWEEN :start AND :final";

    $entityManager = $this->container->get('em');
    $query = $entityManager->createQuery($dql);

    $query->setParameters([
      'start' => $start,
      'final' => $end
    ]);

    $results = $query->getResult();

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

  }
}
