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

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

class Movimientos extends Ideal\Controller
{
    use withJson;

    public function detalles(ServerRequestInterface $request, ResponseInterface $response,
                             Service\Movimiento     $movimientoService,
                             Repository\CentroCosto $centroCostoRepository, int $movimiento_id): ResponseInterface
    {
        $body = $request->getParsedBody();
        $output = [
            'movimiento_id' => $movimiento_id,
            'input' => $body,
            'status' => false,
            'movimiento' => null,
            'centro' => null,
            'detalle' => ''
        ];
        try {
            $movimiento = $movimientoService->getById($movimiento_id);
            $output['movimiento'] = $movimiento;
            $data = [];
            if (isset($body['centro_id'])) {
                $centro = $centroCostoRepository->fetchById($body['centro_id']);
                $data['centro_costo_id'] = $centro->id;
            }
            if (isset($body['detalle'])) {
                $data['detalle'] = $body['detalle'];
            }
            $movimientoService->setDetalles($movimiento, $data);
            if (isset($body['centro_id'])) {
                $output['centro'] = $centro;
            }
            if (isset($body['detalle'])) {
                $output['detalle'] = $body['detalle'];
            }
        } catch (EmptyResult) {}
        return $this->withJson($response, $output);
    }
}
