<?php
namespace Incoviba\Service\Venta;

use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Repository;
use Incoviba\Model;

class Pie
{
    public function __construct(
        protected Repository\Venta\Pie $pieRepository,
        protected Cuota $cuotaService,
        protected Pago $pagoService
    ) {}

    public function getById(int $pie_id): Model\Venta\Pie
    {
        return $this->process($this->pieRepository->fetchById($pie_id));
    }

    public function add(array $data): Model\Venta\Pie
    {
        $pie = $this->pieRepository->create($data);
        return $this->pieRepository->save($pie);
    }
    public function addCuota(array $data): Model\Venta\Cuota
    {
        return $this->cuotaService->add($data);
    }
    public function edit(Model\Venta\Pie $pie, array $data): Model\Venta\Pie
    {
        return $this->pieRepository->edit($pie, $data);
    }
    public function reajustar(Model\Venta\Pie $pie, array $data): Model\Venta\Pie
    {
        $pago = $this->pagoService->add($data);
        return $this->pieRepository->edit($pie, ['reajuste' => $pago->id]);
    }

    protected function process(Model\Venta\Pie $pie): Model\Venta\Pie
    {
        $pie->cuotasArray = $this->cuotaService->getByPie($pie->id);
        try {
            $pie->asociados = $this->pieRepository->fetchAsociados($pie->id);
        } catch (EmptyResult) {}
        return $pie;
    }
}
