<?php
namespace Incoviba\Repository\Proyecto;

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

class TipoUnidad extends Ideal\Repository
{
    public function __construct(Define\Connection $connection)
    {
        parent::__construct($connection);
        $this->setTable('tipo_unidad');
    }

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

    /**
     * @param int $proyecto_id
     * @return array
     * @throws Implement\Exception\EmptyResult
     */
    public function fetchByProyecto(int $proyecto_id): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select('a.*')
            ->from("{$this->getTable()} a")
            ->joined('JOIN proyecto_tipo_unidad b ON b.tipo = a.id')
            ->where('b.proyecto = ?')
            ->group('a.id')
            ->order('a.orden');
        return $this->fetchMany($query, [$proyecto_id]);
    }

    /**
     * @param int $promotion_id
     * @return array
     * @throws Implement\Exception\EmptyResult
     */
    public function fetchByPromotion(int $promotion_id): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select('a.id, put.project_id')
            ->from("{$this->getTable()} a")
            ->joined('INNER JOIN promotion_unit_types put ON put.`unit_type_id` = a.`id`')
            ->where('put.`promotion_id` = :promotion_id')
            ->group('a.id');
        try {
            $result = $this->connection->execute($query, ['promotion_id' => $promotion_id])->fetchAll(PDO::FETCH_ASSOC);
            if (empty($result)) {
                throw new Implement\Exception\EmptyResult($query);
            }
            return $result;
        } catch (PDOException $exception) {
            throw new Implement\Exception\EmptyResult($query, $exception);
        }
        return $this->fetchMany($query, ['promotion_id' => $promotion_id]);
    }
}
