<?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\Repository;

use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use Ferienpass\CoreBundle\Entity\ConsentForm;
use Ferienpass\CoreBundle\Entity\Edition;
use Ferienpass\CoreBundle\Entity\Offer\OfferInterface;

class ConsentFormRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, ConsentForm::class);
    }

    public function findForOffer(OfferInterface $offer): array
    {
        return $this->findByOfferOrEdition($offer, $offer->getEdition());
    }

    public function findByOfferOrEdition(OfferInterface $offer, ?Edition $edition): array
    {
        $qb = $this->createQueryBuilder('f');

        $qb->where('f.offer = :offer');
        if ($edition instanceof Edition) {
            $qb->orWhere($qb->expr()->andX(
                $qb->expr()->eq('f.edition', ':edition'),
                $qb->expr()->isNull('f.offer')
            ))
            ->setParameter('edition', $edition);
        }

        // The host declaration ("Einverständnis der Veranstaltenden") is not part
        // of the applicant flow — never surface it in the application form/exports.
        $qb->andWhere("f.subject <> 'host'");

        return $qb
            ->setParameter('offer', $offer)
            ->getQuery()
            ->getResult();
    }
}
