<?php
namespace Incoviba\Repository\Contabilidad\Movimiento\Auxiliar;

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

class Detalle extends Ideal\Repository
{
    public function __construct(Define\Connection $connection,
                                protected Repository\Contabilidad\Movimiento\Auxiliar $auxiliarRepository,
                                protected Repository\Contabilidad\CentroCosto $centroCostoRepository)
    {
        parent::__construct($connection);
        $this->setTable('auxiliar_detalles');
    }

    public function create(?array $data = null): Model\Contabilidad\Movimiento\Auxiliar\Detalle
    {
        $map = (new Implement\Repository\MapperParser(['rut', 'digito', 'nombre', 'categoria', 'detalle']))
            ->register('auxiliar_id', (new Implement\Repository\Mapper())
                ->setProperty('auxiliar')
                ->setFunction(function($data) {
                    return $this->auxiliarRepository->fetchById($data['auxiliar_id']);
                }))
            ->register('centro_costo_id', (new Implement\Repository\Mapper())
                ->setProperty('centroCosto')
                ->setFunction(function($data) {
                    return $this->centroCostoRepository->fetchById($data['centro_costo_id']);
                })
                ->setDefault(null));
        return $this->parseData(new Model\Contabilidad\Movimiento\Auxiliar\Detalle(), $data, $map);
    }
    public function save(Define\Model $model): Model\Contabilidad\Movimiento\Auxiliar\Detalle
    {
        $this->saveNew([
            'auxiliar_id',
            'rut',
            'digito',
            'nombre',
            'categoria',
            'detalle'
        ], [
            $model->auxiliar->id,
            $model->rut,
            $model->digito,
            $model->nombre,
            $model->categoria,
            $model->detalle
        ]);
        return $model;
    }
    public function edit(Define\Model $model, array $new_data): Model\Contabilidad\Movimiento\Auxiliar\Detalle
    {
        return $this->update($model, ['rut', 'digito', 'nombre', 'categoria', 'detalle'], $new_data);
    }

    /**
     * @throws EmptyResult
     */
    public function fetchByAuxiliar(int $auxiliar_id): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('auxiliar_id = :auxiliar_id');
        return $this->fetchMany($query, ['auxiliar_id' => $auxiliar_id]);
    }
}
