<?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 Ferienpass\CoreBundle\ConsentManager\ConsentManager;
use Ferienpass\CoreBundle\Controller\AbstractPrivateFragmentController;
use Ferienpass\CoreBundle\Entity\Attendance;
use Ferienpass\CoreBundle\Repository\AttendanceRepository;
use Symfony\Component\DependencyInjection\Attribute\Autowire;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;

/**
 * Renders the confirmation / status page body for a single attendance. Access is
 * decided by the parent {@see \Ferienpass\CmsBundle\Controller\Page\AttendanceShowController};
 * this fragment only reads the entity and presents it.
 */
class AttendanceShowController extends AbstractPrivateFragmentController
{
    public function __construct(private readonly AttendanceRepository $attendances, private readonly ConsentManager $consentManager, #[Autowire(env: 'MAPBOX_TOKEN')] private readonly string $mapboxToken = '')
    {
    }

    public function __invoke(Request $request): Response
    {
        $attendance = $this->attendances->findOneBy(['uuid' => (string) $request->attributes->get('attendance')]);
        if (!$attendance instanceof Attendance) {
            throw $this->createNotFoundException();
        }

        $offer = $attendance->getOffer();
        $participant = $attendance->getParticipant();

        // Consents the offer requires for this participant (account-level + per-
        // participant). Used read-only for the review section, and — when the
        // attendance still awaits them — as the inline signing form.
        $consents = null !== $participant
            ? array_values($this->consentManager->forOfferAndParticipants($offer, [$participant]))
            : [];

        // Whether this attendance is being held for its consents (the minor-with-
        // guardian flow), i.e. the consents section should be an editable signing
        // form rather than a read-only review.
        $needsConsents = null !== $participant && [] !== $consents
            && ($attendance->isAwaitingConsents() || $attendance->isConsentOutstanding());

        // Durable link the applicant can forward to a legal guardian who signs the
        // consents. Points straight at this canonical page carrying the consent
        // token; the old /einwilligung/{token} route only stays as a redirect shim
        // for links shared before the move, so a freshly generated one skips it.
        $shareUrl = null;
        if ($needsConsents && null !== $attendance->getConsentToken()) {
            $shareUrl = $this->generateUrl('cms_attendance_show', [
                'attendance' => $attendance->getUuid()->toBase58(),
                'token' => $attendance->getConsentToken(),
            ], UrlGeneratorInterface::ABSOLUTE_URL);
        }

        return $this->render('@Contao/fragment/attendance_show.html.twig', [
            'attendance' => $attendance,
            'offer' => $offer,
            'participant' => $participant,
            'access' => 'anon' === $request->attributes->get('access') ? 'anon' : 'auth',
            'formAction' => (string) $request->attributes->get('formAction'),
            'consentError' => $request->attributes->get('consentError'),
            'consents' => $consents,
            'needsConsents' => $needsConsents,
            'shareUrl' => $shareUrl,
            'questions' => $this->questions($attendance),
            'isCreatedByAdmin' => $attendance->isCreatedByAdmin(),
            'mapboxToken' => $this->mapboxToken,
        ]);
    }

    /**
     * The offer's extra application questions paired with this attendance's stored
     * answers, for the read-only review. Definitions live on the offer
     * ({@see \Ferienpass\CoreBundle\Entity\Offer\OfferInterface::getApplicationExtra()}),
     * answers on {@see Attendance::getExtra()} keyed by the question uuid.
     *
     * @return list<array{question: string, type: string, answer: string|bool|int|null}>
     */
    private function questions(Attendance $attendance): array
    {
        $questions = [];
        foreach ($attendance->getOffer()->getApplicationExtra() ?? [] as $extra) {
            if ('' === trim((string) ($extra['question'] ?? ''))) {
                continue;
            }

            $questions[] = [
                'question' => (string) $extra['question'],
                'type' => (string) ($extra['type'] ?? 'txt'),
                'answer' => $attendance->getExtra((string) ($extra['uuid'] ?? '')),
            ];
        }

        return $questions;
    }
}
