src/StartPlatz/Bundle/EventBundle/Controller/EventRegistrationController.php line 468

Open in your IDE?
  1. <?php declare(strict_types=1);
  2. namespace App\StartPlatz\Bundle\EventBundle\Controller;
  3. /**
  4.  * CRITICAL DEPENDENCY WARNING - APPLICATION SYSTEM INTEGRATION
  5.  *
  6.  * This controller handles the event/signup REGISTRATION flow.
  7.  * It has HEAVY DEPENDENCIES on the Application system from StartupBundle.
  8.  *
  9.  * DO NOT modify Application-related code without testing ALL event registration scenarios:
  10.  * - Anonymous (non-member) event registration
  11.  * - Member event registration
  12.  * - Paid event registration with Stripe
  13.  * - Free event registration
  14.  * - Multi-batch event registration
  15.  * - Event registration with validation workflows
  16.  *
  17.  * Extracted from DefaultController (B-60 Phase 2). Uses shared services for dependencies.
  18.  */
  19. use App\StartPlatz\Bundle\EventBundle\Entity\Event;
  20. use App\StartPlatz\Bundle\EventBundle\Entity\EventRepository;
  21. use App\StartPlatz\Bundle\EventBundle\Entity\EventStripePayment;
  22. use App\StartPlatz\Bundle\EventBundle\Service\EventContentResolver;
  23. use App\StartPlatz\Bundle\EventBundle\Service\EventNotificationService;
  24. use App\StartPlatz\Bundle\EventBundle\Service\EventPaymentService;
  25. use App\StartPlatz\Bundle\EventBundle\Service\EventRegistrationService;
  26. use App\StartPlatz\Bundle\EventBundle\Service\EventViewHelper;
  27. use App\StartPlatz\Bundle\EventBundle\Service\MetaConversionsApiService;
  28. use App\StartPlatz\Bundle\EventBundle\Service\SelfCheckinService;
  29. use App\StartPlatz\Bundle\EventBundle\Service\InvalidCheckinException;
  30. use App\StartPlatz\Bundle\MailBundle\Service\MailService;
  31. use App\StartPlatz\Bundle\MemberBundle\Entity\Member;
  32. use App\StartPlatz\Bundle\MemberBundle\Entity\Option;
  33. use App\StartPlatz\Bundle\MemberBundle\Entity\Product;
  34. use App\StartPlatz\Bundle\MemberBundle\Entity\Service;
  35. use App\StartPlatz\Bundle\MonsumBundle\Entity\Customer;
  36. use App\StartPlatz\Bundle\StartupBundle\Entity\Application;
  37. use App\StartPlatz\Bundle\StartupBundle\Entity\Batch;
  38. use App\StartPlatz\Bundle\StartupBundle\Entity\Program;
  39. use App\StartPlatz\Bundle\StartupBundle\Service\ApplicationSpamFilterService;
  40. use App\StartPlatz\Bundle\EventBundle\Form\EventApplicationType;
  41. use App\StartPlatz\Bundle\StartupBundle\Form\ApplicationType;
  42. use App\StartPlatz\Bundle\UserBundle\Entity\User;
  43. use App\StartPlatz\Bundle\UserBundle\LoginService;
  44. use App\StartPlatz\Bundle\MemberBundle\Entity\Team;
  45. use App\StartPlatz\Bundle\WebsiteBundle\MenuTranslationService;
  46. use App\StartPlatz\Bundle\WebsiteBundle\Utility\Utility;
  47. use App\StartPlatz\Ecosystem\Config\Runtime\Service\AlertRecipientService;
  48. use DateTime;
  49. use Doctrine\ORM\EntityManagerInterface;
  50. use Psr\Log\LoggerInterface;
  51. use Sensio\Bundle\FrameworkExtraBundle\Configuration\IsGranted;
  52. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  53. use Symfony\Component\HttpFoundation\Request;
  54. use Symfony\Component\HttpFoundation\Response;
  55. use Symfony\Component\Routing\Annotation\Route;
  56. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  57. class EventRegistrationController extends AbstractController
  58. {
  59.     public function __construct(
  60.         private readonly MailService $mailService,
  61.         private readonly LoginService $loginService,
  62.         private readonly LoggerInterface $logger,
  63.         private readonly EventNotificationService $eventNotificationService,
  64.         private readonly EventPaymentService $eventPaymentService,
  65.         private readonly EventRegistrationService $eventRegistrationService,
  66.         private readonly EventViewHelper $eventViewHelper,
  67.         private readonly EntityManagerInterface $entityManager,
  68.         private readonly MenuTranslationService $menuTranslationService,
  69.         private readonly AlertRecipientService $alertRecipientService,
  70.         private readonly MetaConversionsApiService $metaConversionsApiService,
  71.         private readonly SelfCheckinService $selfCheckinService,
  72.         private readonly ApplicationSpamFilterService $spamFilter,
  73.     ) {
  74.     }
  75.     #[Route('/signup/{slug}'name'signup_show_single')]
  76.     public function signupSingleAction(Request $request$slug)
  77.     {
  78.         $em $this->entityManager;
  79.         /** @var Program $program */
  80.         if (!$program $em->getRepository(Program::class /*Startup Program*/)->findOneBy(['slug' => 'sign-up'])) {
  81.             $this->addFlash('notice''ERROR Sorry, no program found');
  82.             return $this->redirect($this->generateUrl('apply_home', []));
  83.         }
  84.         /** @var Batch $batch */
  85.         if (!$batch $em->getRepository(Batch::class)->findOneBy(['slug' => $slug'program' => $program])) {
  86.             $this->addFlash('notice''ERROR Sorry, no batch found');
  87.             return $this->redirect($this->generateUrl('apply_home', []));
  88.         }
  89.         // Retrieve the UTM parameters from the URL
  90.         $utmParameters = [
  91.             'utmSource'   => $request->query->get('utm_source'),
  92.             'utmMedium'   => $request->query->get('utm_medium'),
  93.             'utmCampaign' => $request->query->get('utm_campaign'),
  94.             'utmTerm'     => $request->query->get('utm_term'),
  95.             'utmContent'  => $request->query->get('utm_content'),
  96.         ];
  97.         $lang 'DE';
  98.         if ($targetPath $request->server->get('REDIRECT_URL')) {
  99.             $lang $this->menuTranslationService->getLang($targetPath);
  100.         }
  101.         $batchIsOpen $batch && $em->getRepository(Batch::class)->isBatchApplicationOpen($batch);
  102.         $form    null;
  103.         $program null;
  104.         $member  null;
  105.         $application null;
  106.         $product     null;
  107.         $editFeedback "";
  108.         $settings     = [];
  109.         $action       "";
  110.         $customersArr = [];
  111.         if ($batchIsOpen) {
  112.             $program $batch->getProgram();
  113.             $settings $this->eventViewHelper->getProgramSettings($program$batch);
  114.             $batch $em->getRepository(Batch::class)->updateNumbers($batch);
  115.             /** @var User $user */
  116.             if ($user $this->getUser()) {
  117.                 $member $em->getRepository(Member::class)->find($user->getMemberId());
  118.             }
  119.             $action   $request->get('action');
  120.             $application $this->eventRegistrationService->getOrCreateApplication($request$batch$program$member$lang$settings$utmParametersnull);
  121.             if ($batch->getPriceInEuroCent() > 0) {
  122.                 $route                   "signup_show_single";
  123.                 $routeParameters["slug"] = $batch->getSlug();
  124.                 $application $this->handleAction($request$member$application$batch$lang$route$routeParameters$settings);
  125.                 if (is_string($application)) {
  126.                     // Handle redirect
  127.                     return $this->redirect($application);
  128.                 }
  129.             }
  130.             if ($user && in_array($action, ["needsloginvalidation""needsemailverification"])) {
  131.                 $response $this->validateEventApplication($application$member$settings$batch$lang);
  132.                 $application $response['data']['application'];
  133.             }
  134.             if ($batch->getPriceInEuroCent() > && $batch->getProductId()) {
  135.                 if (!$product $em->getRepository(Product::class /*Product Member*/)->find($batch->getProductId())) {
  136.                     $this->addFlash('notice''ERROR configuration not found');
  137.                     return $this->redirect($this->generateUrl('events_list'));
  138.                 }
  139.                 if ($application->getId() && isset($member) && $member->getId()) {
  140.                     $customersArr $em->getRepository(Customer::class)->findValidMonsumCustomersByMemberAndAccount($member$product->getAccount(), false);
  141.                 }
  142.             }
  143.             $form $this->createForm(ApplicationType::class, $application, ['settings' => $settings'program' => $program'batch' => $batch]);
  144.             $form->handleRequest($request);
  145.             ##############################################################
  146.             ##   form validation starts here                            ##
  147.             ##############################################################
  148.             if ($form->isSubmitted() && $form->isValid()) {
  149.                 $application $em->getRepository(Application::class)->cleanApplicationData($application);
  150.                 $adminEmail  $application->getEmail();
  151.                 if ($member) {
  152.                     $memberToBeRegistered $member;
  153.                     $isExistingMember     true;
  154.                 } else {
  155.                     $response $this->eventRegistrationService->resolveOrCreateMember($application);
  156.                     $isExistingMember     $response['data']['isExistingMember'];
  157.                     $memberToBeRegistered $response['data']['memberToBeRegistered'];
  158.                 }
  159.                 $memberToBeRegistered->setIsExistingMember($isExistingMember);
  160.                 // fill application with memberId and teamId and discount information
  161.                 $application $this->eventRegistrationService->bindMemberToApplication($application$memberToBeRegistered$batch);
  162.                 if (!$batch->isMultipleApplicationsPerMember()) {
  163.                     // check if there is already an application to this event == batch with that batchId and memberId
  164.                     if ($existingApplication $em->getRepository(Application::class)->findOneBy(['batchId' => $batch->getId(), 'memberId' => $memberToBeRegistered->getId()])) {
  165.                         // there are two applications - the latest application will always win
  166.                         $fields     Utility::getEntityFieldsArray($application, ['id','assessments''votesRegistered''applicationStatus''editStatus''editMessage''lastChangeUser','history','extraFields','lastModified','createdAt']);
  167.                         $storedData Utility::fillDataByObject($existingApplication$fields);
  168.                         $updatedData Utility::fillDataByObject($application$fields);
  169.                         $differences array_diff_assoc($updatedData$storedData);
  170.                         $application $existingApplication;
  171.                         $application $this->updateApplication($application$differences);
  172.                         $application->setIsExistingApplication(true);
  173.                     }
  174.                 }
  175.                 if (isset($settings['extraFields'])) {
  176.                     $application $this->eventViewHelper->getExtraFieldsData($application$settings$form);
  177.                 }
  178.                 $dummyEvent = new Event();
  179.                 $isPaidEvent $this->eventPaymentService->isPaidEvent($application$batch$dummyEvent);
  180.                 $hasToPay    $this->eventPaymentService->isPaymentRequired($application$memberToBeRegistered$dummyEvent$settings$batch);
  181.                 if ($isPaidEvent && $hasToPay) {
  182.                     // falls es bereits einen zugänglichen Monsum Account für diese Person gibt
  183.                     $customersArr $em->getRepository(Customer::class)->findValidMonsumCustomersByMemberAndAccount($memberToBeRegistered$product->getAccount(), false);
  184.                     $dummyEvent = new Event();
  185.                     $application  $this->eventPaymentService->updateApplicationWithStepOneInfo($application$memberToBeRegistered$dummyEvent);
  186.                     // Application in Datenbank schreiben, sonst kann im nächsten Schritt keine appId übergeben werden
  187.                     $application $em->getRepository(Application::class)->setApplication($application);
  188.                 } else {
  189.                     $route 'signup_show_single';
  190.                     $routeParameters $request->get('_route_params');
  191.                     $response $this->eventRegistrationService->processRegistrationWithoutPayment($isExistingMember$user$memberToBeRegistered$application$settings$lang$adminEmail$batch$route$routeParameters);
  192.                     // Bei SignUps: Prüfe ob goToPage gesetzt ist
  193.                     if ($batch->getGoToPage()) {
  194.                         // Weiterleitung zu goToPage (kann URL oder interner Pfad sein)
  195.                         return $this->redirect($batch->getGoToPage());
  196.                     }
  197.                     // Ansonsten auf SignUp-Seite bleiben - keine Weiterleitung
  198.                     $application  $response['data']['application'];
  199.                     $member       $response['data']['member'];
  200.                 }
  201.             }
  202.         }
  203.         // Default to legacy template for backward compatibility
  204.         $view '@StartPlatzEventBundle/Default/signup-single.html.twig';
  205.         // Check for pageTemplate field (new approach)
  206.         if ($batch->getPageTemplate()) {
  207.             switch ($batch->getPageTemplate()) {
  208.                 case 'modern':
  209.                 case 'flexible':
  210.                     $view '@StartPlatzEventBundle/Default/signup-single.modern.html.twig';
  211.                     break;
  212.                 case 'petition':
  213.                     $view '@StartPlatzEventBundle/Default/signup-single.deepSeekPetition.html.twig';
  214.                     break;
  215.                 case 'legacy':
  216.                 default:
  217.                     $view '@StartPlatzEventBundle/Default/signup-single.html.twig';
  218.                     break;
  219.             }
  220.         }
  221.         // Keep backward compatibility for existing petition SignUps using JSON settings
  222.         elseif (array_key_exists('signupTemplate'$settings)) {
  223.             $view '@StartPlatzEventBundle/Default/signup-single.deepSeekPetition.html.twig';
  224.         }
  225. // Build the metaData array using only the $batch object (landing page fields)
  226.         $metaData = [
  227.             // SEO Tag: Description (using landingPageDescription)
  228.             'description'       => $batch->getLandingPageDescription(),
  229.             // Canonical URL (the domain remains lowercase)
  230.             'canonical'         => 'https://www.startplatz.de/signup/' urlencode($batch->getSlug()),
  231.             // Open Graph Tags for Social Sharing (using landingPage fields)
  232.             'ogTitle'           => $batch->getLandingPageTitle(),
  233.             'ogDescription'     => $batch->getLandingPageDescription(),
  234.             'ogImage'           => $batch->getLandingPageSocialImage(),
  235.             'ogUrl'             => 'https://www.startplatz.de/signup/' urlencode($batch->getSlug()),
  236.             'ogType'            => 'website',
  237.             'ogSiteName'        => 'STARTPLATZ'// Protected trademark must be uppercase
  238.             // Twitter Card Tags (using landingPage fields)
  239.             'twitterCard'       => 'summary'// or "summary_large_image" if preferred
  240.             'twitterTitle'      => $batch->getLandingPageTitle(),
  241.             'twitterDescription'=> $batch->getLandingPageDescription(),
  242.             'twitterImage'      => $batch->getLandingPageSocialImage(),
  243.             'twitterSite'       => '@STARTPLATZ'// Protected trademark must be uppercase
  244.             // Title for the page (taken from landingPageTitle)
  245.             'title'             => $batch->getLandingPageTitle(),
  246.             // Additional Landing Page Fields
  247.             'landingPageCss'            => $batch->getLandingPageCss(),
  248.             'landingPageContent'        => $batch->getLandingPageContent(),
  249.             'landingPageJs'             => $batch->getLandingPageJs(),
  250.             'landingPageFooterTemplate' => $batch->getLandingPageFooterTemplate(),
  251.         ];
  252.         return $this->render($view, [
  253.             'batch'          => $batch,
  254.             'program'        => $program,
  255.             'settings'       => $settings,
  256.             'metaData'       => $metaData,
  257.             'form'           => $form $form->createView() : $form,
  258.             'application'    => $application,
  259.             'action'         => $action,
  260.             'batchIsOpen'    => $batchIsOpen,
  261.             'customersArr'   => $customersArr,
  262.             'member'         => $member,
  263.             'isMultiBatchEvent' => false,  // Signups have no event, so no multi-batch
  264.             'utmParameters'  => $utmParameters,
  265.             'phrases'        => $em->getRepository(Option::class)->getApplicationPhrases($program$batchfalse$lang),
  266.             'editFeedback'   => $editFeedback,
  267.             'templateVars'   => [],
  268.             'preview'             => $request->get('preview'),
  269.             'lang'            => $lang,
  270.             'targetRoute'     => "signup_show_single",
  271.             'targetRouteSlug' => $batch->getSlug(),
  272.             'targetPath'      => $targetPath,
  273.         ]);
  274.     }
  275.     ### section signup ends here ###
  276.     #[Route('/allmeda/event/application/send-confirmation-mail/{applicationId}'name'allmeda_event_send-confirmation-mail')]
  277.     /**
  278.      * @IsGranted("ROLE_ADMIN")
  279.      */
  280.     public function sendConfirmationMailViaPublicFunction($applicationId)
  281.     {
  282.         $em $this->entityManager;
  283.         $application $em->getRepository(Application::class)->find($applicationId);
  284.         $member $em->getRepository(Member::class)->find($application->getMemberId());
  285.         $batch $em->getRepository(Batch::class)->find($application->getBatchId());
  286.         $feedback $this->eventNotificationService->sendConfirmationMail(null$member, [], $application$batch);
  287.         $response "SUCCESS Confirmation Mail has been sent";
  288.         return new Response($response);
  289.     }
  290.     #[Route('/event-confirmation/{slug}/'name'event_confirmation')]
  291.     public function eventConfirmationAction(Request $request$slug)
  292.     {
  293.         $em $this->entityManager;
  294.         $event $this->findEventBySlug($slug);
  295.         if (!$event) {
  296.             $this->addFlash('notice''ERROR Event not found');
  297.             return $this->redirectToRoute('events_list');
  298.         }
  299.         $seriesEvents = [];
  300.         if ($seriesTag $event->getSeriesTag()) {
  301.             /** @var EventRepository $eventRepository */
  302.             $eventRepository $em->getRepository(Event::class);
  303.             $seriesEvents $eventRepository->findBySeriesTag($seriesTag'', ['startDate' => 'DESC']);
  304.         }
  305.         $embed $request->get('embed');
  306.         $batch $em->getRepository(Batch::class)->findOneBy(['programId'=>27'eventId'=>$event->getId(), 'status'=>'active''access' =>'anonymous']);
  307.         if (!$batch) {
  308.             $this->addFlash('notice''ERROR No active batch found for this event');
  309.             return $this->redirectToRoute('events_list');
  310.         }
  311.         $program $batch->getProgram();
  312.         $action   $request->get('action');
  313.         $applicationId $request->get('app');
  314.         $route                   "event_confirmation";
  315.         $routeParameters["slug"] = $event->getSlug();
  316.         $settings = [];
  317.         $member   false;
  318.         $application = new Application();
  319.         // Load application first, then determine language
  320.         if ($applicationId){
  321.             if (!$application $em->getRepository(Application::class)->find($applicationId)){
  322.                 $this->addFlash('notice''ERROR Application with ID '.$applicationId.' not found');
  323.                 return $this->redirectToRoute('events_list');
  324.             }
  325.         }
  326.         // Language detection: Priority is Application > Event > Default DE
  327.         // This ensures user's language choice persists through Stripe redirect
  328.         $lang = ($application && $application->getId() && $application->getLang())
  329.             ? $application->getLang()
  330.             : ($event->getLang() ?? 'DE');
  331.         // Handle action after language is determined
  332.         if ($applicationId && $action){
  333.             $application $this->handleAction($request$member$application$batch$lang$route$routeParameters$settings);
  334.             if (is_string($application)) {
  335.                 // Handle redirect
  336.                 return $this->redirect($application);
  337.             }
  338.         }
  339.         // Generate the absolute base URL based on the route and parameters
  340.         $baseURL $this->generateUrl('event_show_single', ['slug' => $slug], UrlGeneratorInterface::ABSOLUTE_URL);
  341.         // UTM parameters for the promotion URL
  342.         $promotionUtmParameters = [
  343.             'utm_source'   => 'affiliate',
  344.             'utm_medium'   => is_numeric($application->getMemberId()) ? $application->getMemberId() : '',
  345.             'utm_campaign' => 'event:' $event->getId(),
  346.             'utm_term'     => '',
  347.             'utm_content'  => '',
  348.         ];
  349.         $promotionUrl $em->getRepository(Batch::class)->generatePromotionUrl($baseURL$promotionUtmParameters);
  350.         $view '@StartPlatzEventBundle/Default/event-confirmation.html.twig';
  351.         if ($embed){
  352.             $view '@StartPlatzEventBundle/Default/event-confirmation.embed.html.twig';
  353.         }
  354.         if ($event->getTwigFile() == 'winter-2025' ){
  355.             $view '@StartPlatzEventBundle/Default/event-confirmation.winter-2025.html.twig';
  356.         }
  357.         if ($event->getTwigFile() == 'style-ecodynamics' ){
  358.             $view '@StartPlatzEventBundle/Default/event-confirmation.style-ecodynamics.html.twig';
  359.         }
  360.         if ($event->getTwigFile() == 'style-ai-hub' ){
  361.             $view '@StartPlatzEventBundle/Default/event-confirmation.style-ai-hub.html.twig';
  362.         }
  363.         if ($event->getTwigFile() == 'style-startplatz' ){
  364.             $view '@StartPlatzEventBundle/Default/event-confirmation.style-ai-hub.html.twig';
  365.         }
  366.         return $this->render($view, [
  367.             'event'         => $event,
  368.             'seriesEvents'  => $seriesEvents,
  369.             'promotionUrl'   => $promotionUrl,
  370.             'batch'          => $batch,
  371.             'settings'       => $settings,
  372.             'application'    => $application,
  373.             'action'         => $action,
  374.             'member'         => $member,
  375.             'speakers'       => $this->eventViewHelper->getSpeakers($event),
  376.             'phrases'        => $em->getRepository(Option::class)->getApplicationPhrases($program$batchfalse$lang),
  377.             'templateVars'   => [],
  378.             'embed'          => $embed,
  379.             'lang'            => $lang,
  380.             'isMultiBatchEvent' => $event->isMultiBatchEvent(),
  381.         ]);
  382.     }
  383.     #[Route('/event/{slug}/'name'event_show_single')]
  384.     #[Route('/event/{slug}/{date}'name'event_show_single_by_date'requirements: ['date' => '\d{4}-\d{2}-\d{2}'])]
  385.     public function eventSingleAction(Request $request$slug$date null)
  386.     {
  387.         ##event-single
  388.         if ($slug == 'ai-bootcamp-koeln-2024-01-18') return $this->redirect$this->generateUrl('event_show_single', array('slug' => 'ai-bootcamp-koeln-2024-01-29')) );
  389.         if ($slug == 'ai-summer-school-koeln-2208') return $this->redirect$this->generateUrl('event_show_single', array('slug' => 'ai-bootcamp-koeln-1109')) );
  390.         if ($slug == 'ai-summer-school-duesseldorf-2908') return $this->redirect$this->generateUrl('event_show_single', array('slug' => 'ai-bootcamp-duesseldorf-2609')) );
  391.         if ($slug == 'ai-disruptme-marketing-in-unternehmen-koeln-2023-10-19') return $this->redirect$this->generateUrl('event_show_single', array('slug' => 'ai-disruptme-marketing-in-unternehmen-koeln-2024-01-31')) );
  392.         if ($slug == 'ai-disruptme-publisher-koeln-2023-10-18') return $this->redirect$this->generateUrl('event_show_single', array('slug' => 'ai-disruptme-publisher-duesseldorf-2024-03-20')) );
  393.         if ($slug == 'ai-disruptme-travel-tourismus-duesseldorf-2023-11-09') return $this->redirect$this->generateUrl('event_show_single', array('slug' => 'ai-disruptme-travel-tourismus-duesseldorf-2024-02-22')) );
  394.         if ($slug == 'genai-ki-app-no-code-backend-fuer-ki-anwendung-2024-05-28') return $this->redirect$this->generateUrl('event_show_single', array('slug' => 'genai-ki-anwendung-bauen-frontend-ux-ui-2024-05-21')) );
  395.         if ($slug == 'ai-barcamp-generative-ki') return $this->redirect$this->generateUrl('event_show_single', array('slug' => 'ai-barcamp-logistik')) );
  396.         if ($slug == 'genai-generative-ki-zertifikat-ki-kompetenz-erwerben-2025-05-20') return $this->redirect$this->generateUrl('event_show_single', array('slug' => 'ki-kompetenzpflicht-zertifikat-artikel-4-2025-05-20')) );
  397.         // Retrieve the UTM parameters from the URL
  398.         $utmParameters = [
  399.             'utmSource'   => $request->query->get('utm_source') ?? 'homepage',
  400.             'utmMedium'   => $request->query->get('utm_medium'),
  401.             'utmCampaign' => $request->query->get('utm_campaign'),
  402.             'utmTerm'     => $request->query->get('utm_term'),
  403.             'utmContent'  => $request->query->get('utm_content'),
  404.         ];
  405.         $em $this->entityManager;
  406.         /** @var Event $event */
  407.         $event $this->findEventBySlug($slug);
  408.         if (!$event) {
  409.             $this->addFlash('notice''ERROR Veranstaltung nicht gefunden');
  410.             return $this->redirectToRoute('events_list');
  411.         }
  412.         // Handle event visibility: redirect if not published or previewed without user session.
  413.         $response $this->handleEventStatus($event$request);
  414.         if ($response) {
  415.             return $response;
  416.         }
  417.         $seriesEvents = [];
  418.         if ($seriesTag $event->getSeriesTag()) {
  419.             /** @var EventRepository $eventRepository */
  420.             $eventRepository $em->getRepository(Event::class);
  421.             $seriesEvents $eventRepository->findBySeriesTag($seriesTag'', ['startDate' => 'DESC']);
  422.         }
  423.         // Language detection with priority: URL parameter > Event default
  424.         // This ensures ?lang=en parameter works for bilingual events
  425.         $lang strtoupper($request->query->get('lang''')) ?: ($event->getLang() ?? 'DE');
  426.         $embed $request->get('embed');
  427.         $eventbriteId   $event->getEventbriteId();
  428.         $isEventbriteOnly $event->getTicketing() > '';
  429.         $applicationUrl $event->getApplicationUrl();
  430.         // Multi-batch aware logic
  431.         $futureBatches = [];
  432.         $allBatches = [];
  433.         if ($event->isMultiBatchEvent()) {
  434.             $allBatches $em->getRepository(Batch::class)->findAllBatchesByEvent($event);
  435.             if ($date) {
  436.                 // User selected a specific date
  437.                 $batch $em->getRepository(Batch::class)->findBatchByEventAndDate($event$date);
  438.                 if (!$batch) {
  439.                     // Invalid date, redirect to main event page
  440.                     $this->addFlash('notice''Der gewählte Termin ist nicht verfügbar.');
  441.                     return $this->redirectToRoute('event_show_single', ['slug' => $slug]);
  442.                 }
  443.             } else {
  444.                 // No date selected, show next upcoming batch
  445.                 $batch $em->getRepository(Batch::class)->findNextOpenBatchByEvent($event);
  446.                 // Redirect to canonical date URL
  447.                 if ($batch && $batch->getStartDate()) {
  448.                     return $this->redirectToRoute('event_show_single_by_date', [
  449.                         'slug' => $slug,
  450.                         'date' => $batch->getStartDate()->format('Y-m-d'),
  451.                     ], 302);
  452.                 }
  453.                 // Fallback: no open batch found — use any batch for display context
  454.                 if (!$batch && !empty($allBatches)) {
  455.                     $batch $allBatches[0];
  456.                 }
  457.             }
  458.             // Get all future batches for the selector
  459.             $futureBatches $em->getRepository(Batch::class)->findFutureBatchesByEvent($event10);
  460.             // Get past batches for archive display
  461.             $pastBatches $em->getRepository(Batch::class)->findPastBatchesByEvent($event10);
  462.         } else {
  463.             // Single batch event - keep existing logic
  464.             // Try to find active batch first, then fall back to completed batch for display
  465.             $batch $em->getRepository(Batch::class)->findOneBy(['programId'=>27'eventId'=>$event->getId(), 'status'=>'active''access' =>'anonymous']);
  466.             if (!$batch) {
  467.                 // No active batch found, look for completed batch (for past events that need to display)
  468.                 $batch $em->getRepository(Batch::class)->findOneBy(['programId'=>27'eventId'=>$event->getId(), 'status'=>'completed''access' =>'anonymous']);
  469.             }
  470.             if ($batch) {
  471.                 $allBatches = [$batch];
  472.             }
  473.         }
  474.         $batchIsOpen $batch && $batch->isEventRegistrationOpen();
  475.         // Multi-batch: batch-level external URL overrides event-level
  476.         if ($batch && $batch->getExternalRegistrationUrl()) {
  477.             $applicationUrl $batch->getExternalRegistrationUrl();
  478.         }
  479.         $form    null;
  480.         $program null;
  481.         $application null;
  482.         $product     null;
  483.         $editFeedback "";
  484.         $settings     = [];
  485.         $action       "";
  486.         $customersArr = [];
  487.         $member null;
  488.         /** @var User $user */
  489.         if ($user $this->getUser()) {
  490.             $member $em->getRepository(Member::class)->find($user->getMemberId());
  491.         }
  492.         if ($batch && !$isEventbriteOnly) {
  493.             $program $batch->getProgram();
  494.             // Event-Batches gehoeren zu Program 27 — Fallback wenn programId fehlt
  495.             if (!$program && $batch->isEventBatch()) {
  496.                 $program $em->getRepository(Program::class)->find(27);
  497.             }
  498.         }
  499.         if ($batchIsOpen && !$isEventbriteOnly && $program) {
  500.             $settings $this->eventViewHelper->getProgramSettings($program$batch);
  501.             $batch $em->getRepository(Batch::class)->updateNumbers($batch);
  502.             $action   $request->get('action');
  503.             $referral $request->get('referral');
  504.             // do some exceptions
  505.             if ($member && isset($settings['batchType'])) {
  506.                 if ($settings['batchType'] == 'memberDocumentation'){
  507.                     // check if member
  508.                     if ($em->getRepository(Application::class)->findApplicationsByAiFridayBatchSlugAndMemberId($member->getId()))
  509.                     {
  510.                         if (!$em->getRepository(Application::class)->findOneBy(['memberId'=>$member->getId(), 'batchId' => $batch->getId()])){
  511.                             $memberTeam  $em->getRepository(Team::class)->find($member->getTeamId());
  512.                             $adminEmail  $member->getEmail();
  513.                             $application $em->getRepository(Application::class)->createApplicationIfNotExists($program$batch$memberTeam$member$adminEmail);
  514.                             $application->setBatchStatus('applicant');
  515.                             $application->setApplicationStatus('applied');
  516.                             $em->persist($application);
  517.                             $em->flush();
  518.                             $batch $em->getRepository(Batch::class)->updateNumbers($batch);
  519.                         }
  520.                     }
  521.                 }
  522.             }
  523.             $application $this->eventRegistrationService->getOrCreateApplication($request$batch$program$member$lang$settings$utmParameters$event);
  524.             if ($referral && $application->getRealPriceinEuroCent() > 0) {
  525.                 if ($recommendedByMember $em->getRepository(Member::class)->find($referral)) {
  526.                     if ($neededTag $settings['isRecommendedBy'] ?? '') {
  527.                         if (Utility::contains($recommendedByMember->getTags(), $neededTag)) {
  528.                             $application->setRealPriceinEuroCent(0);
  529.                             $application->setDiscountReason("geworben durch {$recommendedByMember->getName()}");
  530.                             $application->setDiscountPercent(100);
  531.                         }
  532.                     }
  533.                 }
  534.             }
  535.             if ($user && in_array($action, ["needsloginvalidation""needsemailverification"])) {
  536.                 $response $this->validateEventApplication($application$member$settings$batch$lang);
  537.                 $application $response['data']['application'];
  538.             }
  539.             // Only check for Monsum product if we're not using Stripe
  540.             $hasStripeConfig = ($batch && $batch->getStripePriceId()) || ($event && $event->getStripePriceId());
  541.             if ($batch->getPriceInEuroCent() > && $batch->getProductId() && !$hasStripeConfig) {
  542.                 if (!$product $em->getRepository(Product::class /*Product Member*/)->find($batch->getProductId())) {
  543.                     $this->addFlash('notice''ERROR configuration not found');
  544.                     return $this->redirect($this->generateUrl('events_list'));
  545.                 }
  546.             }
  547.             $formType $batch->isEventBatch() ? EventApplicationType::class : ApplicationType::class;
  548.             $form $this->createForm($formType$application, [
  549.                 'settings' => $settings,
  550.                 'program' => $program,
  551.                 'batch' => $batch,
  552.                 'csrf_protection' => $embed false true,
  553.             ]);
  554.             $form->handleRequest($request);
  555.             ##############################################################
  556.             ##   form validation starts here                            ##
  557.             ##############################################################
  558.             if ($form->isSubmitted() && $form->isValid()) {
  559.                 $application $em->getRepository(Application::class)->cleanApplicationData($application);
  560.                 $adminEmail $application->getEmail();
  561.                 $email $application->getEmail();
  562.                 // Tarpit: Spam-Treffer → still redirecten, kein Persist/Mail/Stripe.
  563.                 // Bot sieht scheinbaren Erfolg und versucht nicht weiter; B-129.
  564.                 $spamResult $this->spamFilter->checkSubmission([
  565.                     'firstName' => $application->getFirstName() ?? '',
  566.                     'lastName'  => $application->getLastName() ?? '',
  567.                     'email'     => $email ?? '',
  568.                 ], $request);
  569.                 if ($spamResult->isSpam) {
  570.                     $this->logger->info('Application spam dropped (tarpit)', [
  571.                         'batchId' => $batch->getId(),
  572.                         'eventId' => $event->getId(),
  573.                         'reason'  => $spamResult->reason,
  574.                         'score'   => $spamResult->score,
  575.                     ]);
  576.                     return $this->redirectToRoute('event_show_single', ['slug' => $slug]);
  577.                 }
  578.                 if (!Utility::validateEmail($email)){
  579.                     $this->addFlash('notice''ERROR Incorrect email adress. Please check your email adress!');
  580.                 } else {
  581.                     // maxApplicants
  582.                     if (isset($settings['maxApplicants'])) {
  583.                         $applicants $em->getRepository(Application::class)->findBy(['batchId' => $batch->getId(), 'applicationStatus' => 'applied']);
  584.                         $currentApplicantsCount count($applicants);
  585.                         if ($currentApplicantsCount >= $settings['maxApplicants']) {
  586.                             $this->addFlash('notice''ERROR Leider sind alle verfügbaren Plätze bereits vergeben.');
  587.                             return $this->redirectToRoute('event_show_single', ['slug' => $slug]);
  588.                         }
  589.                     }
  590.                     // isErrorDetectionOn
  591.                     if (isset($settings['isErrorDetectionOn']) and $settings['isErrorDetectionOn']) {
  592.                         $this->addFlash('notice''ERROR There was a problem in processing your application. Please contact support@startplatz.de');
  593.                         return $this->redirectToRoute('event_show_single', ['slug' => $slug]);
  594.                     }
  595.                     if ($member) {
  596.                         $memberToBeRegistered $member;
  597.                         $isExistingMember true;
  598.                     } else {
  599.                         $response $this->eventRegistrationService->resolveOrCreateMember($application);
  600.                         $isExistingMember $response['data']['isExistingMember'];
  601.                         $memberToBeRegistered $response['data']['memberToBeRegistered'];
  602.                     }
  603.                     $memberToBeRegistered->setIsExistingMember($isExistingMember);
  604.                     // fill application with memberId and teamId and discount information
  605.                     $application $this->eventRegistrationService->bindMemberToApplication($application$memberToBeRegistered$batch);
  606.                     if (!$batch->isMultipleApplicationsPerMember()) {
  607.                         // check if there is already an application to this event == batch with that batchId and memberId
  608.                         if ($existingApplication $em->getRepository(Application::class)->findOneBy(['batchId' => $batch->getId(), 'memberId' => $memberToBeRegistered->getId()])) {
  609.                             // there are two applications - the latest application will always win
  610.                             $fields Utility::getEntityFieldsArray($application, ['id''assessments''votesRegistered''applicationStatus''editStatus''editMessage''lastChangeUser''history''extraFields''lastModified''createdAt']);
  611.                             $storedData Utility::fillDataByObject($existingApplication$fields);
  612.                             $updatedData Utility::fillDataByObject($application$fields);
  613.                             $differences array_diff_assoc($updatedData$storedData);
  614.                             $application $existingApplication;
  615.                             $application $this->updateApplication($application$differences);
  616.                             $application->setIsExistingApplication(true);
  617.                         }
  618.                     }
  619.                     if (isset($settings['extraFields'])) {
  620.                         $application $this->eventViewHelper->getExtraFieldsData($application$settings$form);
  621.                     }
  622.                     // FEAT-010: Lead-Capture — Save + Track + Redirect, kein Payment
  623.                     if ($batch->getRegistrationMode() === 'lead-capture') {
  624.                         $application->setApplicationStatus('applied');
  625.                         $application $em->getRepository(Application::class)->setApplication($application$memberToBeRegistered);
  626.                         $this->metaConversionsApiService->sendCompleteRegistration($application$event$request$request->request->get('_meta_event_id'));
  627.                         if ($batch->getRegistrationRedirectUrl()) {
  628.                             return $this->redirect($batch->getRegistrationRedirectUrl());
  629.                         }
  630.                         return $this->redirectToRoute('event_show_single', ['slug' => $slug]);
  631.                     }
  632.                     $isPaidEvent $this->eventPaymentService->isPaidEvent($application$batch$event);
  633.                     // Debug logging for ki-campus payment exception
  634.                     $this->logger->info('Payment exception check', [
  635.                         'member_exists' => $member true false,
  636.                         'member_id' => $member $member->getId() : null,
  637.                         'member_email' => $member $member->getEmail() : null,
  638.                         'member_tags' => $member $member->getTags() : null,
  639.                         'memberToBeRegistered_id' => $memberToBeRegistered->getId(),
  640.                         'memberToBeRegistered_email' => $memberToBeRegistered->getEmail(),
  641.                         'memberToBeRegistered_tags' => $memberToBeRegistered->getTags(),
  642.                         'batch_isFreeForKiCampus' => $batch $batch->getIsFreeForKiCampus() : null,
  643.                         'event_isFreeForKiCampus' => $event $event->getIsFreeForKiCampus() : null,
  644.                     ]);
  645.                     // Always use memberToBeRegistered for payment exception check
  646.                     $hasToPay $this->eventPaymentService->isPaymentRequired($application$memberToBeRegistered$event$settings$batch);
  647.                     if ($isPaidEvent && $hasToPay) {
  648.                         $application $this->eventPaymentService->updateApplicationWithStepOneInfo($application$memberToBeRegistered$event);
  649.                         $isAdmin $user && $user->getIsAdmin();
  650.                         $discountCode $request->get('discount');
  651.                         $paymentLink $this->eventPaymentService->createStripeCheckoutUrl($application$memberToBeRegistered$event$batch$embed$isAdmin$discountCode);
  652.                         if (is_string($paymentLink)) {
  653.                             // B-128: Meta CAPI Lead (paid event, before Stripe redirect)
  654.                             $this->metaConversionsApiService->sendLead($application$event$request$request->request->get('_meta_event_id'));
  655.                             // call stripe and let applicant pay for the ticket
  656.                             if ($embed){
  657.                                 return $this->render('@StartPlatzEventBundle/Default/iframe_redirect.html.twig', [
  658.                                     'targetUrl' => $paymentLink
  659.                                 ]);
  660.                             } else {
  661.                                 return $this->redirect($paymentLink);
  662.                             }
  663.                         } elseif ($paymentLink === null) {
  664.                             // No Stripe config — check Monsum
  665.                             if ($product) {
  666.                                 $customersArr $em->getRepository(Customer::class)->findValidMonsumCustomersByMemberAndAccount($memberToBeRegistered$product->getAccount(), false);
  667.                             }
  668.                         }
  669.                         // paymentLink === false: Stripe was configured but failed — fall through to render page
  670.                         // Application in Datenbank schreiben, sonst kann im nächsten Schritt keine appId übergeben werden
  671.                         $application $em->getRepository(Application::class)->setApplication($application);
  672.                     } else {
  673.                         $route 'event_show_single';
  674.                         $routeParameters $request->get('_route_params');
  675.                         if (!array_key_exists('slug'$routeParameters)) {
  676.                             $routeParameters['slug'] = $event->getSlug();
  677.                         }
  678.                         $response $this->eventRegistrationService->processRegistrationWithoutPayment($isExistingMember$user$memberToBeRegistered$application$settings$lang$adminEmail$batch$route$routeParameters);
  679.                         if ($response['status'] == 'error') {
  680.                             $targetPath $response['data']['targetPath'];
  681.                             return $this->redirect($targetPath);
  682.                         }
  683.                         $application $response['data']['application'];
  684.                         $member $response['data']['member'];
  685.                         // B-128: Meta CAPI Lead (free event, after registration)
  686.                         $this->metaConversionsApiService->sendLead($application$event$request$request->request->get('_meta_event_id'));
  687.                         if ($this->shouldSetAiHubMembership($settings$application->getApplicationStatus())) {
  688.                             $aiHubStatus $settings["setAiHubMembership"];
  689.                             $service $this->configureServiceForAiHub($aiHubStatus$event->getStartDate());
  690.                             $reason "participated in event with id={$event->getId()} and title={$event->getTitle()}";
  691.                             $em->getRepository(Member::class)->setAiHubMembership($service$member$reason);
  692.                         }
  693.                     }
  694.                 }
  695.             }
  696.         }
  697.         $promotionUrl null;
  698.         if ($user && $batch) {
  699.             // Generate the absolute base URL based on the route and parameters
  700.             $baseURL $this->generateUrl('event_show_single', ['slug' => $slug], UrlGeneratorInterface::ABSOLUTE_URL);
  701.             // UTM parameters for the promotion URL
  702.             $promotionUtmParameters = [
  703.                 'utm_source' => 'affiliate',
  704.                 'utm_medium' => $member->getId(),
  705.                 'utm_campaign' => 'event:' $event->getId(),
  706.                 'utm_term'     => '',
  707.                 'utm_content'  => '',
  708.             ];
  709.             $promotionUrl $em->getRepository(Batch::class)->generatePromotionUrl($baseURL$promotionUtmParameters);
  710.         }
  711.         // Überprüfen Sie den Wert des Teaserfeldes, um showTeaser zu setzen
  712.         $showTeaser = !empty($event->getTeaser());
  713.         $paymentLink false;
  714.         $view '@StartPlatzEventBundle/Default/event-single.html.twig';
  715.         if (($event->isSinglePage() && !$event->isMultiBatchEvent()) or $embed){
  716.             $view '@StartPlatzEventBundle/Default/event-single.lp.html.twig';
  717.         }
  718.         if ($event->getTwigFile() == 'winter-2025' ){
  719.             $view '@StartPlatzEventBundle/Default/event-single.winter-2025.html.twig';
  720.         }
  721.         if ($event->getTwigFile() == 'style-ecodynamics' ){
  722.             $view '@StartPlatzEventBundle/Default/event-single.style-ecodynamics.html.twig';
  723.         }
  724.         if ($event->getTwigFile() == 'style-ai-hub' ){
  725.             $view '@StartPlatzEventBundle/Default/event-single.style-ai-hub.html.twig';
  726.         }
  727.         if ($event->getTwigFile() == 'style-startplatz' ){
  728.             $view '@StartPlatzEventBundle/Default/event-single.style-startplatz.html.twig';
  729.         }
  730.         if ($event->getTwigFile() == 'tailwind' ){
  731.             $view '@StartPlatzEventBundle/Default/event-single.tailwind.html.twig';
  732.         }
  733.         $resolved = new EventContentResolver($event$batch$lang === 'EN');
  734.         return $this->render($view, [
  735.             'event'         => $event,
  736.             'resolved'      => $resolved,
  737.             'seriesEvents'  => $seriesEvents,
  738.             'showTeaser'    => $showTeaser,
  739.             'utmParameters'  => $utmParameters,
  740.             'promotionUrl'   => $promotionUrl,
  741.             'eventbriteId'   => $eventbriteId,
  742.             'isEventbriteOnly' => $isEventbriteOnly,
  743.             'applicationUrl' => $applicationUrl,
  744.             'batch'          => $batch,
  745.             'settings'       => $settings,
  746.             'form'           => $form $form->createView() : $form,
  747.             'application'    => $application,
  748.             'action'         => $action,
  749.             'batchIsOpen'    => $batchIsOpen,
  750.             'customersArr'   => $customersArr,
  751.             'member'         => $member,
  752.             'paymentLink'    => $paymentLink,
  753.             // Multi-batch event support
  754.             'futureBatches'  => $futureBatches,
  755.             'pastBatches'    => $pastBatches ?? [],
  756.             'allBatches'     => $allBatches,
  757.             'selectedDate'   => $date,
  758.             'isMultiBatchEvent' => $event->isMultiBatchEvent(),
  759.             'speakers'       => $this->eventViewHelper->getSpeakers($event),
  760.             'phrases'        => $em->getRepository(Option::class)->getApplicationPhrases($program$batchfalse$lang),
  761.             'editFeedback'   => $editFeedback,
  762.             'templateVars'   => [],
  763.             'preview'             => $request->get('preview'),
  764.             'lang'           => $lang,
  765.             'isEnglish'      => $lang === 'EN',
  766.             'embed'          => $embed,
  767.             'targetRoute'     => "event_show_single",
  768.             'targetRouteSlug' => $event->getSlug(),
  769.         ]);
  770.     }
  771.     // ── Private Helpers ──────────────────────────────────────────────
  772.     private function findEventBySlug($slug)
  773.     {
  774.         /** @var EventRepository $eventRepository */
  775.         $eventRepository $this->entityManager->getRepository(Event::class);
  776.         $event $eventRepository->findOneBy(['slug' => $slug]);
  777.         if (!$event) {
  778.             $querySlug '/' $slug;
  779.             $event $eventRepository->findOneBy(['slug' => $querySlug]);
  780.             if (!$event) {
  781.                 return false;
  782.             } else {
  783.                 $em $this->entityManager;
  784.                 $event->setSlug($slug);
  785.                 $em->persist($event);
  786.                 $em->flush();
  787.             }
  788.         }
  789.         return $event;
  790.     }
  791.     private function handleEventStatus(Event $eventRequest $request)
  792.     {
  793.         // SEO-optimized handling: Archive events are displayed normally (no redirect)
  794.         // Template will show archive banner and hide registration forms
  795.         // This preserves 100% SEO juice and backlinks
  796.         if ($event->getStatus() != 'publish' and $event->getStatus() != 'archive' and !$request->get('preview')) {
  797.             // Draft and trash events require authentication
  798.             if (!$this->getUser()) {
  799.                 $this->addFlash('notice''ERROR Veranstaltung ist nicht verfügbar');
  800.                 return $this->redirectToRoute('events_list');
  801.             }
  802.         }
  803.         return null;
  804.     }
  805.     /**
  806.      * handleAction - Handles various actions for the application
  807.      *
  808.      * This function is called in the following contexts:
  809.      * 1. During Signup (signupSingleAction)
  810.      *    - With route "signup_show_single"
  811.      *    - Parameters include batch slug, language, etc.
  812.      *
  813.      * 2. During Event Handling (eventSingleAction / eventConfirmationAction)
  814.      *    - With route "event_show_single" or "event_confirmation"
  815.      *    - Parameters include event slug, language, etc.
  816.      */
  817.     private function handleAction(Request $request$memberApplication $applicationBatch $batch$lang$route$routeParameters$settings)
  818.     {
  819.         $action $request->get("action");
  820.         $em $this->entityManager;
  821.         switch ($action) {
  822.             case "checkSuccess":
  823.                 $provider $request->get('provider');
  824.                 $isVerifiedStripePayment false;
  825.                 if ($provider === 'stripe') {
  826.                     $payment $em->getRepository(EventStripePayment::class)
  827.                         ->findLatestSuccessfulByApplicationIds([$application->getId()])[$application->getId()] ?? null;
  828.                     if ($payment && in_array($payment->getPaymentStatus(), ['paid''refunded''partially_refunded'], true)) {
  829.                         $isVerifiedStripePayment true;
  830.                     }
  831.                     // Polling fallback: if webhook hasn't arrived yet, ask Stripe directly
  832.                     if (!$isVerifiedStripePayment) {
  833.                         $isVerifiedStripePayment $this->eventPaymentService->pollStripePaymentStatus($application->getId());
  834.                     }
  835.                 }
  836.                 // Guard: only process once — skip if already applied (prevents duplicate mails on reload)
  837.                 $alreadyProcessed $application->getApplicationStatus() === 'applied' && $application->getHasPaid();
  838.                 if (!$alreadyProcessed && ($provider !== 'stripe' || $isVerifiedStripePayment)) {
  839.                     if ($provider === 'stripe') {
  840.                         $application->setEditStatus("success:stripePaid");
  841.                     }
  842.                     $application->setApplicationStatus('applied');
  843.                     $application->setHasPaid(true);
  844.                     $application $em->getRepository(Application::class)->setApplication($application);
  845.                 }
  846.                 switch ($lang) {
  847.                     case "DE":
  848.                         $message $provider === 'stripe' && !$isVerifiedStripePayment
  849.                             "Deine Zahlung wird gerade geprüft.<br>Bitte aktualisiere die Seite in ein paar Sekunden erneut."
  850.                             "Danke für Deine Anmeldung.<br>Wir freuen uns auf Dich!";
  851.                         break;
  852.                     case "EN":
  853.                         $message $provider === 'stripe' && !$isVerifiedStripePayment
  854.                             "Your payment is being verified.<br>Please refresh this page again in a few seconds."
  855.                             "Thanks, Your application is now approved.<br>We are looking forward to having you!";
  856.                         break;
  857.                 }
  858.                 if ($productNumber $request->get('productnumber') or $provider == 'stripe'){
  859.                     ## productNumber is only given in case of sign up
  860.                     if (!($provider === 'stripe' && !$isVerifiedStripePayment)) {
  861.                         switch ($lang) {
  862.                             case "DE":
  863.                                 $message "Danke für Deine Buchung.<br>Wir freuen uns auf Dich!";
  864.                                 break;
  865.                             case "EN":
  866.                                 $message "Thanks, Your booking was successful.<br>We are looking forward to having you!";
  867.                                 break;
  868.                         }
  869.                     }
  870.                     $account      $request->get('account');
  871.                     $customerHash $request->get('customerId');
  872.                     $subscriptionHash $request->get('subscriptionId');
  873.                     if (!$member) {
  874.                         $member $em->getRepository(Member::class)->find($application->getMemberId());
  875.                     }
  876.                     if (array_key_exists("setAiHubMembership"$settings)) {
  877.                         // Hole den Status aus den Einstellungen
  878.                         $aiMembershipStatus $settings["setAiHubMembership"];
  879.                         // Setze das Start- und Enddatum basierend auf dem aktuellen Datum und dem Status
  880.                         $aiMembershipStartDate = new DateTime();  // Setze auf aktuelles Datum und Uhrzeit
  881.                         $aiMembershipEndDate = clone $aiMembershipStartDate;
  882.                         if ($aiMembershipStatus === 'trial') {
  883.                             $aiMembershipEndDate->modify('+1 month');
  884.                         } elseif ($aiMembershipStatus === 'active') {
  885.                             $aiMembershipEndDate->modify('+3 months');
  886.                         }
  887.                         // Setze den Grund für die Mitgliedschaft
  888.                         $reason "Buy of {$productNumber}";
  889.                         // Erstelle oder aktualisiere das Service-Objekt mit den neuen Daten
  890.                         // (Du müsstest diese Logik entsprechend deiner Anwendung implementieren)
  891.                         $service = new Service();  // oder hole ein existierendes Service-Objekt
  892.                         $service->setStatus($aiMembershipStatus);
  893.                         $service->setStartDate($aiMembershipStartDate);
  894.                         $service->setEndDate($aiMembershipEndDate);
  895.                         // Rufe die setAiHubMembership Funktion auf
  896.                         $successContent[] = $em->getRepository(Member::class)->setAiHubMembership($service$member$reason);
  897.                     }
  898.                     $loginLink null;
  899.                     $targetPath $this->generateUrl('x_membership_first-steps', ['productNumber' => $productNumber'account' => $account]);
  900.                     $this->addFlash('notice'$message);
  901.                     if ($provider === 'stripe' && !$isVerifiedStripePayment) {
  902.                         return $application;
  903.                     }
  904.                     // Send confirmation mail + monitoring only on first successful verification
  905.                     if (!$alreadyProcessed) {
  906.                         if (!$user $this->getUser()) {
  907.                             $loginLink $this->loginService->getLoginLinkByTargetPath($member->getEmail(), $targetPath);
  908.                             $user $em->getRepository(User::class)->findOneBy(['memberId'=>$member->getId()]);
  909.                         }
  910.                         $feedback $this->eventNotificationService->sendConfirmationMail($usernull$settings$application$batch);
  911.                         if ($provider == 'stripe'){
  912.                             $mailContent = [
  913.                                 'applicationId' => $application->getId(),
  914.                                 'memberId' => $application->getMemberId(),
  915.                                 'editStatus' => $application->getEditStatus(),
  916.                                 'applicationStatus' => $application->getApplicationStatus(),
  917.                                 'person' => $application->getPerson(),
  918.                                 'email' => $application->getEmail(),
  919.                                 'utmSource' => $application->getUtmSource(),
  920.                                 'batchSlug' => $application->getBatchSlug(),
  921.                             ];
  922.                             $response $this->mailService->send("stripe step two {$application->getBatchId()} {$application->getEmail()}"'support@startplatz.de''Monitoring Stripe'$this->alertRecipientService->get('alert.stripe_monitoring'), 'Lorenz'print_r($mailContent,true), false);
  923.                         }
  924.                     }
  925.                     if ($provider == 'stripe'){
  926.                         return $application;
  927.                     } else {
  928.                         return isset($loginLink) ? $loginLink $targetPath;
  929.                     }
  930.                 } else { // if productNumber is not defined
  931.                     if ($provider === 'stripe' && !$isVerifiedStripePayment) {
  932.                         $this->addFlash('notice'$message);
  933.                         return $application;
  934.                     }
  935.                     if (!$user $this->getUser()) {
  936.                         $user $em->getRepository(User::class)->findOneBy(['memberId'=>$member->getId()]);
  937.                     }
  938.                     $feedback $this->eventNotificationService->sendConfirmationMail($usernull$settings$application$batch);
  939.                 }
  940.                 break;
  941.             case "sendMagicLinkForPayment":
  942.                 // create LoginLink and send email
  943.                 $customerId  $request->get('customerId');
  944.                 $feedbackUrl $this->eventPaymentService->sendMagicLinkForPayment($application$batch$customerId$route$routeParameters);
  945.                 return $feedbackUrl;
  946.             case "createConsumerMonsumAccount":
  947.             case "useExistingCustomerAccount":
  948.                 $customerId  $request->get('customerId');
  949.                 $checkoutUrl $this->eventPaymentService->prepareMonsumCheckout($application$batch$action$route$routeParameters$customerId);
  950.                 return $checkoutUrl;
  951.         }
  952.         // Return the modified $application object to the main controller
  953.         return $application;
  954.     }
  955.     private function validateEventApplication(Application $applicationMember $member$settings$batchstring $lang): array
  956.     {
  957.         $em $this->entityManager;
  958.         $message "";
  959.         $status "";
  960.         // Check if a confirmation email needs to be sent
  961.         $shouldSendConfirmationMail false;
  962.         $feedback null;
  963.         switch ($application->getEditStatus()) {
  964.             case "error:validateLogin":
  965.                 $application->setEditStatus('success:validatedLogin');
  966.                 $application->setEditMessage("Application has been validated by {$member->getEmail()}");
  967.                 $application $em->getRepository(Application::class)->setHistory($application$application->getEditMessage());
  968.                 $application $em->getRepository(Application::class)->setApplication($application$member);
  969.                 $status "success";
  970.                 $shouldSendConfirmationMail true;
  971.                 break;
  972.             case "error:validateEmail":
  973.                 $application->setEditStatus('success:validatedEmail');
  974.                 $application->setEditMessage("Email of this Application has been validated by {$member->getEmail()}");
  975.                 $application $em->getRepository(Application::class)->setHistory($application$application->getEditMessage());
  976.                 if ($application->getApplicationStatus() == 'started') {
  977.                     $application->setApplicationStatus('applied');
  978.                 }
  979.                 $application $em->getRepository(Application::class)->setApplication($application$member);
  980.                 $status "success";
  981.                 $shouldSendConfirmationMail true;
  982.                 break;
  983.         }
  984.         if ($shouldSendConfirmationMail) {
  985.             // Logic to send confirmation mail
  986.             $feedback $this->eventNotificationService->sendConfirmationMail(null$member$settings$application$batch);
  987.         }
  988.         if ($status == "success") {
  989.             $application $em->getRepository(Application::class)->setApplicationApplied($application$member);
  990.             switch ($lang) {
  991.                 case "DE":
  992.                     $message "SUCCESS Danke, Deine Anmeldung ist jetzt bestätigt. Wir freuen uns auf Dich!";
  993.                     if ($feedback){
  994.                         $message .= "<br>Wir haben Dir eine Bestätigungsmail geschickt. Bitte prüfe Deinen Posteingang.";
  995.                     }
  996.                     break;
  997.                 case "EN":
  998.                     $message "SUCCESS Thanks, Your application is now approved. We are looking forward to having you!";
  999.                     if ($feedback){
  1000.                         $message .= "<br>We have sent you a confirmation mail. Please check your inbox!";
  1001.                     }
  1002.                     break;
  1003.             }
  1004.             $this->addFlash('notice'$message);
  1005.         }
  1006.         return [
  1007.             'data' => [
  1008.                 'application' => $application,
  1009.             ],
  1010.             'message' => $message,
  1011.             'status' => $status,
  1012.         ];
  1013.     }
  1014.     private function shouldSetAiHubMembership($settings$applicationStatus)
  1015.     {
  1016.         return array_key_exists("setAiHubMembership"$settings) && $applicationStatus === 'applied';
  1017.     }
  1018.     private function configureServiceForAiHub($statusDateTime $startDate)
  1019.     {
  1020.         $service = new Service();  // oder hole ein existierendes Service-Objekt
  1021.         $endDate = clone $startDate;
  1022.         if ($status === 'trial') {
  1023.             $endDate->modify('+1 month');
  1024.         } elseif ($status === 'active') {
  1025.             $endDate->modify('+3 months');
  1026.         }
  1027.         $service->setStatus($status);
  1028.         $service->setStartDate($startDate);
  1029.         $service->setEndDate($endDate);
  1030.         return $service;
  1031.     }
  1032.     private function updateApplication(Application $application$differences)
  1033.     {
  1034.         foreach ($differences as $diff => $value) {
  1035.             $method 'set' ucfirst((string) $diff);
  1036.             if (method_exists($application$method)) {
  1037.                 $application->$method($value);
  1038.             }
  1039.         }
  1040.         return $application;
  1041.     }
  1042.     #[Route('/events/{slug}/self-checkin'name'event_self_checkin'methods: ['GET''POST'])]
  1043.     public function selfCheckin(string $slugRequest $request): Response
  1044.     {
  1045.         $token $request->query->get('token''');
  1046.         if ($request->isMethod('GET')) {
  1047.             // Validate token for GET request
  1048.             if (!$token) {
  1049.                 return $this->render('@StartPlatzEventBundle/Event/selfCheckin.html.twig', [
  1050.                     'slug' => $slug,
  1051.                     'error' => 'Ungültige Check-in Session. QR-Code scannen.',
  1052.                 ]);
  1053.             }
  1054.             return $this->render('@StartPlatzEventBundle/Event/selfCheckin.html.twig', [
  1055.                 'slug' => $slug,
  1056.                 'token' => $token,
  1057.             ]);
  1058.         }
  1059.         // POST
  1060.         if (!$token) {
  1061.             return $this->render('@StartPlatzEventBundle/Event/selfCheckin.html.twig', [
  1062.                 'slug' => $slug,
  1063.                 'error' => 'Check-in Session abgelaufen. QR-Code erneut scannen.',
  1064.             ]);
  1065.         }
  1066.         $code $request->request->get('code''');
  1067.         $email $request->request->get('email''');
  1068.         try {
  1069.             $checkinData $this->selfCheckinService->validateAndCheckin($slug$email$code$token);
  1070.             return $this->render('@StartPlatzEventBundle/Checkin/success.html.twig', [
  1071.                 'event' => $checkinData['event'],
  1072.                 'message' => 'Erfolgreich eingecheckt!',
  1073.             ]);
  1074.         } catch (InvalidCheckinException $e) {
  1075.             return $this->render('@StartPlatzEventBundle/Event/selfCheckin.html.twig', [
  1076.                 'slug' => $slug,
  1077.                 'token' => $token,
  1078.                 'error' => $e->getMessage(),
  1079.             ]);
  1080.         }
  1081.     }
  1082. }