<?php
namespace Incoviba\Repository;

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

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

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

    public function fetchByDescripcion(string $descripcion): Define\Model
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('descripcion = ?');
        return $this->fetchOne($query, [$descripcion]);
    }
    public function fetchByProvincia(int $provincia_id): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('provincia = ?');
        return $this->fetchMany($query, [$provincia_id]);
    }
    public function fetchByRegion(int $region_id): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select('c.*')
            ->from("{$this->getTable()} c")
            ->joined('JOIN provincia p ON c.provincia = p.id')
            ->where('p.region = ?');
        return $this->fetchMany($query, [$region_id]);
    }
    public function fetchByDireccion(string $direccion): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select('c.*')
            ->from("{$this->getTable()} c")
            ->joined('JOIN direccion d ON c.id = d.comuna')
            ->where('TRIM(CONCAT_WS(" ", d.calle, d.numero, d.extra)) LIKE ?');
        return $this->fetchMany($query, ["%{$direccion}%"]);
    }
}
