<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CoreBundle\Facade;

use Doctrine\Common\Collections\Criteria;
use Doctrine\ORM\QueryBuilder;
use Ferienpass\CoreBundle\Entity\Attendance;
use Ferienpass\CoreBundle\Entity\User;
use Ferienpass\CoreBundle\Repository\AttendanceRepository;

class PaymentsFacade
{
    public function __construct(private readonly AttendanceRepository $attendances)
    {
    }

    /** @return Attendance[] */
    public function attendancesDue(?User $user = null): array
    {
        $qb = $this->attendances->createQueryBuilder('attendance')
            ->select('attendance', 'participant')
            ->innerJoin('attendance.participant', 'participant')
        ;

        self::addWhereLogic($qb);

        if ($user instanceof User) {
            $qb
                ->andWhere('participant.user = :user')
                ->setParameter('user', $user->getId())
            ;
        }

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

    public static function addWhereLogic(QueryBuilder $queryBuilder): void
    {
        $queryBuilder
            ->andWhere('attendance.paid <> 1')
            ->andWhere('attendance.payable <> 0')
        ;
    }

    public static function addCriteria(Criteria $criteria): void
    {
        $expr = Criteria::expr();

        $criteria
            ->andWhere($expr->eq('paid', false))
            ->andWhere($expr->eq('payable', true))
        ;
    }
}
