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

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