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

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