<?php
namespace Incoviba\Repository\Venta;

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

class EstadoPrecio extends Ideal\Repository
{
    public function __construct(Define\Connection $connection, protected Repository\Venta\Precio $precioRepository, protected Repository\Venta\TipoEstadoPrecio $tipoEstadoPrecioRepository)
    {
        parent::__construct($connection);
        $this->setTable('estado_precio');
    }

    public function create(?array $data = null): Define\Model
    {
        $map = (new Implement\Repository\MapperParser())
            ->register('precio', (new Implement\Repository\Mapper())
                ->setFunction(function($data) {
                    return $this->precioRepository->fetchById($data['precio']);
                }))
            ->register('estado', (new Implement\Repository\Mapper())
                ->setProperty('tipoEstadoPrecio')
                ->setFunction(function($data) {
                    return $this->tipoEstadoPrecioRepository->fetchById($data['estado']);
                }))
            ->register('fecha', new Implement\Repository\Mapper\DateTime('fecha'));
        return $this->parseData(new Model\Venta\EstadoPrecio(), $data, $map);
    }
    public function save(Define\Model $model): Define\Model
    {
        $model->id = $this->saveNew(
            ['precio', 'estado', 'fecha'],
            [$model->precio->id, $model->tipoEstadoPrecio->id, $model->fecha->format('Y-m-d')]
        );
        return $model;
    }
    public function edit(Define\Model $model, array $new_data): Define\Model
    {
        return $this->update($model, ['precio', 'estado', 'fecha'], $new_data);
    }

    public function fetchByPrecio(int $precio_id): array
    {
        $query = "SELECT * FROM `{$this->getTable()}` WHERE `precio` = ?";
        return $this->fetchMany($query, [$precio_id]);
    }
    public function fetchCurrentByPrecio(int $precio_id): Define\Model
    {
        $query = "SELECT e1.* 
FROM `{$this->getTable()}` e1 JOIN (SELECT MAX(`id`) AS 'id', `precio` FROM `{$this->getTable()}` GROUP BY `precio`) e0 ON e0.`id` = e1.`id` 
WHERE e1.`precio` = ?";
        return $this->fetchOne($query, [$precio_id]);
    }
}
