<?php
namespace Incoviba\Repository\Venta;

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

class Precio extends Ideal\Repository
{
    public function __construct(Define\Connection $connection, protected Repository\Venta\Unidad $unidadRepository)
    {
        parent::__construct($connection);
        $this->setTable('precio');
    }

    public function create(?array $data = null): Define\Model
    {
        $map = (new Implement\Repository\MapperParser(['valor']))
            ->register('unidad', (new Implement\Repository\Mapper())
                ->setFunction(function($data) {
                    return $this->unidadRepository->fetchById($data['unidad']);
                }));
        return $this->parseData(new Model\Venta\Precio(), $data, $map);
    }
    public function save(Define\Model $model): Define\Model
    {
        $model->id = $this->saveNew(
            ['unidad', 'valor'],
            [$model->unidad->id, $model->valor]
        );
        return $model;
    }

    /**
     * @param Define\Model $model
     * @param array $new_data
     * @return Define\Model
     * @throws Implement\Exception\EmptyResult
     */
    public function edit(Define\Model $model, array $new_data): Define\Model
    {
        return $this->update($model, ['unidad', 'valor'], $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($this->joinEstado())
            ->joined('INNER JOIN `tipo_estado_precio` tep ON tep.`id` = ep.`estado`')
            ->joined('INNER JOIN `unidad` ON `unidad`.`id` = a.`unidad`')
            ->joined('INNER JOIN `proyecto_tipo_unidad` ptu ON ptu.`id` = `unidad`.`pt`')
            ->joined('INNER JOIN `tipo_unidad` tu ON tu.`id` = ptu.`tipo`')
            ->where('ptu.`proyecto` = ? AND tep.`descripcion` = "vigente"')
            ->order('tu.`orden`, ptu.`nombre`, `unidad`.`subtipo`, LPAD(`unidad`.`descripcion`, 4, "0")');
        return $this->fetchMany($query, [$proyecto_id]);
    }

    /**
     * @param int $unidad_id
     * @return array
     * @throws Implement\Exception\EmptyResult
     */
    public function fetchByUnidad(int $unidad_id): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select('a.*')
            ->from("{$this->getTable()} a")
            ->joined($this->joinEstado())
            ->joined('INNER JOIN tipo_estado_precio tep ON tep.`id` = ep.`estado`')
            ->where('`unidad` = ?');
        return $this->fetchMany($query, [$unidad_id]);
    }

    /**
     * @param int $unidad_id
     * @return Define\Model
     * @throws Implement\Exception\EmptyResult
     */
    public function fetchVigenteByUnidad(int $unidad_id): Define\Model
    {
        $query = $this->connection->getQueryBuilder()
            ->select('a.*')
            ->from("{$this->getTable()} a")
            ->joined($this->joinEstado())
            ->joined('INNER JOIN tipo_estado_precio tep ON tep.`id` = ep.`estado`')
            ->where('`unidad` = ? AND tep.`descripcion` = "vigente"');
        return $this->fetchOne($query, [$unidad_id]);
    }

    /**
     * @param array $unidad_ids
     * @return array
     * @throws Implement\Exception\EmptyResult
     */
    public function fetchVigentesByUnidades(array $unidad_ids): array
    {
        $interrogations = implode(',', array_fill(0, count($unidad_ids), '?'));
        $query = $this->connection->getQueryBuilder()
            ->select('a.*, unidad')
            ->from("{$this->getTable()} a")
            ->joined($this->joinEstado())
            ->joined('INNER JOIN tipo_estado_precio tep ON tep.`id` = ep.`estado`')
            ->where("`unidad` IN ({$interrogations}) AND tep.`descripcion` = \"vigente\"");
        try {
            $results = $this->connection->execute($query, $unidad_ids)->fetchAll(PDO::FETCH_ASSOC);
            if (empty($results)) {
                throw new Implement\Exception\EmptyResult($query);
            }
            return array_map(function($result) {
                return [
                    'id' => $result['unidad'],
                    'precio' => $this->load($result)
                ];
            }, $results);
        } catch (PDOException $exception) {
            throw new Implement\Exception\EmptyResult($query, $exception);
        }
    }

    /**
     * @param int $unidad_id
     * @param string $date_time
     * @return Define\Model
     * @throws Implement\Exception\EmptyResult
     */
    public function fetchByUnidadAndDate(int $unidad_id, string $date_time): Define\Model
    {
        $query = $this->connection->getQueryBuilder()
            ->select('a.*')
            ->from("{$this->getTable()} a")
            ->joined($this->joinEstado())
            ->joined('INNER JOIN `tipo_estado_precio` tep ON tep.`id` = ep.`estado`')
            ->where('`unidad` = ? AND ep.`fecha` <= ? AND tep.`descripcion` = "vigente"');
        return $this->fetchOne($query, [$unidad_id, $date_time]);
    }

    protected function joinEstado(): string
    {
        $subSubQuery = $this->connection->getQueryBuilder()
            ->select('MAX(id) AS id, precio')
            ->from('estado_precio')
            ->group('precio');
        $subQuery = $this->connection->getQueryBuilder()
            ->select('e1.*')
            ->from('estado_precio e1')
            ->joined("INNER JOIN ($subSubQuery) e0 ON e0.id = e1.id");
        return "JOIN ($subQuery) ep ON ep.precio = a.id";
    }
}
