<?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\CmsBundle\View;

use Ferienpass\CoreBundle\Entity\Attendance;
use Symfony\Component\DependencyInjection\Attribute\Exclude;

#[Exclude]
class ApplicationList
{
    private array $attendances;

    public static function fromDatabaseResult(array $attendances): static
    {
        $new = new static();
        $new->attendances = $attendances;

        return $new;
    }

    public function getFilteredAttendances(string $filter): array
    {
        $attendances = $this->attendances;

        usort($attendances, static function (Attendance $a, Attendance $b) {
            return $a->getOffer()->getDateBegin() <=> $b->getOffer()->getDateBegin();
        });

        return array_values(array_filter($attendances, static function (Attendance $attendance) use ($filter) {
            $threshold = new \DateTimeImmutable('-1 day');
            $withdrawnStatuses = ['withdrawn', 'unfulfilled', 'rejected'];
            $isWithdrawnStatus = \in_array($attendance->getStatus(), $withdrawnStatuses, true);

            if ('abgemeldet' === $filter) {
                return $isWithdrawnStatus;
            }
            if ('vergangene' === $filter) {
                return !$isWithdrawnStatus && $attendance->getOffer()->isPast();
            }
            if ('unbezahlte' === $filter) {
                return $attendance->isPayable() && !$attendance->isPaid();
            }

            return !$isWithdrawnStatus
                && (null === $attendance->getOffer()->getDateBegin() || $attendance->getOffer()->getDateBegin() >= $threshold)
                || ($attendance->isPayable() && !$attendance->isPaid());
        }));
    }
}
