<?php
namespace Incoviba\Repository\Venta;

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

class Comentario extends Ideal\Repository
{
    public function __construct(Define\Connection $connection)
    {
        parent::__construct($connection);
        $this->setTable('comentario');
    }

    public function create(?array $data = null): Define\Model
    {
        $map = (new Implement\Repository\MapperParser(['texto']))
            ->register('fecha', new Implement\Repository\Mapper\DateTime('fecha'))
            ->register('estado', new Implement\Repository\Mapper\Boolean('estado', 'activo'));
        return $this->parseData(new Model\Venta\Comentario(), $data, $map);
    }
    public function save(Define\Model $model): Define\Model
    {
        $model->id = $this->saveNew(
            ['fecha', 'texto', 'estado'],
            [$model->fecha->format('Y-m-d'), $model->texto, $model->activo ? 1 : 0]
        );
        return $model;
    }
    public function edit(Define\Model $model, array $new_data): Define\Model
    {
        return $this->update($model, ['fecha', 'texto', 'estado'], $new_data);
    }

    public function fetchByVenta(int $venta_id): array
    {
        $query = "SELECT * FROM `{$this->getTable()}` WHERE `venta` = ? AND `estado` = 1 ORDER BY `fecha` DESC";
        return $this->fetchMany($query, [$venta_id]);
    }
}
