<?php
namespace Incoviba\Repository\Inmobiliaria;

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

class Cuenta extends Ideal\Repository
{
    public function __construct(Define\Connection                       $connection,
                                protected Repository\Inmobiliaria       $inmobiliariaRepository,
                                protected Repository\Contabilidad\Banco $bancoRepository)
    {
        parent::__construct($connection);
        $this->setTable('cuenta');
    }

    public function create(?array $data = null): Model\Inmobiliaria\Cuenta
    {
        $map = (new Implement\Repository\MapperParser(['cuenta']))
            ->register('inmobiliaria', (new Implement\Repository\Mapper())
                ->setFunction(function(array $data) {
                    return $this->inmobiliariaRepository->fetchById($data['inmobiliaria']);
                }))
            ->register('banco', (new Implement\Repository\Mapper())
                ->setFunction(function(array $data) {
                    return $this->bancoRepository->fetchById($data['banco']);
                }));
        return $this->parseData(new Model\Inmobiliaria\Cuenta(), $data, $map);
    }
    public function save(Define\Model $model): Model\Inmobiliaria\Cuenta
    {
        $model->id = $this->saveNew(['inmobiliaria', 'banco', 'cuenta'],
            [$model->inmobiliaria->rut, $model->banco->id, $model->cuenta]);
        return $model;
    }
    public function edit(Define\Model $model, array $new_data): Model\Inmobiliaria\Cuenta
    {
        return $this->update($model, ['inmobiliaria', 'banco', 'cuenta'], $new_data);
    }

    public function fetchByInmobiliaria(int $inmobiliaria_rut): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('inmobiliaria = ?');
        return $this->fetchMany($query, [$inmobiliaria_rut]);
    }
    public function fetchByInmobiliariaAndBanco(int $inmobiliaria_rut, int $banco_id): Model\Inmobiliaria\Cuenta
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('inmobiliaria = ? AND banco = ?');
        return $this->fetchOne($query, [$inmobiliaria_rut, $banco_id]);
    }
}
