<?php
namespace Incoviba\Repository\Venta;

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

class EstadoPago extends Ideal\Repository
{
    public function __construct(protected Define\Connection $connection,
                                protected Repository\Venta\Pago $pagoRepository,
                                protected Repository\Venta\TipoEstadoPago $tipoEstadoPagoRepository)
    {
        parent::__construct($connection);
        $this->setTable('estado_pago');
    }

    public function create(?array $data = null): Model\Venta\EstadoPago
    {
        $map = (new Implement\Repository\MapperParser())
            ->register('pago', (new Implement\Repository\Mapper())
                ->setFunction(function($data) {
                    return $this->pagoRepository->fetchById($data['pago']);
                }))
            ->register('estado', (new Implement\Repository\Mapper())
                ->setProperty('tipoEstadoPago')
                ->setFunction(function($data) {
                    return $this->tipoEstadoPagoRepository->fetchById($data['estado']);
                }))
            ->register('fecha', new Implement\Repository\Mapper\DateTime('fecha'));
        return $this->parseData(new Model\Venta\EstadoPago(), $data, $map);
    }

    public function save(Define\Model $model): Model\Venta\EstadoPago
    {
        $model->id = $this->saveNew(
            ['pago', 'estado', 'fecha'],
            [$model->pago->id, $model->tipoEstadoPago->id, $model->fecha->format('Y-m-d')]
        );
        return $model;
    }

    public function edit(Define\Model $model, array $new_data): Model\Venta\EstadoPago
    {
        return $this->update($model, ['pago', 'estado', 'fecha'], $new_data);
    }

    public function fetchByPago(int $pago_id): array
    {
        $query = "SELECT * FROM `{$this->getTable()}` WHERE `pago` = ?";
        return $this->fetchMany($query, [$pago_id]);
    }
    public function fetchCurrentByPago(int $pago_id): Model\Venta\EstadoPago
    {
        $query = "SELECT a.* 
FROM `{$this->getTable()}` a
    JOIN (SELECT MAX(`id`) AS 'id', `pago` FROM `{$this->getTable()}` GROUP BY `pago`) e0 ON e0.`id` = a.`id`
WHERE a.`pago` = ?";
        return $this->fetchOne($query, [$pago_id]);
    }
    public function fetchByPagoAndEstado(int $pago_id, int $estado_id): Model\Venta\EstadoPago
    {
        $query = "SELECT * FROM `{$this->getTable()}` WHERE `pago` = ? AND `estado` = ?";
        return $this->fetchOne($query, [$pago_id, $estado_id]);
    }
}
