<?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 EstadoCierre extends Ideal\Repository
{
    public function __construct(Define\Connection $connection, protected Repository\Venta\Cierre $cierreRepository, protected Repository\Venta\TipoEstadoCierre $tipoEstadoCierreRepository)
    {
        parent::__construct($connection);
        $this->setTable('estado_cierre');
    }

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

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