<?php
namespace Incoviba\Repository\Contabilidad;

use Incoviba\Common\Define;
use Incoviba\Common\Ideal;
use Incoviba\Common\Implement;
use Incoviba\Model;
use Incoviba\Repository;

class PagoCentroCosto extends Ideal\Repository
{
    public function __construct(Define\Connection $connection, protected Repository\Venta\Pago $pagoRepository, protected CentroCosto $centroCostoRepository)
    {
        parent::__construct($connection);
        $this->setTable('pagos_centros_costos');
    }

    public function create(?array $data = null): Model\Contabilidad\PagoCentroCosto
    {
        $map = (new Implement\Repository\MapperParser())
            ->register('pago_id', (new Implement\Repository\Mapper())
                ->setProperty('pago')
                ->setFunction(function(array $data) {
                    return $this->pagoRepository->fetchById($data['pago_id']);
                }))
            ->register('centro_costo_id', (new Implement\Repository\Mapper())
                ->setProperty('centroCosto')
                ->setFunction(function(array $data) {
                    return $this->centroCostoRepository->fetchById($data['centro_costo_id']);
                }));
        return $this->parseData(new Model\Contabilidad\PagoCentroCosto(), $data, $map);
    }
    public function save(Define\Model $model): Model\Contabilidad\PagoCentroCosto
    {
        $model->id = $this->saveNew(['pago_id', 'centro_costo_id'], [$model->pago->id, $model->centroCosto->id]);
        return $model;
    }
    public function edit(Define\Model $model, array $new_data): Model\Contabilidad\PagoCentroCosto
    {
        return $this->update($model, ['pago_id', 'centro_costo_id'], $new_data);
    }
}
