<?php
namespace Incoviba\Repository\Venta;

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

class ValorCierre extends Ideal\Repository
{
    public function __construct(Define\Connection $connection,
                                protected Repository\Venta\Cierre $cierreRepository,
                                protected Repository\Venta\TipoValorCierre $tipoValorCierreRepository)
    {
        parent::__construct($connection);
        $this->setTable('valor_cierre');
    }

    public function create(?array $data = null): Define\Model
    {
        $map = (new Implement\Repository\MapperParser(['valor']))
            ->register('cierre', (new Implement\Repository\Mapper())
                ->setFunction(function($data) {
                    return $this->cierreRepository->fetchById($data['cierre']);
                }))
            ->register('tipo', (new Implement\Repository\Mapper())
                ->setProperty('tipoValorCierre')
                ->setFunction(function($data) {
                    return $this->tipoValorCierreRepository->fetchById($data['tipo']);
                }));
        return $this->parseData(new Model\Venta\ValorCierre(), $data, $map);
    }
    public function save(Define\Model $model): Define\Model
    {
        $model->id = $this->saveNew(
            ['cierre', 'tipo', 'valor'],
            [$model->cierre->id, $model->tipoValorCierre->id, $model->valor]
        );
        return $model;
    }
    public function edit(Define\Model $model, array $new_data): Define\Model
    {
        return $this->update($model, ['cierre', 'tipo', 'valor'], $new_data);
    }

    public function fetchByCierre(int $cierre_id): array
    {
        $query = "SELECT * FROM `{$this->getTable()}` WHERE `cierre` = ?";
        return $this->fetchMany($query, [$cierre_id]);
    }
}
