<?php
namespace Incoviba\Repository\Inmobiliaria\Proveedor;

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

class Datos extends Ideal\Repository
{
    public function __construct(Define\Connection $connection, protected Repository\Inmobiliaria\Proveedor $proveedorRepository,
                                protected Repository\Direccion $direccionRepository)
    {
        parent::__construct($connection);
        $this->setTable('datos_proveedores');
    }
    public function create(?array $data = null): Model\Inmobiliaria\Proveedor\Datos
    {
        $map = (new Implement\Repository\MapperParser(['telefono', 'giro']))
            ->register('proveedor_rut', (new Implement\Repository\Mapper())->setProperty('proveedor')->setFunction(function($data) {
                return $this->proveedorRepository->fetchById($data['proveedor_rut']);
            }))
            ->register('direccion_id', (new Implement\Repository\Mapper())->setProperty('direccion')->setFunction(function($data) {
                return $this->direccionRepository->fetchById($data['direccion_id']);
            }));
        return $this->parseData(new Model\Inmobiliaria\Proveedor\Datos(), $data, $map);
    }
    public function save(Define\Model $model): Model\Inmobiliaria\Proveedor\Datos
    {
        $model->id = $this->saveNew([
            'proveedor_rut', 'direccion_id', 'telefono', 'giro'
        ], [
            $model->proveedor->rut, $model->direccion->id, $model->telefono, $model->giro
        ]);
        return $model;
    }
    public function edit(Define\Model $model, array $new_data): Model\Inmobiliaria\Proveedor\Datos
    {
        return $this->update($model, ['proveedor_rut', 'direccion_id', 'telefono', 'giro'], $new_data);
    }

    public function fetchByProveedor(int $proveedor_rut): Model\Inmobiliaria\Proveedor\Datos
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('proveedor_rut = :proveedor_rut');
        return $this->fetchOne($query, compact('proveedor_rut'));
    }
}
