<?php
namespace Incoviba\Repository\Venta;

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

class Pago extends Ideal\Repository
{
    public function __construct(
        Define\Connection $connection,
        protected Repository\Banco $bancoRepository,
        protected TipoPago $tipoPagoRepository
    )
    {
        parent::__construct($connection);
        $this->setTable('pago');
    }

    public function create(?array $data = null): Model\Venta\Pago
    {
        $map = (new Implement\Repository\MapperParser(['valor', 'identificador', 'uf', 'pagador']))
            ->register('banco', (new Implement\Repository\Mapper())
                ->setFunction(function($data) {
                    if ($data['banco'] === null or $data['banco'] === 0) {
                        return null;
                    }
                    return $this->bancoRepository->fetchById($data['banco']);
                }))
            ->register('tipo', (new Implement\Repository\Mapper())
                ->setProperty('tipoPago')
                ->setFunction(function($data) {
                    if ($data['tipo'] === null) {
                        return null;
                    }
                    return $this->tipoPagoRepository->fetchById($data['tipo']);
                }))
            ->register('fecha', (new Implement\Repository\Mapper\DateTime('fecha'))
                ->setDefault(null))
            ->register('asociado', (new Implement\Repository\Mapper())
                ->setFunction(function($data) {
                    if ($data['asociado'] === null) {
                        return null;
                    }
                    return $this->fetchById($data['asociado']);
                }));
        return $this->parseData(new Model\Venta\Pago(), $data, $map);
    }
    public function save(Define\Model $model): Model\Venta\Pago
    {
        $model->id = $this->saveNew(
            ['valor', 'banco', 'tipo', 'identificador', 'fecha', 'uf', 'pagador', 'asociado'],
            [$model->valor, $model->banco?->id, $model->tipoPago?->id, $model->identificador, $model->fecha?->format('Y-m-d H:i:s'), $model->uf, $model->pagador, $model->asociado?->id]
        );
        return $model;
    }
    public function edit(Define\Model $model, array $new_data): Model\Venta\Pago
    {
        return $this->update($model, ['valor', 'banco', 'tipo', 'identificador', 'fecha', 'uf', 'pagador', 'asociado'], $new_data);
    }
}
