<?php
namespace Incoviba\Repository\Venta\Factura;

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

class Estado extends Ideal\Repository
{
    public function __construct(Define\Connection $connection, protected Repository\Venta\Factura $facturaRepository, protected Repository\Venta\Factura\Estado\Tipo $tipoRepository)
    {
        parent::__construct($connection);
        $this->setTable('estados_facturas');
    }

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

    public function fetchByFactura(int $factura_id): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('factura_id = :factura_id');
        return $this->fetchMany($query, ['factura_id' => $factura_id]);
    }
}
