<?php
namespace Incoviba\Repository\Contabilidad;

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

class Movimiento extends Ideal\Repository
{
    public function __construct(Define\Connection $connection, protected Inmobiliaria\Cuenta $cuentaRepository)
    {
        parent::__construct($connection);
        $this->setTable('movimientos');
    }

    public function create(?array $data = null): Model\Contabilidad\Movimiento
    {
        $map = (new Implement\Repository\MapperParser(['cargo', 'abono', 'saldo', 'glosa', 'documento']))
            ->register('fecha', new Implement\Repository\Mapper\DateTime('fecha'))
            ->register('cuenta_id', (new Implement\Repository\Mapper())
                ->setProperty('cuenta')
                ->setFunction(function($data) {
                    return $this->cuentaRepository->fetchById($data['cuenta_id']);
                })
            );
        return $this->parseData(new Model\Contabilidad\Movimiento(), $data, $map);
    }
    public function save(Define\Model $model): Model\Contabilidad\Movimiento
    {
        $model->id = $this->saveNew([
            'cuenta_id',
            'fecha',
            'glosa',
            'documento',
            'cargo',
            'abono',
            'saldo'
        ], [
            $model->cuenta->id,
            $model->fecha->format('Y-m-d'),
            $model->glosa,
            $model->documento,
            $model->cargo,
            $model->abono,
            $model->saldo
        ]);
        return $model;
    }
    public function edit(Define\Model $model, array $new_data): Model\Contabilidad\Movimiento
    {
        return $this->update($model, ['cuenta_id', 'fecha', 'glosa', 'documento', 'cargo', 'abono', 'saldo'], $new_data);
    }

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

    /**
     * @param int $cuenta_id
     * @param DateTimeInterface $fecha
     * @return array
     * @throws Implement\Exception\EmptyResult
     */
    public function fetchByCuentaAndFecha(int $cuenta_id, DateTimeInterface $fecha): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('cuenta_id = ? AND fecha = ?');
        return $this->fetchMany($query, [$cuenta_id, $fecha->format('Y-m-d')]);
    }

    /**
     * @param int $cuenta_id
     * @param DateTimeInterface $fecha
     * @param string $glosa
     * @param int $cargo
     * @param int $abono
     * @param int $saldo
     * @return Model\Contabilidad\Movimiento
     * @throws Implement\Exception\EmptyResult
     */
    public function fetchByCuentaAndFechaAndGlosaAndCargoAndAbonoAndSaldo(int $cuenta_id, DateTimeInterface $fecha, string $glosa, int $cargo, int $abono, int $saldo): Model\Contabilidad\Movimiento
    {
        $len = (int) round(strlen($glosa) * .75);
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where("cuenta_id = ? AND fecha = ? AND SUBSTRING(LOWER(LTRIM(glosa)), 0, {$len}) = SUBSTRING(LOWER(LTRIM(?)), 0, {$len}) AND cargo = ? AND abono = ? AND saldo = ?");
        return $this->fetchOne($query, [$cuenta_id, $fecha->format('Y-m-d'), $glosa, $cargo, $abono, $saldo]);
    }
    public function fetchAmountStartingFrom(int $start, int $amount): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->limit($amount, $start);
        return $this->fetchMany($query);
    }
    public function fetchAmountBySociedadAndMes(int $sociedad_rut, DateTimeInterface $mes, ?int $amount): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select('a.*')
            ->from("{$this->getTable()} a")
            ->joined('JOIN cuenta b ON a.cuenta_id = b.id')
            ->where('b.inmobiliaria = ? AND a.fecha BETWEEN ? AND ?');
        if ($amount !== null) {
            $query->limit($amount);
        }
        return $this->fetchMany($query, [$sociedad_rut, $mes->format('Y-m-01'), $mes->format('Y-m-t')]);
    }

    /**
     * @param int $cuenta_id
     * @param DateTimeInterface $startDate
     * @param DateTimeInterface $endDate
     * @param array $idList
     * @return array
     * @throws Implement\Exception\EmptyResult
     */
    public function fetchMissingInDateRange(int $cuenta_id, DateTimeInterface $startDate, DateTimeInterface $endDate, array $idList = []): array
    {
        $query = $this->connection->getQueryBuilder()
            ->select()
            ->from($this->getTable())
            ->where('cuenta_id = ? AND fecha BETWEEN ? AND ?');
        if (count($idList) > 0) {
            $idString = implode(', ', array_map(function(int $id) {
                return $this->connection->getPDO()->quote($id);
            }, $idList));
            $query->where("id NOT IN ({$idString})");
        }
        return $this->fetchMany($query, [$cuenta_id, $startDate->format('Y-m-d'), $endDate->format('Y-m-d')]);
    }
}
