<?php
namespace Incoviba\Controller\API\Ventas;

use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Incoviba\Controller\API\withJson;
use Incoviba\Common\Ideal\Controller;
use Incoviba\Common\Implement;
use Incoviba\Service;

class Facturas extends Controller
{
    use withJson;

    public function add(ServerRequestInterface $request, ResponseInterface $response, Service\Venta\Factura $facturaService): ResponseInterface
    {
        $data = $request->getParsedBody();
        $output = [
            'input' => $data,
            'factura' => null,
            'success' => false
        ];
        try {
            /*foreach (['cliente', 'unidades', 'detalle', 'total', 'uf'] as $key) {
                if (!isset($data[$key]) or empty($data[$key])) {
                    continue;
                }
                $data[$key] = json_decode($data[$key], true);
            }*/
            $data['cliente'] = json_decode($data['cliente'], true);
            $output['factura'] = $facturaService->add($data);
            $output['success'] = true;
        } catch (Implement\Exception\EmptyResult) {
            $output['error'] = 'No se pudo agregar la factura';
            return $this->withJson($response, $output, 400);
        }
        return $this->withJson($response, $output);
    }
}
