<?php
namespace Incoviba\Repository\Venta;

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

class Pago extends Ideal\Repository
{
    public function __construct(
        Define\Connection                       $connection,
        protected Repository\Contabilidad\Banco $bancoRepository,
        protected TipoPago                      $tipoPagoRepository
    )
    {
        parent::__construct($connection);
        $this->setTable('pago');
    }

    public function create(?array $data = null): Model\Venta\Pago
    {
        $map = (new Implement\Repository\MapperParser(['valor', 'identificador', 'uf', 'pagador']))
            ->register('banco', (new Implement\Repository\Mapper())
                ->setFunction(function($data) {
                    if ($data['banco'] === null or $data['banco'] === 0 or trim($data['banco']) === '') {
                        return null;
                    }
                    return $this->bancoRepository->fetchById($data['banco']);
                }))
            ->register('tipo', (new Implement\Repository\Mapper())
                ->setProperty('tipoPago')
                ->setFunction(function($data) {
                    if ($data['tipo'] === null) {
                        return null;
                    }
                    return $this->tipoPagoRepository->fetchById($data['tipo']);
                }))
            ->register('fecha', (new Implement\Repository\Mapper\DateTime('fecha'))
                ->setDefault(null))
            ->register('asociado', (new Implement\Repository\Mapper())
                ->setFunction(function($data) {
                    if ($data['asociado'] === null) {
                        return null;
                    }
                    return $this->fetchById($data['asociado']);
                }));
        return $this->parseData(new Model\Venta\Pago(), $data, $map);
    }
    public function save(Define\Model $model): Model\Venta\Pago
    {
        $model->id = $this->saveNew(
            ['valor', 'banco', 'tipo', 'identificador', 'fecha', 'uf', 'pagador', 'asociado'],
            [$model->valor, $model->banco?->id, $model->tipoPago?->id, $model->identificador, $model->fecha?->format('Y-m-d H:i:s'), $model->uf, $model->pagador, $model->asociado?->id]
        );
        return $model;
    }
    public function edit(Define\Model $model, array $new_data): Model\Venta\Pago
    {
        return $this->update($model, ['valor', 'banco', 'tipo', 'identificador', 'fecha', 'uf', 'pagador', 'asociado'], $new_data);
    }

    public function fetchByVenta(int $venta_id): array
    {
        $query = "SELECT a.*
FROM (
        SELECT a.*, venta.id AS venta_id, 'cuota' AS fuente
        FROM pago a
            JOIN cuota ON cuota.pago = a.id
            JOIN venta ON venta.pie = cuota.pie
        UNION ALL
        SELECT a.*, venta.id AS venta_id, 'reajuste' AS fuente
        FROM pago a
            JOIN pie ON pie.reajuste = a.id
            JOIN venta ON venta.pie = pie.id
        UNION ALL
        SELECT a.*, venta.id AS venta_id, 'credito' AS fuente
        FROM pago a
            JOIN credito ON credito.pago = a.id
            JOIN venta ON venta.credito = credito.id
        UNION ALL
        SELECT a.*, venta.id AS venta_id, 'escritura' AS fuente
        FROM pago a
            JOIN escritura ON escritura.pago = a.id
            JOIN venta ON venta.escritura = escritura.id
        UNION ALL
        SELECT a.*, venta.id AS venta_id, 'subsidio' AS fuente
        FROM pago a
            JOIN subsidio ON subsidio.subsidio = a.id
            JOIN venta ON venta.subsidio = subsidio.id
        UNION ALL
        SELECT a.*, venta.id AS venta_id, 'ahorro' AS fuente
        FROM pago a
            JOIN subsidio ON subsidio.pago = a.id
            JOIN venta ON venta.subsidio = subsidio.id
    ) a
    JOIN (SELECT e1.* FROM estado_pago e1 JOIN (SELECT MAX(id) AS id, pago FROM estado_pago GROUP BY pago) e0 ON e0.id = e1.id) ep ON ep.pago = a.id
    JOIN tipo_estado_pago tep ON tep.id = ep.estado
WHERE venta_id = ?";
        return $this->fetchMany($query, [$venta_id]);
    }

    /**
     * @param int $value
     * @return array
     * @throws Implement\Exception\EmptyResult
     */
    public function fetchByValue(int $value): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('valor = ? OR ROUND(valor/uf, 3) = ?');
        return $this->fetchMany($query, [$value, $value]);
    }

    /**
     * @param int $venta_id
     * @return Model\Venta\Pago
     * @throws Implement\Exception\EmptyResult
     */
    public function fetchDevolucionByVenta(int $venta_id): Model\Venta\Pago
    {
        $query = $this->connection->getQueryBuilder()
            ->select('a.*')
            ->from("{$this->getTable()} a")
            ->joined('JOIN venta ON venta.devolucion = a.id')
            ->where('venta.id = ?');
        return $this->fetchOne($query, [$venta_id]);
    }
    public function filterData(array $data): array
    {
        return array_intersect_key($data, array_flip(['valor', 'banco', 'tipo', 'identificador', 'fecha', 'uf', 'pagador', 'asociado']));
    }
}
