<?php
namespace Incoviba\Repository\Contabilidad;

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

class Deposito extends Ideal\Repository
{
    public function __construct(Define\Connection $connection, protected Repository\Inmobiliaria\Cuenta $cuentaRepository)
    {
        parent::__construct($connection);
        $this->setTable('depositos');
    }

    public function create(?array $data = null): Model\Contabilidad\Deposito
    {
        $map = (new Implement\Repository\MapperParser(['id', 'capital', 'futuro']))
            ->register('cuenta_id', (new Implement\Repository\Mapper())
                ->setProperty('cuenta')
                ->setFunction(function(array $data) {
                    return $this->cuentaRepository->fetchById($data['cuenta_id']);
                }))
            ->register('inicio', new Implement\Repository\Mapper\DateTime('inicio'))
            ->register('termino', new Implement\Repository\Mapper\DateTime('termino'));
        return $this->parseData(new Model\Contabilidad\Deposito(), $data, $map);
    }
    public function save(Define\Model $model): Model\Contabilidad\Deposito
    {
        $this->saveNew([
            'id', 'cuenta_id', 'capital', 'futuro', 'inicio', 'termino'
        ], [
            $model->id, $model->cuenta->id, $model->capital, $model->futuro,
            $model->inicio->format('Y-m-d'), $model->termino->format('Y-m-d')
        ]);
        return $model;
    }

    public function edit(Define\Model $model, array $new_data): Model\Contabilidad\Deposito
    {
        return $this->update($model, ['cuenta_id', 'capital', 'futuro', 'inicio', 'termino'], $new_data);
    }

    public function fetchByCuenta(int $cuenta_id): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('cuenta_id = ?');
        return $this->fetchMany($query, [$cuenta_id]);
    }
    public function fetchAllActive(): array
    {
        $fecha = new DateTimeImmutable();
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('inicio <= ? AND termino >= ?');
        return $this->fetchMany($query, [$fecha->format('Y-m-d'), $fecha->format('Y-m-d')]);
    }
}
