<?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\Controller\Fragment;

use Contao\CoreBundle\Controller\AbstractFragmentController;
use Ferienpass\CoreBundle\ConsentManager\ConsentManager;
use Ferienpass\CoreBundle\ConsentManager\ConsentState;
use Ferienpass\CoreBundle\Entity\Attendance;
use Ferienpass\CoreBundle\Repository\AttendanceRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;

/**
 * The consent-signing page for the legal guardian, reached via the shared
 * consent link ({@see \Ferienpass\CmsBundle\Controller\Page\ConsentLinkController},
 * which also processes the POST). Public — the token in the URL is the
 * credential.
 */
class ConsentSignController extends AbstractFragmentController
{
    public function __construct(private readonly AttendanceRepository $attendances, private readonly ConsentManager $consentManager)
    {
    }

    public function __invoke(Request $request): Response
    {
        $attendance = $this->attendances->findOneBy(['consentToken' => (string) $request->attributes->get('token')]);
        if (!$attendance instanceof Attendance) {
            throw new \RuntimeException('Attendance not found for consent token');
        }

        // Every consent the offer requires (account-level step-1 + per-participant);
        // the guardian signs them all via the link.
        $states = array_values($this->consentManager->forOfferAndParticipants($attendance->getOffer(), [$attendance->getParticipant()]));

        $outstanding = [] !== array_filter($states, static fn (ConsentState $state) => $state->isOutstanding());

        return $this->render('@Contao/fragment/consent_sign.html.twig', [
            'attendance' => $attendance,
            'offer' => $attendance->getOffer(),
            'participant' => $attendance->getParticipant(),
            'states' => $states,
            'outstanding' => $outstanding,
            'error' => $request->attributes->get('error'),
            'signed' => (bool) $request->attributes->get('signed'),
        ]);
    }
}
