src/Controller/DefaultController.php line 25

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\Booking;
  4. use App\Entity\Participant;
  5. use App\Entity\Session;
  6. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  7. use Symfony\Component\HttpFoundation\Request;
  8. use Symfony\Component\HttpFoundation\Response;
  9. use Symfony\Component\Routing\Annotation\Route;
  10. use Symfony\Component\Mailer\MailerInterface;
  11. use Symfony\Bridge\Twig\Mime\TemplatedEmail;
  12. use Symfony\Component\Mime\Address;
  13. use Symfony\Component\Mime\Email;
  14. use Symfony\Component\Mailer\Exception\HttpTransportException;
  15. class DefaultController extends AbstractController
  16. {
  17.     /**
  18.      * @Route("/", name="app_default")
  19.      */
  20.     public function index(Request $request)
  21.     {   
  22.         $em $this->getDoctrine()->getManager();
  23.        
  24.        if($request->isMethod('POST'))
  25.        {
  26.        
  27.                 $booking = new Booking();
  28.                 $booking->setStatus('Brouillon');
  29.                 $em->persist($booking);
  30.                 $em->flush();
  31.                 $p = new Participant();
  32.                 $p->setBooking($booking)
  33.                  ->setGardianName($request->get('gardianName'))
  34.                  ->setGardianNickname($request->get('gardianNickname'))
  35.                  ->setGardianEmail($request->get('gardianEmail'))
  36.                  ->setGardianPhone($request->get('gardianPhone'))
  37.                  ->setName($request->get('participantName'))
  38.                  ->setNickName($request->get('participantNickname'))
  39.                  ->setPhone($request->get('participantPhone'))
  40.                  ->setEmail($request->get('participantEmail'))
  41.                  ->setDob(new \DateTimeImmutable($request->get('participantDob')));
  42.                 $em->persist($p);
  43.                 $em->flush();
  44.                 return $this->redirectToRoute('step',['id' => $p->getId()]); 
  45.             
  46.         }
  47.         return $this->render('default/session-step2.html.twig');
  48.     }
  49.     /**
  50.      * @Route("/participants/{id}", name="step.2")
  51.      */
  52.     public function stepTwo(Request $request$id)
  53.   {
  54.     $em $this->getDoctrine()->getManager();
  55.     $booking $em->getRepository(Booking::class)->find($id);
  56.     if (!$booking) {
  57.         throw $this->createNotFoundException('Réservation introuvable.');
  58.     }
  59.     // Pour réafficher en cas de GET initial (ou si tu veux voir ce qui a été saisi)
  60.     $prefill = [];
  61.     if ($request->isMethod('POST')) {
  62.         // Récupération brute des participants (toujours un tableau)
  63.         $params $request->request->all();
  64.         $participantsData $params['participants'] ?? [];
  65.         if (!is_array($participantsData)) { $participantsData = []; }
  66.         $prefill $participantsData;
  67.         // 1) On supprime les anciens participants liés au booking (si retour arrière)
  68.         foreach ($booking->getParticipants() as $old) { $em->remove($old); }
  69.         $booking->getParticipants()->clear();
  70.         // 2) On enregistre ce qu'on reçoit, sans se prendre la tête
  71.         foreach ($participantsData as $row) {
  72.             // On tolère plusieurs conventions de noms pour éviter les 500 :
  73.             $name     trim((string)($row['name'] ?? $row['first_name'] ?? ''));
  74.             $nickName trim((string)($row['nickName'] ?? $row['last_name'] ?? ''));
  75.             $email    trim((string)($row['email'] ?? ''));
  76.             $phone    trim((string)($row['phone'] ?? $row['mobile'] ?? ''));
  77.             $dobStr   trim((string)($row['dob'] ?? ''));
  78.             $gName    trim((string)($row['gardianName'] ?? $row['gardian_name'] ?? $row['guardian_first_name'] ?? ''));
  79.             $gNick    trim((string)($row['gardianNickname'] ?? $row['gardian_nickname'] ?? $row['guardian_last_name'] ?? ''));
  80.             $gEmail   trim((string)($row['gardianEmail'] ?? $row['gardian_email'] ?? $row['guardian_email'] ?? ''));
  81.             $gPhone   trim((string)($row['gardianPhone'] ?? $row['gardian_phone'] ?? $row['guardian_mobile'] ?? ''));
  82.             // case à cocher : on sauvegarde "1" si coché, NULL sinon
  83.             $gConsent = !empty($row['gardian_participant_consent'] ?? $row['guardian_participant_consent'] ?? $row['guardian_authorizes_participation'] ?? null) ? '1' null;
  84.             // Si la ligne est complètement vide, on skip
  85.             if ($name === '' && $nickName === '' && $email === '' && $phone === '' && $dobStr === '') {
  86.                 continue;
  87.             }
  88.             $p = new Participant();
  89.             $p->setBooking($booking);
  90.             // Setters selon TON entité
  91.             $p->setName($name !== '' $name null);
  92.             if (method_exists($p'setNickName')) {
  93.                 $p->setNickName($nickName !== '' $nickName null);
  94.             } elseif (method_exists($p'setNickname')) {
  95.                 $p->setNickname($nickName !== '' $nickName null);
  96.             }
  97.             $p->setEmail($email !== '' $email null);
  98.             if (method_exists($p'setPhone')) {
  99.                 $p->setPhone($phone !== '' $phone null);
  100.             }
  101.             if ($dobStr !== '') {
  102.                 try { $p->setDob(new \DateTimeImmutable($dobStr)); } catch (\Throwable $e) { /* on ignore */ }
  103.             }
  104.             if (method_exists($p'setGardianName'))      { $p->setGardianName($gName !== '' $gName null); }
  105.             if (method_exists($p'setGardianNickname'))  { $p->setGardianNickname($gNick !== '' $gNick null); }
  106.             elseif (method_exists($p'setGardianNickName')) { $p->setGardianNickName($gNick !== '' $gNick null); }
  107.             if (method_exists($p'setGardianEmail'))     { $p->setGardianEmail($gEmail !== '' $gEmail null); }
  108.             if (method_exists($p'setGardianPhone'))     { $p->setGardianPhone($gPhone !== '' $gPhone null); }
  109.             if (method_exists($p'setGardianParticipantConsent')) {
  110.                 $p->setGardianParticipantConsent($gConsent); // string nullable
  111.             }
  112.             $em->persist($p);
  113.             if (method_exists($booking'addParticipant')) {
  114.                 $booking->addParticipant($p);
  115.             }
  116.         }
  117.         // 3) On écrit et on file en étape 3
  118.         $em->flush();
  119.         return $this->redirectToRoute('step.dis', ['id' => $booking->getId()]);
  120.     }
  121.     // GET initial (ou si tu veux pré-remplir)
  122.     return $this->render('default/session-step2.html.twig', [
  123.         'booking' => $booking,
  124.         'prefill' => $prefill,
  125.     ]);
  126. }
  127.     /**
  128.      * @Route("/disclamer/{id}", name="step")
  129.      */
  130.     public function stepDix(Request $request$id)
  131.  {
  132.     $em $this->getDoctrine()->getManager();
  133.     $booking $em->getRepository(Booking::class)->find($id);
  134.     if (!$booking) {
  135.         throw $this->createNotFoundException('Réservation introuvable.');
  136.     }
  137.     if ($request->isMethod('POST')) {
  138.         $consents $request->get('disclamer');
  139.     /// dd('kkikoo');
  140.         foreach ($booking->getParticipants() as $p) {
  141.             $checked = !empty($consents[$p->getId()]['disclamer'] ?? null);
  142.                 $p->setDisclamer('1'); // on stocke "1" si coché
  143.                 $em->persist($p);
  144.             }
  145.                       $em->flush();
  146.  
  147.      
  148.             return $this->redirectToRoute('step.3', ['id' => $booking->getId()]);
  149.         }
  150.     return $this->render('default/session-step3-1.html.twig', [
  151.         'booking'=> $booking
  152.     ]);
  153. }
  154.     /**
  155.      * @Route("/consentement/{id}", name="step.3")
  156.      */
  157.     public function stepThree(Request $request$idMailerInterface $mailer)
  158.  {
  159.     $em $this->getDoctrine()->getManager();
  160.     $booking $em->getRepository(Booking::class)->find($id);
  161.     if (!$booking) {
  162.         throw $this->createNotFoundException('Réservation introuvable.');
  163.     }
  164.     // Date d’événement depuis la session si dispo, sinon aujourd’hui
  165.     $eventDate null;
  166.     if (method_exists($booking'getSession') && $booking->getSession() && method_exists($booking->getSession(), 'getStartsAt')) {
  167.         $eventDate $booking->getSession()->getStartsAt();
  168.     }
  169.     if (!$eventDate) { $eventDate = new \DateTimeImmutable('today'); }
  170.     $eventDatePlus10 $eventDate->modify('+10 years');
  171.     // Qui est mineur ? (pour afficher la bonne phrase côté Twig)
  172.     $minors = [];
  173.     foreach ($booking->getParticipants() as $p) {
  174.         $isMinor false;
  175.         if (method_exists($p'getDob') && $p->getDob() instanceof \DateTimeInterface) {
  176.             $age $p->getDob()->diff(new \DateTimeImmutable('today'))->y;
  177.             $isMinor = ($age 18);
  178.         }
  179.         $minors[$p->getId()] = $isMinor;
  180.     }
  181.     $errors = [];
  182.     if ($request->isMethod('POST')) {
  183.         $consents $request->request->get('consents', []);
  184.         foreach ($booking->getParticipants() as $p) {
  185.             $checked = !empty($consents[$p->getId()]['imgConsent'] ?? null);
  186.             if (!$checked) {
  187.                 $displayName trim(($p->getName() ?? '').' '.($p->getNickName() ?? ''));
  188.                 $errors[] = "Merci d’accepter les droits à l’image pour « {$displayName} ».";
  189.             } else {
  190.                 $p->setImgConsent('1'); // on stocke "1" si coché
  191.                 $em->persist($p);
  192.             }
  193.         }
  194.         if (empty($errors)) {
  195.             if (method_exists($booking'setStatus')) {
  196.                 $booking->setStatus('Confirmé');
  197.                 $em->persist($booking);
  198.             }
  199.             $em->flush();
  200.         // Construit quelques infos utiles pour l’email
  201.         $session   method_exists($booking'getSession') ? $booking->getSession() : null;
  202.         $startsAt  = ($session && method_exists($session,'getStartsAt')) ? $session->getStartsAt() : null;
  203.         $endsAt    = ($session && method_exists($session,'getEndsAt'))   ? $session->getEndsAt()   : null;
  204.         // Envoi email (on encapsule dans try/catch pour ne pas bloquer l’utilisateur en cas d’échec SMTP)
  205.   
  206.             $email = (new TemplatedEmail())
  207.                 ->from(new Address('noreply@agence58.com''JPO EDF'))
  208.                 ->to('sei-guadeloupe-communication@edf.fr')
  209.                 ->subject(sprintf('Nouvelle réservation — JPO EDF — #%d'$booking->getId()))
  210.                 ->htmlTemplate('default/email-booking.html.twig')
  211.                 ->context([
  212.                     'booking'  => $booking,
  213.                     'startsAt' => $startsAt,
  214.                     'endsAt'   => $endsAt,
  215.                 ]);
  216.             $mailer->send($email);
  217.       
  218.             $this->addFlash('success''Merci ! Les inscriptions ont bien été prises en compte.');
  219.             return $this->redirectToRoute('step.4', ['id' => $booking->getId()]);
  220.         }
  221.     }
  222.    // dd($booking);
  223.     return $this->render('default/session-step3.html.twig', [
  224.         'booking'         => $booking,
  225.         'errors'          => $errors,
  226.         'eventDate'       => $eventDate,
  227.         'eventDatePlus10' => $eventDatePlus10,
  228.         'minors'          => $minors,
  229.     ]);
  230. }
  231.    /**
  232.      * @Route("/confirmation/{id}", name="step.4")
  233.      */
  234.     public function stepFour($id)
  235.      {
  236.         $em $this->getDoctrine()->getManager();
  237.         $booking $em->getRepository(Booking::class)->find($id);
  238.     return $this->render('default/session-step4.html.twig', [
  239.         'booking'         => $booking]);
  240.     }
  241.     /**
  242.      * @Route("/mail-test", name="mail.test")
  243.      */
  244.     public function mailTest(MailerInterface $mailer): Response {
  245.     {
  246.         try {
  247.             $email = (new Email())
  248.                 ->from('no-reply@agence58.com')
  249.                 ->to('agence.deejayevents@gmail.com')
  250.                 ->subject('Test Brevo API')
  251.                 ->text('Ceci est un test d’envoi via Brevo (API).');
  252.             $mailer->send($email);
  253.             return new Response('✅ Mail envoyé (vérifie ta boîte ou ton dossier spam)');
  254.        }
  255.         catch (HttpTransportException $e) {
  256.             // Erreurs API Brevo : on récupère le détail JSON
  257.             $details $e->getResponse() ? $e->getResponse()->getContent(false) : '';
  258.             return new Response("❌ HttpTransportException: {$e->getMessage()}\n\n{$details}"500);
  259.         }
  260.         catch (\Throwable $e) {
  261.             return new Response("❌ Exception: {$e->getMessage()}"500);
  262.         }
  263.     }
  264. }
  265. }