<?php
namespace App\Controllers\Admin;

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

use \App\Models\Entity\Admin\ClientSeller;

use \App\Controllers\Container;

class ClientOrderList extends Container
{
  // lista todos os sellers parceiros
  public function all(Request $request, Response $response, $args){

    $entityManager = $this->container->get('em');
    $sellerRepository = $entityManager->getRepository('App\Models\Entity\Admin\ClientSeller');
    $sellers = $sellerRepository->findAll();

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

  //cadastra novo seller
  public function create(Request $request, Response $response, $args){
    $params = (object) $request->getParams();
    $entityManager = $this->container->get('em');

    // verifica se existe complemento de endereço
    if (isset($params->complementAdress)) {
      $seller = (new ClientSeller())->setName($params->name)
                                    ->setCnpj($params->cnpj)
                                    ->setWarehouseId($params->warehouseId)
                                    ->setDockId($params->warehouseId)
                                    ->setAgency($params->agency)
                                    ->setAccountNumber($params->accountNumber)
                                    ->setBank($params->bank)
                                    ->setAccountType($params->accountType)
                                    ->setBoss($params->boss)
                                    ->setState($params->state)
                                    ->setCity($params->city)
                                    ->setStreet($params->street)
                                    ->setPostalCode($params->postalCode)
                                    ->setComplementAdress($params->complementAdress)
                                    ->setNumberAdress($params->numberAdress)
                                    ->setNeighborhood($params->neighborhood)
                                    ->setPhone($params->phone)
                                    ->setWhatsapp($params->whatsapp)
                                    ->setEmail($params->email);
    }else {
      $seller = (new ClientSeller())->setName($params->name)
                                    ->setCnpj($params->cnpj)
                                    ->setWarehouseId($params->warehouseId)
                                    ->setDockId($params->warehouseId)
                                    ->setAgency($params->agency)
                                    ->setAccountNumber($params->accountNumber)
                                    ->setBank($params->bank)
                                    ->setAccountType($params->accountType)
                                    ->setBoss($params->boss)
                                    ->setState($params->state)
                                    ->setCity($params->city)
                                    ->setStreet($params->street)
                                    ->setPostalCode($params->postalCode)
                                    ->setNumberAdress($params->numberAdress)
                                    ->setNeighborhood($params->neighborhood)
                                    ->setPhone($params->phone)
                                    ->setWhatsapp($params->whatsapp)
                                    ->setEmail($params->email);
    }

    $entityManager->persist($seller);
    $entityManager->flush();

    return $response->withJson($seller, 201)->withHeader('Content-type', 'application/json');
  }

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

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

    $sellerRepository = $entityManager->getRepository('App\Models\Entity\Admin\ClientSeller');
    $seller = $sellerRepository->find($id);

    if (!$seller) {
      throw new \Exception("Nao existe", 404);
    }

    $seller->setAgency($request->getParam('agency'))
           ->setBank($request->getParam('bank'))
           ->setAccountType($request->getParam('accountType'))
           ->setBoss($request->getParam('boss'))
           ->setPostalCode($request->getParam('postalCode'))
           ->setState($request->getParam('state'))
           ->setCity($request->getParam('city'))
           ->setStreet($request->getParam('street'))
           ->setNumberAdress($request->getParam('numberAdress'))
           ->setComplementAdress($request->getParam('complementAdress'))
           ->setNeighborhood($request->getParam('neighborhood'))
           ->setPhone($request->getParam('phone'))
           ->setEmail($request->getParam('email'))
           ->setWhatsapp($request->getParam('whatsapp'));

     $entityManager->persist($seller);
     $entityManager->flush();

     return $response->withJson($seller, 201)->withHeader('Content-type', 'application/json');
  }

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

    $entityManager = $this->container->get('em');
    $sellerRepository = $entityManager->getRepository('App\Models\Entity\Admin\ClientSeller');
    $sellers = $sellerRepository->find($id);

    if (!$sellers) {
      throw new \Exception("Nao existe", 404);
    }

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

  }

  // lista pedidos por seller
  public function get(Request $request, Response $response, $args){
    $route = $request->getAttribute('route');
    $warehouseId = $route->getArgument('warehouseId');

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

    foreach ($orderSeller as $s) {
      if ($warehouseId == $s->getWarehouseId()) {
        $idSeller[] = $s->getId();
      }
    }

    if (empty($idSeller)) {
      throw new \Exception("Seller sem pedidos", 404);
    }

    foreach ($idSeller as $id) {
      $client[] = $orderSellerRepository->find($id);
    }

    rsort($client);

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

  // consulta por data
  public function dateseller(Request $request, Response $response, $args){
    $route = $request->getAttribute('route');
    $warehouseId = $route->getArgument('warehouseId');
    $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.warehouseId = :dock AND u.creationDate BETWEEN :start AND :final";

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

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

    $results = $query->getResult();

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

  }
}
