<?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 = "SELECT * FROM `{$this->getTable()}` WHERE `descripcion` = ?";
        return $this->fetchOne($query, [$descripcion]);
    }
    public function fetchByProvincia(int $provincia_id): array
    {
        $query = "SELECT * FROM `{$this->getTable()}` WHERE `provincia` = ?";
        return $this->fetchMany($query, [$provincia_id]);
    }
    public function fetchByDireccion(string $direccion): array
    {
        $query = "SELECT a.* 
FROM `{$this->getTable()}` a 
    JOIN `direccion` ON `direccion`.`comuna` = a.`id`
WHERE TRIM(CONCAT_WS(' ', `direccion`.`calle`, `direccion`.`numero`, `direccion`.`extra`)) LIKE ?";
        return $this->fetchMany($query, ["%{$direccion}%"]);
    }
}
