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

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

class Sociedades extends Ideal\Service
{
    use withJson;

    public function add(ServerRequestInterface $request, ResponseInterface $response,
                        Service\Sociedad $sociedadService, Service\Persona $personaService): ResponseInterface
    {
        $input = $request->getParsedBody();
        $output = [
            'input' => $input,
            'sociedad' => null
        ];
        try {
            $data = json_decode($input, true);
            $contacto = $personaService->add($data['contacto']);
            $data['contacto_rut'] = $contacto->rut;
            unset($data['contacto']);
            $output['sociedad'] = $sociedadService->add($data);
        } catch (EmptyResult) {
            $output['error'] = 'No se pudo agregar la sociedad';
        }
        return $this->withJson($response, $output);
    }
}
