<?php
namespace Incoviba\Service\Venta;

use PDOException;
use DateTimeImmutable;
use DateMalformedStringException;
use Incoviba\Common\Implement\Exception\EmptyResult;
use Incoviba\Exception\ServiceAction\{Create, Read};
use Incoviba\Model;
use Incoviba\Repository;
use Incoviba\Service\UF;

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

    public function getById(int $pie_id): Model\Venta\Pie
    {
        return $this->process($this->pieRepository->fetchById($pie_id));
    }
    public function getByVenta(int $venta_id): Model\Venta\Pie
    {
        try {
            return $this->process($this->pieRepository->fetchByVenta($venta_id));
        } catch (EmptyResult $exception) {
            throw new Read(__CLASS__, $exception);
        }
    }

    /**
     * @param array $data
     * @return Model\Venta\Pie
     * @throws Create
     */
    public function add(array $data): Model\Venta\Pie
    {
        try {
            $filteredData = $this->pieRepository->filterData($data);
            if (!isset($filteredData['uf'])) {
                try {
                    $date = new DateTimeImmutable($filteredData['fecha']);
                    $filteredData['uf'] = $this->ufService->get($date);
                } catch (DateMalformedStringException) {}
            }
            $pie = $this->pieRepository->create($filteredData);
            return $this->pieRepository->save($pie);
        } catch (PDOException $exception) {
            throw new Create(__CLASS__, $exception);
        }
    }
    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
    {
        $filteredData = $this->pieRepository->filterData($data);
        return $this->pieRepository->edit($pie, $filteredData);
    }
    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) {}
        if (isset($pie->asociado)) {
            $pie->asociado = $this->getById($pie->asociado->id);
        }
        if (($pie->uf === null or $pie->uf === 0.0) and $pie->fecha <= new DateTimeImmutable()) {
            $pie->uf = $this->ufService->get($pie->fecha);
            try {
                $this->pieRepository->edit($pie, ['uf' => $pie->uf]);
            } catch (EmptyResult) {}
        }
        return $pie;
    }
}
