<?php
namespace Incoviba\Controller\API;

use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Message\ResponseInterface;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Repository;

class CentrosCostos
{
    use withJson;

    public function add(ServerRequestInterface $request, ResponseInterface $response,
                        Repository\CentroCosto $centroCostoRepository): ResponseInterface
    {
        $body = $request->getParsedBody();
        $output = [
            'input' => $body,
            'added' => false
        ];
        try {
            $centroCosto = $centroCostoRepository->create($body);
            $centroCosto->id = $body['id'];
            $centroCostoRepository->save($centroCosto);
            $output['added'] = true;
        } catch (EmptyResult) {}
        return $this->withJson($response, $output);
    }
    public function edit(ServerRequestInterface $request, ResponseInterface $response,
                         Repository\CentroCosto $centroCostoRepository, int $centro_costo_id): ResponseInterface
    {
        $body = $request->getParsedBody();
        $output = [
            'centro_costo_id' => $centro_costo_id,
            'input' => $body,
            'edited' => false
        ];
        try {
            $centroCosto = $centroCostoRepository->fetchById($centro_costo_id);
            if ($body['tipo_cuenta_id'] === '') {
                $body['tipo_cuenta_id'] = null;
            }
            $centroCostoRepository->edit($centroCosto, $body);
            $output['edited'] = true;
        } catch (EmptyResult) {}
        return $this->withJson($response, $output);
    }
    public function remove(ServerRequestInterface $request, ResponseInterface $response,
                           Repository\CentroCosto $centroCostoRepository, int $centro_costo_id): ResponseInterface
    {
        $output = [
            'centro_costo_id' => $centro_costo_id,
            'removed' => false
        ];
        try {
            $centroCosto = $centroCostoRepository->fetchById($centro_costo_id);
            $centroCostoRepository->remove($centroCosto);
            $output['removed'] = true;
        } catch (EmptyResult) {}
        return $this->withJson($response, $output);
    }
}
