<?php
namespace Incoviba\Controller\Ventas;

use Incoviba\Common\Implement\Exception\EmptyResult;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Incoviba\Common\Alias\View;
use Incoviba\Service;

class Cierres
{
    public function __invoke(ServerRequestInterface $request, ResponseInterface $response, View $view): ResponseInterface
    {
        return $view->render($response, 'ventas.cierres.list');
    }
    public function show(ServerRequestInterface $request, ResponseInterface $response, View $view, Service\Venta\Cierre $service, int $cierre_id): ResponseInterface
    {
        $cierre = $service->getById($cierre_id);
        return $view->render($response, 'ventas.cierres.show', compact('cierre'));
    }

    public function proyecto(ServerRequestInterface $request, ResponseInterface $response, Service\Venta\Cierre $service): ResponseInterface
    {
        $body = $request->getBody();
        $json = json_decode($body->getContents());
        $proyecto_id = $json->proyecto_id;
        $output = ['total' => 0];
        try {
            $cierres = $service->getByProyecto($proyecto_id);
            $output['cierres'] = $cierres;
            $output['total'] = count($cierres);
        } catch (EmptyResult) {}
        $response->getBody()->write(json_encode($output));
        return $response->withHeader('Content-Type', 'application/json');
    }
}
