<?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\Controller\AbstractPrivateFragmentController;
use Ferienpass\CoreBundle\Entity\Offer\OfferInterface;
use Ferienpass\CoreBundle\Entity\User;
use Ferienpass\CoreBundle\HttpCache\CacheTag;
use Ferienpass\CoreBundle\Repository\OfferRepositoryInterface;
use Symfony\Component\HttpFoundation\Response;

final class ApplicationFormController extends AbstractPrivateFragmentController
{
    public function __invoke(
        string $offerUuid,
        OfferRepositoryInterface $offers,
        ?string $consentToken = null,
        ?string $routeParameters = null,
    ): Response {
        $offer = $offers->findByUuid($offerUuid);
        if (!$offer instanceof OfferInterface) {
            throw $this->createNotFoundException();
        }

        $response = $this->render('@Contao/fragment/application_form.html.twig', [
            'offer' => $offer,
            'consentToken' => $consentToken,
            'routeParameters' => $routeParameters,
        ]);

        $this->tagResponse(CacheTag::offer($offer));

        $user = $this->getUser();
        if ($user instanceof User) {
            $this->tagResponse(CacheTag::user($user));

            foreach ($user->getParticipants() as $participant) {
                $this->tagResponse(CacheTag::participant($participant));
            }

            foreach ($offer->getAttendancesNotHidden() as $attendance) {
                if ($attendance->getParticipant()?->getUser() === $user) {
                    $this->tagResponse(CacheTag::attendance($attendance));
                }
            }
        }

        return $response;
    }
}
