<?php
namespace Incoviba\Repository\Inmobiliaria;

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

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

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

    public function fetchByInmobiliaria(int $inmobiliaria_rut): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('inmobiliaria_rut = :inmobiliaria_rut');
        return array_map([$this, 'load'], $this->fetchMany($query, compact('inmobiliaria_rut')));
    }
    public function fetchBySociedad(int $sociedad_rut): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('sociedad_rut = :sociedad_rut');
        return array_map([$this, 'load'], $this->fetchMany($query, compact('sociedad_rut')));
    }
}
