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

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