<?php
namespace Incoviba\Repository;

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

class Direccion extends Ideal\Repository
{
    public function __construct(Define\Connection $connection, protected Comuna $comunaRepository)
    {
        parent::__construct($connection);
        $this->setTable('direccion');
    }

    public function create(?array $data = null): Define\Model
    {
        $map = (new Implement\Repository\MapperParser(['calle', 'numero', 'extra']))
            ->register('comuna', (new Implement\Repository\Mapper())->setFunction(function($data) {
                return $this->comunaRepository->fetchById($data['comuna']);
            }));
        return $this->parseData(new Model\Direccion(), $data, $map);
    }
    public function save(Define\Model $model): Define\Model
    {
        $model->id = $this->saveNew(
            ['calle', 'numero', 'extra', 'comuna'],
            [$model->calle, $model->numero, $model->extra, $model->comuna->id]
        );
        return $model;
    }
    public function edit(Define\Model $model, array $new_data): Define\Model
    {
        return $this->update($model, ['calle', 'numero', 'extra', 'comuna'], $new_data);
    }

    public function fetchByCalleAndNumero(string $calle, int $numero): array
    {
        $query = "SELECT * FROM `{$this->getTable()}` WHERE `calle` = ? AND `numero` = ?";
        return $this->fetchMany($query, [$calle, $numero]);
    }
    public function fetchByCalleAndNumeroAndExtra(string $calle, int $numero, string $extra): Model\Direccion
    {
        $query = "SELECT * FROM `{$this->getTable()}` WHERE `calle` = ? AND `numero` = ? AND `extra` = ?";
        return $this->fetchOne($query, [$calle, $numero, $extra]);
    }
}
