<?php

declare(strict_types=1);

/*
 * Chill is a software for social workers
 *
 * For the full copyright and license information, please view
 * the LICENSE file that was distributed with this source code.
 */

namespace Chill\BudgetBundle\Repository;

use Chill\BudgetBundle\Entity\Charge;
use Chill\PersonBundle\Entity\Household\Household;
use Chill\PersonBundle\Entity\Person;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * ChargeRepository.
 *
 * This class was generated by the Doctrine ORM. Add your own custom
 * repository methods below.
 */
class ChargeRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, Charge::class);
    }

    /**
     * @return Charge[]
     */
    public function findAllByEntity(Household|Person $entity): array
    {
        $qb = $this->createQueryBuilder('c');

        $property = $entity instanceof Person ? 'person' : 'household';

        $qb->where("c.{$property} = :entity")
            ->setParameter('entity', $entity);

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

    public function findByEntityAndDate($entity, \DateTime $date, $sort = null)
    {
        $qb = $this->createQueryBuilder('c');

        $entityStr = $entity instanceof Person ? 'person' : 'household';

        $qb->where("c.{$entityStr} = :entity")
            ->andWhere('c.startDate <= :date')
            ->andWhere('c.endDate > :date OR c.endDate IS NULL');

        if (null !== $sort) {
            $qb->orderBy($sort);
        }

        $qb->setParameters([
            'entity' => $entity,
            'date' => $date,
        ]);

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