<?php
namespace Incoviba\Repository\Contabilidad;

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

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

    public function create(?array $data = null): Model\Contabilidad\Nubox
    {
        $map = (new Implement\Repository\MapperParser(['usuario', 'alias']))
            ->register('inmobiliaria_rut', (new Implement\Repository\Mapper())
                ->setProperty('inmobiliaria')
                ->setFunction(function(array $data) {
                    return $this->inmobiliariaRepository->fetchById($data['inmobiliaria_rut']);
                }))
            ->register('contraseña', (new Implement\Repository\Mapper())
                ->setProperty('password'));
        return $this->parseData(new Model\Contabilidad\Nubox(), $data, $map);
    }
    public function save(Define\Model $model): Model\Contabilidad\Nubox
    {
        $this->saveNew(
            ['inmobiliaria_rut', 'alias', 'usuario', 'contraseña'],
            [$model->inmobiliaria->rut, $model->alias, $model->usuario, $model->password]
        );
        return $model;
    }
    public function edit(Define\Model $model, array $new_data): Model\Contabilidad\Nubox
    {
        return $this->update($model, ['inmobiliaria_rut', 'alias', 'usuario', 'contraseña'], $new_data);
    }

    public function fetchByInmobiliaria(int $inmobiliaria_rut): Model\Contabilidad\Nubox
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('inmobiliaria_rut = ?');
        return $this->fetchOne($query, [$inmobiliaria_rut]);
    }

    protected function getKey(): string
    {
        return 'inmobiliaria_rut';
    }
    protected function getIndex(Define\Model $model): mixed
    {
        return $model->inmobiliaria->rut;
    }
    protected function setIndex(Define\Model &$model, mixed $value): Ideal\Repository
    {
        $model->inmobiliaria = $this->inmobiliariaRepository->fetchById($value);
        return $this;
    }
}
