<?php
namespace Incoviba\Repository\Venta;

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

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

    public function create(?array $data = null): Model\Venta\Subsidio
    {
        $map = (new Implement\Repository\MapperParser())
            ->register('pago', (new Implement\Repository\Mapper())
                ->setProperty('ahorro')
                ->setFunction(function($data) {
                    return $this->pagoRepository->fetchById($data['pago']);
                }))
            ->register('subsidio', (new Implement\Repository\Mapper())
                ->setFunction(function($data) {
                    return $this->pagoRepository->fetchById($data['subsidio']);
                }));
        return $this->parseData(new Model\Venta\Subsidio(), $data, $map);
    }
    public function save(Define\Model $model): Model\Venta\Subsidio
    {
        $model->id = $this->saveNew(
            ['pago', 'subsidio'],
            [$model->ahorro->id, $model->subsidio->id]
        );
        return $model;
    }
    public function edit(Define\Model $model, array $new_data): Model\Venta\Subsidio
    {
        return $this->update($model, ['pago', 'subsidio'], $new_data);
    }

    public function fetchByPago(int $pago_id): Model\Venta\Subsidio
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('subsidio = ? OR pago = ?');
        return $this->fetchOne($query, [$pago_id, $pago_id]);
    }

    /**
     * @param int $venta_id
     * @return Model\Venta\Subsidio
     * @throws Implement\Exception\EmptyResult
     */
    public function fetchByVenta(int $venta_id): Model\Venta\Subsidio
    {
        $query = $this->connection->getQueryBuilder()
            ->select('a.*')
            ->from("{$this->getTable()} a")
            ->joined('JOIN venta ON venta.subsidio = a.id')
            ->where('venta.id = ?');
        return $this->fetchOne($query, [$venta_id]);
    }
}
