<?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 EstadoVenta extends Ideal\Repository
{
    public function __construct(Define\Connection $connection, protected Repository\Venta $ventaRepository,
                                protected TipoEstadoVenta $tipoEstadoVentaRepository)
    {
        parent::__construct($connection);
        $this->setTable('estado_venta');
    }

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

    public function fetchByVenta(int $venta_id): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('venta = ?');
        return $this->fetchMany($query, [$venta_id]);
    }
    public function fetchCurrentByVenta(int $venta_id): Model\Venta\EstadoVenta
    {
        $query = $this->connection->getQueryBuilder()
            ->select('a.*')
            ->from("{$this->getTable()} a")
            ->joined("JOIN (SELECT MAX(id) AS id, venta FROM {$this->getTable()} GROUP BY venta) ev0 ON ev0.id = a.id")
            ->where('a.venta = ?');
        return $this->fetchOne($query, [$venta_id]);
    }
}
