<?php

/*
 * This file is part of the Serenity package.
 *
 * (c) CP Creation <web@cpcreation.fr>
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace CpCreation\VitiCore\Cart\Repository;

use CpCreation\VitiCore\Cart\Model\Invoice;
use CpCreation\VitiCore\Repository\BaseRepository;
use Doctrine\Persistence\ManagerRegistry;
use Knp\Component\Pager\Pagination\PaginationInterface;

class InvoiceRepository extends BaseRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Invoice::class);
    }

    public function findLastCredit(): ?Invoice
    {
        [$startOfYear, $startOfNextYear] = $this->createCurrentYearBoundaries();

        $qb = $this->createQueryBuilder('c')
            ->setMaxResults(1)
            ->andWhere('c.numberCredit IS NOT NULL')
            ->andWhere('c.credit = :credit')
            ->andWhere('c.creditAt >= :startOfYear')
            ->andWhere('c.creditAt < :startOfNextYear')
            ->orderBy('c.numberCredit', 'DESC')
            ->setParameter('credit', true)
            ->setParameter('startOfYear', $startOfYear)
            ->setParameter('startOfNextYear', $startOfNextYear);

        return $qb->getQuery()->getOneOrNullResult();
    }

    public function findLastDebit(): ?Invoice
    {
        $qb = $this->createQueryBuilder('c')
            ->setMaxResults(1)
            ->andWhere('c.numberDebit IS NOT NULL')
            ->andWhere('c.year = :year')
            ->orderBy('c.numberDebit', 'DESC')
            ->setParameter('year', $this->getCurrentYear());

        return $qb->getQuery()->getOneOrNullResult();
    }

    public function getNextCreditNumber(): int
    {
        return ($this->findLastCredit()?->getNumberCredit() ?? 0) + 1;
    }

    public function getNextDebitNumber(): int
    {
        return ($this->findLastDebit()?->getNumberDebit() ?? 0) + 1;
    }

    public function findCartsPagination(int $page, int $limit = 5): PaginationInterface
    {
        $qb = $this
            ->createQueryBuilder('i')
            ->orderBy('i.createdAt', 'DESC');

        return $this->pagination($qb->getQuery(), $page, $limit);
    }

    /**
     * @return array{0: \DateTimeImmutable, 1: \DateTimeImmutable}
     */
    private function createCurrentYearBoundaries(): array
    {
        $startOfYear = new \DateTimeImmutable(sprintf('%d-01-01 00:00:00', $this->getCurrentYear()));

        return [$startOfYear, $startOfYear->modify('+1 year')];
    }

    private function getCurrentYear(): int
    {
        return (int) (new \DateTimeImmutable())->format('Y');
    }
}
