src/Controller/HomeController.php line 382

  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\LikedBuilding;
  4. use App\Entity\UserForm;
  5. use App\Services\Mails\Mails;
  6. use App\Form\ContactForm;
  7. use App\Form\UserForm\AttestationUserFormType;
  8. use App\Form\UserForm\OwnerUserFormType;
  9. use App\Form\UserForm\TenantUserFormType;
  10. use App\Form\UserForm\NewsletterUserFormType;
  11. use App\Entity\User;
  12. use App\Entity\Building;
  13. use App\Repository\UserFormRepository;
  14. use App\Repository\LikedBuildingRepository;
  15. use App\Repository\BuildingRepository;
  16. use App\Repository\CityRepository;
  17. use Symfony\Contracts\Translation\TranslatorInterface;
  18. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  19. use Symfony\Component\HttpFoundation\Request;
  20. use Symfony\Component\Routing\Annotation\Route;
  21. use Doctrine\ORM\EntityManagerInterface;
  22. use Symfony\Component\Mailer\MailerInterface;
  23. use Symfony\Component\Mime\Email;
  24. use Symfony\Component\HttpFoundation\JsonResponse;
  25. use Symfony\Component\HttpFoundation\Response;
  26. use Symfony\Component\DependencyInjection\ParameterBag\ParameterBagInterface;
  27. class HomeController extends AbstractController
  28. {
  29.     private $cityRepository;
  30.     private $likedBuildingRepository;
  31.     private $translator;
  32.     private $userFormRepository;
  33.     private $entityManager;
  34.     private string $googleMapKey;
  35.     public function __construct(
  36.         CityRepository $cityRepository,
  37.         LikedBuildingRepository $likedBuildingRepository,
  38.         TranslatorInterface $translator,
  39.         UserFormRepository $userFormRepository,
  40.         EntityManagerInterface $entityManager,
  41.         ParameterBagInterface $params
  42.     ) {
  43.         $this->cityRepository $cityRepository;
  44.         $this->likedBuildingRepository $likedBuildingRepository;
  45.         $this->translator $translator;
  46.         $this->userFormRepository $userFormRepository;
  47.         $this->entityManager $entityManager;
  48.         $this->googleMapKey $params->get('app.googlemapkey');
  49.     }
  50.     #[Route(path: ["fr" => "/""en" => "/en/",], name'home')]
  51.     public function index(BuildingRepository $buildingRepositoryLikedBuildingRepository $likedBuildingRepositoryRequest $request)
  52.     {
  53.         $userForm false//fiche d'attente formulaire utilisateur
  54.         $landing true;
  55.         if($landing == true) return $this->redirectToRoute('landing');
  56.         if($userForm == true) return $this->redirectToRoute('userForm');
  57.     
  58.         $lng $request->query->get('lng');
  59.         $lat $request->query->get('lat');
  60.         $city $request->query->get('city');
  61.         $selectedCity null;
  62.         $selectedBuildings = [];
  63.     if ($userForm == true) {
  64.         return $this->redirectToRoute('userForm'); 
  65.     }
  66.     if ($landing == true) {
  67.         return $this->redirectToRoute('landing'); 
  68.     }
  69.     
  70.     $lng $request->query->get('lng');
  71.     $lat $request->query->get('lat');
  72.     $city $request->query->get('city');
  73.     $selectedCity null;
  74.     $selectedBuildings = [];
  75.     if ($city != "null") {
  76.         $selectedCity $this->cityRepository->findOneBy(['city' => $city]);
  77.         if ($selectedCity != null) {
  78.             $selectedBuildings $buildingRepository->findBy(
  79.                 ['cityEntity' => $selectedCity->getId(), 'isEnd' => true'isActive' => true],
  80.                 ['id' => 'DESC']
  81.             );
  82.         }
  83.     }
  84.     $cities $this->cityRepository->findBy(['isInsideHomepage' => true]);
  85.     $filter $request->query->get('filter');
  86.     $filterChoice = match ($filter) {
  87.         'appartement' => "typeBien.appartement",
  88.         'chambre_privee' => "typeBien.chambrePrivee",
  89.         'chambre_partagee' => "typeBien.chambrePartagee",
  90.         'bons_plans' => "Bon plan",
  91.         default => null,
  92.     };
  93.     $buildingss = [];
  94.     foreach ($cities as $city) {
  95.         $buildingss[$city->getCity()] = $buildingRepository->findByIsInHomepage($city->getId(), $filterChoice);
  96.     }
  97.     // Récupérer l'utilisateur actuel
  98.     $user $this->getUser();
  99.     $buildings $buildingRepository->findBy(['isEnd' => true'isActive' => true], ['id' => 'DESC']);
  100.     $likedBuildings = [];
  101.     foreach ($buildings as $building) {
  102.         $isLiked $this->likedBuildingRepository->findOneBy(['user' => $user'building' => $building]) !== null;
  103.         $likedBuildings[$building->getId()] = $isLiked;
  104.     }
  105.     $buildingsLast = ($filterChoice != null)
  106.         ? $buildingRepository->findBy(['format' => $filterChoice'isEnd' => true'isActive' => true], ['id' => 'DESC'])
  107.         : $buildingRepository->findBy(['isEnd' => true'isActive' => true], ['id' => 'DESC'], 8);
  108.     $buildingsMap = [];
  109.     $buildingsMapData $buildingRepository->findByLatAndLngNotNull();
  110.     foreach ($buildingsMapData as $building) {
  111.         $buildingsMap[] = [
  112.             'lat' => $building->getLat(),
  113.             'lng' => $building->getLng(),
  114.             'id' => $building->getId(),
  115.         ];
  116.     }
  117.     $liked $likedBuildingRepository->findOneBy(['user' => $this->getUser(), 'building' => $building]);
  118.     return $this->render('home/index.html.twig', [
  119.         'building' => $building,
  120.         'likedBuildings' => $likedBuildings,
  121.         'liked' => $liked,
  122.         'cities' => $cities,
  123.         'lastBuildings' => $buildingsLast,
  124.         'arrayBuildings' => $buildingss,
  125.         'selectedCity' => $selectedCity,
  126.         'selectedBuildings' => $selectedBuildings,
  127.         'buildingsMap' => $buildingsMap,
  128.         'filter' => $filter,
  129.     ]);
  130. }
  131.     #[Route(path: ["fr" => "/mentions-legales""en" => "/en/mentions-legales",], name'mentions_legales')]
  132.     public function mentionsLegales()
  133.     {
  134.         return $this->render('mentionslegales/mentions_legales.html.twig', []);
  135.     }
  136.     public function enleveaccents($param)
  137.     {
  138.         $param strtr(
  139.             $param,
  140.             [
  141.                 "À" => 'A',
  142.                 "Á" => 'A',
  143.                 "Â" => 'A',
  144.                 "Ã" => 'A',
  145.                 "Ä" => 'A',
  146.                 "Å" => 'A',
  147.                 "à" => 'a',
  148.                 "á" => 'a',
  149.                 "â" => 'a',
  150.                 "ã" => 'a',
  151.                 "ä" => 'a',
  152.                 "å" => 'a',
  153.                 "Ò" => 'O',
  154.                 "Ó" => 'O',
  155.                 "Ô" => 'O',
  156.                 "Õ" => 'O',
  157.                 "Ö" => 'O',
  158.                 "Ø" => 'O',
  159.                 "ò" => 'o',
  160.                 "ó" => 'o',
  161.                 "ô" => 'o',
  162.                 "õ" => 'o',
  163.                 "ö" => 'o',
  164.                 "ø" => 'o',
  165.                 "È" => 'E',
  166.                 "É" => 'E',
  167.                 "Ê" => 'E',
  168.                 "Ë" => 'E',
  169.                 "è" => 'e',
  170.                 "é" => 'e',
  171.                 "ê" => 'e',
  172.                 "ë" => 'e',
  173.                 "Ç" => 'C',
  174.                 "ç" => 'c',
  175.                 "Ì" => 'I',
  176.                 "Í" => 'I',
  177.                 "Î" => 'I',
  178.                 "Ï" => 'I',
  179.                 "ì" => 'i',
  180.                 "í" => 'i',
  181.                 "î" => 'i',
  182.                 "ï" => 'i',
  183.                 "Ù" => 'U',
  184.                 "Ú" => 'U',
  185.                 "Û" => 'U',
  186.                 "Ü" => 'U',
  187.                 "ù" => 'u',
  188.                 "ú" => 'u',
  189.                 "û" => 'u',
  190.                 "ü" => 'u',
  191.                 "ÿ" => 'y',
  192.                 "Ñ" => 'N',
  193.                 "ñ" => 'n'
  194.             ]
  195.         );
  196.         return $param;
  197.     }
  198.     #[Route(path: [
  199.         "fr" => "/search/advanced",
  200.         "en" => "/en/search/advanced",
  201.     ], name'advanced_search')]
  202.     public function advancedSearch(BuildingRepository $buildingRepositoryRequest $requestLikedBuildingRepository $likedBuildingRepository): Response
  203.     {
  204.         $lng $request->query->get('lng');
  205.         $lat $request->query->get('lat');
  206.         $city $request->query->get('city');
  207.         $page $request->query->getInt('page'1);
  208.         $limit 16// Nombre de logements par page
  209.     
  210.         if (empty($city) || empty($lng) || empty($lat)) {
  211.             if(!empty($city)){
  212.                 $apiKey $this->googleMapKey;
  213.                 $url "https://maps.googleapis.com/maps/api/geocode/json?address={$city}&key={$apiKey}";
  214.                 $response file_get_contents($url);
  215.                 $data json_decode($responsetrue);
  216.                 if ($data['status'] === 'OK') {
  217.                     $lat $data['results'][0]['geometry']['location']['lat'];
  218.                     $lng $data['results'][0]['geometry']['location']['lng'];
  219.                 } else {
  220.                     $this->addFlash('error''Impossible de trouver les coordonnées de la ville');
  221.                     return $this->redirectToRoute('home');
  222.                 }
  223.             }
  224.             // $this->addFlash('error', $this->translator->trans('nav.notFoundSearch'));
  225.             // return $this->redirectToRoute('home');
  226.         }
  227.     
  228.         $selectedCity $this->cityRepository->findOneBy(['city' => $city]);
  229.     
  230.         if (!$selectedCity) {
  231.             $city str_replace("-"" "$city);
  232.             $city $this->enleveaccents($city);
  233.             $cityCaps mb_strtoupper($city);
  234.             $selectedCity $this->cityRepository->findOneBy(['city' => $cityCaps]);
  235.         }
  236.     
  237.         if (!$selectedCity) {
  238.             $city str_replace(["Saint "" Saint"" Saint "], ["ST "" ST "" ST "], $city);
  239.             $cityCaps mb_strtoupper($city);
  240.             $selectedCity $this->cityRepository->findOneBy(['city' => $cityCaps]);
  241.         }
  242.     
  243.         if (!$selectedCity) {
  244.             $this->addFlash('error''Aucune ville trouvée');
  245.             return $this->redirectToRoute('home');
  246.         }
  247.     
  248.         $criteria = [
  249.             'cityId' => $selectedCity->getId(),
  250.             'city' => $selectedCity->getCity(),
  251.             'minPrice' => $request->query->get('minPrice'),
  252.             'maxPrice' => $request->query->get('maxPrice'),
  253.             'type' => $request->query->get('type'),
  254.             'isShared' => $request->query->get('isShared'),
  255.             'isFurnished' => $request->query->get('isFurnished'),
  256.             'bathroomType' => $request->query->get('bathroomType'),
  257.             'isAidEligible' => $request->query->get('isAidEligible'),
  258.             'dpe' => array_keys($request->query->all('dpe')),
  259.             'minSurface' => $request->query->get('minSurface'),
  260.             'maxSurface' => $request->query->get('maxSurface'),
  261.         ];
  262.     
  263.         $selectedBuildings $buildingRepository->findBySearchCriteria($criteria$page$limit);
  264.         $totalItems $buildingRepository->countBySearchCriteria($criteria);
  265.         $pagesCount ceil($totalItems $limit);
  266.     
  267.         // Création de la map pour afficher les résultats
  268.         $buildingsMap = [];
  269.         foreach ($selectedBuildings as $building) {
  270.             if ($building->getLng() !== null && $building->getLat() !== null) {
  271.                 $buildingsMap[] = [
  272.                     'lat' => $building->getLat(),
  273.                     'lng' => $building->getLng(),
  274.                     'id' => $building->getId(),
  275.                 ];
  276.             }
  277.         }
  278.     
  279.         // Gestion des bâtiments likés
  280.         $likedBuildings = [];
  281.         $user $this->getUser();
  282.         if ($user) {
  283.             foreach ($selectedBuildings as $building) {
  284.                 $isLiked $likedBuildingRepository->findOneBy(['user' => $user'building' => $building]) !== null;
  285.                 $likedBuildings[$building->getId()] = $isLiked;
  286.             }
  287.         }
  288.         //dd($selectedBuildings);
  289.         $selectedBuildingsArray array_map(function ($building) {
  290.             return [
  291.                 'id' => $building->getId(),
  292.                 'latitude' => $building->getLat(),
  293.                 'longitude' => $building->getLng(),
  294.             ];
  295.         }, $selectedBuildings);
  296.     
  297.         return $this->render('home/search.html.twig', [
  298.             'selectedBuildingsMap' => $selectedBuildingsArray,
  299.             'selectedBuildings' => $selectedBuildings,
  300.             'city' => $city,
  301.             'lat' => $lat,
  302.             'lng' => $lng,
  303.             'likedBuildings' => $likedBuildings,
  304.             'buildingsMap' => $buildingsMap,
  305.             'totalItems' => $totalItems,
  306.             'pagesCount' => $pagesCount,
  307.             'currentPage' => $page,
  308.             'query' => $request->query->all(), // Passer les paramètres de requête au template
  309.             'selectedDPE' => array_keys($request->query->all('dpe')),
  310.         ]);
  311.     }
  312.     
  313.      
  314.     #[Route(path: [
  315.         "fr" => "/cgv",
  316.         "en" => "/en/cgv",
  317.     ], name'cgv')]
  318.     public function cgv()
  319.     {
  320.         return $this->render('cgv/cgv.html.twig');
  321.     }
  322.     #[Route(path: [
  323.         "fr" => "/cookies",
  324.         "en" => "/en/cookies",
  325.     ], name'cookies')]
  326.     public function cookies()
  327.     {
  328.         return $this->render('cookies/index.html.twig');
  329.     }
  330.     
  331.     #[Route(path: [
  332.         "fr" => "/assurance",
  333.         "en" => "/en/assurance",
  334.     ], name'assurance')]
  335.     public function assurance()
  336.     {
  337.         return $this->render('assurance/index.html.twig');
  338.     }
  339.     #[Route(path: [
  340.         "fr" => "/attestation",
  341.         "en" => "/en/attestation",
  342.     ], name'attestation')]
  343.     public function attestation()
  344.     {
  345.         return $this->render('attestation/index.html.twig');
  346.     }
  347.     #[Route(path: [
  348.         "fr" => "/qui",
  349.         "en" => "/en/qui",
  350.     ], name'qui')]
  351.     public function qui()
  352.     {
  353.         return $this->render('qui/index.html.twig');
  354.     }
  355.     #[Route(path: [
  356.         "fr" => "/services",
  357.         "en" => "/en/services",
  358.     ], name'services')]
  359.     public function services()
  360.     {
  361.         return $this->render('services/index.html.twig');
  362.     }
  363.     #[Route(path: [
  364.         "fr" => "/partenaire",
  365.         "en" => "/en/partenaire",
  366.     ], name'partenaire')]
  367.     public function partenaire()
  368.     {
  369.         return $this->render('partenaire/index.html.twig');
  370.     }
  371.     #[Route(path: [
  372.         "fr" => "/why_us",
  373.         "en" => "/en/why_us",
  374.     ], name'why_us')]
  375.     public function why_us()
  376.     {
  377.         return $this->render('why_us/index.html.twig');
  378.     }
  379.     #[Route(path: [
  380.         "fr" => "/contact",
  381.         "en" => "/en/contact",
  382.     ], name'contact')]
  383.     public function contact(Request $requestMails $mails)
  384.     {
  385.         $form $this->createForm(ContactForm::class);
  386.         $form->handleRequest($request);
  387.         if ($form->isSubmitted() && $form->isValid()) {
  388.             $to = ['contact@roomlers.com''julie@roomlers.com'];
  389.             $data $form->getData();
  390.             $email $mails->createEmail('mails/contactUs.html.twig', [
  391.                 "prenom" => $data['firstName'],
  392.                 "nom" => $data['lastName'],
  393.                 "email" => $data['email'],
  394.                 "tel" => $data['phone'],
  395.                 "requestType" => $data['requestType'],
  396.                 "problemType" => $data['problemType'],
  397.                 "message" => $data['message']
  398.             ])
  399.             ->to(...$to)
  400.             ->subject('Formulaire Roomlers');
  401.             $mails->send($email);
  402.             $this->addFlash('notice''Le formulaire de contact a bien été envoyé.');
  403.             return $this->redirectToRoute('contact');
  404.         }
  405.         return $this->render('contact/index.html.twig', [
  406.             'form' => $form,
  407.         ]);
  408.     }
  409.     #[Route(path: [
  410.         "fr" => "/privacy",
  411.         "en" => "/en/privacy",
  412.     ], name'privacy')]
  413.     public function privacy()
  414.     {
  415.         return $this->render('privacy/index.html.twig');
  416.     }
  417.     #[Route(path: [
  418.         "fr" => "/plan",
  419.         "en" => "/en/plan",
  420.     ], name'plan')]
  421.     public function plan()
  422.     {
  423.         return $this->render('plan/index.html.twig');
  424.     }
  425.     #[Route('/userForm/attestation'name'userFormAttestation')]
  426.     public function userFormAttestation(Request $requestMailerInterface $mailer)
  427.     {
  428.         $userForm = new UserForm();
  429.         $form $this->createForm(AttestationUserFormType::class, $userForm);
  430.         $form->handleRequest($request);
  431.         if ($form->isSubmitted() && $form->isValid()) {
  432.             $email $userForm->getEmail();
  433.             $emailExists $this->userFormRepository->findByEmailFormAttestation($email);
  434.             if ($emailExists) {
  435.                 return new JsonResponse([
  436.                     'error' => 'Une erreur est survenue, veuillez vérifier vos informations. ❌',
  437.                     'errors' => ['email' => 'Cet email est déjà utilisé.']
  438.                 ], 400);
  439.             }
  440.             $userForm->setAttestationPrereservation(true);
  441.             $this->entityManager->persist($userForm);
  442.             $this->entityManager->flush();
  443.             $messageContent "
  444.             Nom: " $userForm->getFirstName() . "
  445.             Prénom: " $userForm->getLastName() . "
  446.             Date de naissance: " $userForm->getBirthDate()->format('Y-m-d') . "
  447.             Nationalité: " $userForm->getNationality() . "
  448.             Email: " $userForm->getEmail() . "
  449.             Téléphone: " $userForm->getPhone() . "
  450.             Ville: " $userForm->getCity() . "
  451.             Type de logement: " $userForm->getType() . "
  452.             Budget: " $userForm->getBudget() . "
  453.             N° de passeport: " $userForm->getPassportNumber() . "
  454.             Expiration du passeport: " $userForm->getPassportExpirationDate()->format('Y-m-d') . "
  455.             Ecole: " $userForm->getSchool() . "
  456.             Date de rentrée: " $userForm->getStartDateSchool()->format('Y-m-d') . "
  457.             Consulat/Ambassade: " $userForm->getConsulate() . "
  458.             Inscription à la newsletter: " . ($userForm->getAcceptNewsletter() ? 'Oui' 'Non') . "
  459.             ";
  460.             $emailRoomlers = (new Email())
  461.                 ->from('noreply@roomlers.com')
  462.                 ->to('geraldlegoff@appyness.fr')
  463.                 ->cc('contact@roomlers.com''julie@roomlers.com')
  464.                 ->subject('Obtenir une attestation de pré-réservation de logement dans le cadre d’une demande de visa')
  465.                 ->text('Obtenir une attestation de pré-réservation de logement dans le cadre d’une demande de visa' $messageContent);
  466.             $mailer->send($emailRoomlers);
  467.             $messageContent "Votre demande a bien été prise en compte. Nous vous remercions pour la confiance accordée à Roomlers.
  468.             Un membre de notre équipe prendra rapidement contact avec vous.";
  469.             $emailCustomer = (new Email())
  470.                 ->from('noreply@roomlers.com')
  471.                 ->to($email)
  472.                 ->subject('Formulaire de Pré-réservation de Logement')
  473.                 ->text('Formulaire de Pré-réservation de Logement ' $messageContent);
  474.             $mailer->send($emailCustomer);
  475.             return new JsonResponse(['success' => 'Formulaire soumis et email envoyé avec succès!'], 200);
  476.         }
  477.         return $this->render('userForm/attestation.html.twig', [
  478.             'form' => $form->createView(),
  479.         ]);
  480.     }
  481.     #[Route('/userForm/owner'name'userFormOwner')]
  482.     public function userFormOwner(Request $requestMailerInterface $mailer)
  483.     {
  484.         $userForm = new UserForm();
  485.         $form $this->createForm(OwnerUserFormType::class, $userForm);
  486.         $form->handleRequest($request);
  487.         if ($form->isSubmitted() && $form->isValid()) {
  488.             $captcha_response $request->request->get('captcha');
  489.             $captcha_num1 $request->request->get('captcha_num1');
  490.             $captcha_num2 $request->request->get('captcha_num2');
  491.             // Vérifier la réponse du captcha
  492.             if ((int)$captcha_response !== ((int)$captcha_num1 + (int)$captcha_num2)) {
  493.                 return new JsonResponse([
  494.                     'error' => 'Captcha incorrect. Veuillez réessayer.',
  495.                 ], 400);
  496.             }
  497.             $email $userForm->getEmail();
  498.             $emailExists $this->userFormRepository->findByEmailFormOwner($email);
  499.             if ($emailExists) {
  500.                 return new JsonResponse([
  501.                     'error' => 'Une erreur est survenue, veuillez vérifier vos informations. ❌',
  502.                     'errors' => ['email' => 'Cet email est déjà utilisé.']
  503.                 ], 400);
  504.             }
  505.             $userForm->setOwner(true);
  506.             $this->entityManager->persist($userForm);
  507.             $this->entityManager->flush();
  508.             $messageContent "
  509.             Nom: " $userForm->getFirstName() . "
  510.             Prénom: " $userForm->getLastName() . "
  511.             Nationalité: " $userForm->getNationality() . "
  512.             Email: " $userForm->getEmail() . "
  513.             Téléphone: " $userForm->getPhone() . "
  514.             Ville: " $userForm->getCity() . "
  515.             Type de logement: " $userForm->getType() . "
  516.             Loyer mensuel charges comprises: " $userForm->getMonthlyRent() . "
  517.             Charges mensuelles: " $userForm->getMonthlyCharges() . "
  518.             Disponible à partir de: " $userForm->getAvailableFrom()->format('Y-m-d') . "
  519.             Présentez-nous brièvement votre logement: " $userForm->getDescription() . "
  520.             Inscription à la newsletter: " . ($userForm->getAcceptNewsletter() ? 'Oui' 'Non') . "
  521.             ";
  522.             $emailRoomlers = (new Email())
  523.                 ->from('noreply@roomlers.com')
  524.                 ->to('mohamedouzammad@appyness.fr')
  525.                 ->cc('contact@roomlers.com''julie@roomlers.com')
  526.                 ->subject('Proposer votre logement à la location à plus de 4500 potentiels locataires')
  527.                 ->text('Proposer votre logement à la location à plus de 4500 potentiels locataires' $messageContent);
  528.             $mailer->send($emailRoomlers);
  529.             $messageContent "Votre demande a bien été prise en compte. Nous vous remercions pour la confiance accordée à Roomlers. `\n` Un membre de notre équipe prendra rapidement contact avec vous.";
  530.             $emailCustomer = (new Email())
  531.             ->from('noreply@roomlers.com')
  532.             ->to($email)
  533.             ->subject('Proposer votre logement à la location à plus de 4500 potentiels locataires')
  534.             ->text('Proposer votre logement à la location à plus de 4500 potentiels locataires' $messageContent);
  535.             $mailer->send($emailCustomer);
  536.             return new JsonResponse(['success' => 'Formulaire soumis et email envoyé avec succès!'], 200);
  537.         }
  538.         return $this->render('userForm/owner.html.twig', [
  539.             'form' => $form->createView(),
  540.         ]);
  541.     }
  542.     #[Route('/userForm/tenant'name'userFormTenant')]
  543.     public function userFormTenant(Request $requestMailerInterface $mailer)
  544.     {
  545.         $userForm = new UserForm();
  546.         $form $this->createForm(TenantUserFormType::class, $userForm);
  547.         $form->handleRequest($request);
  548.         if ($form->isSubmitted() && $form->isValid()) {
  549.             $captcha_response $request->request->get('captcha');
  550.             $captcha_num1 $request->request->get('captcha_num1');
  551.             $captcha_num2 $request->request->get('captcha_num2');
  552.             // Vérifier la réponse du captcha
  553.             if ((int)$captcha_response !== ((int)$captcha_num1 + (int)$captcha_num2)) {
  554.                 return new JsonResponse([
  555.                     'error' => 'Captcha incorrect. Veuillez réessayer.',
  556.                 ], 400);
  557.             }
  558.             $email $userForm->getEmail();
  559.             $emailExists $this->userFormRepository->findByEmailFormTenant($email);
  560.             if ($emailExists) {
  561.                 return new JsonResponse([
  562.                     'error' => 'Une erreur est survenue, veuillez vérifier vos informations. ❌',
  563.                     'errors' => ['email' => 'Cet email est déjà utilisé.']
  564.                 ], 400);
  565.             }
  566.             $userForm->setTenant(true);
  567.             $this->entityManager->persist($userForm);
  568.             $this->entityManager->flush();
  569.             $messageContent "
  570.             Nom: " $userForm->getFirstName() . "
  571.             Prénom: " $userForm->getLastName() . "
  572.             Date de naissance: " $userForm->getBirthDate()->format('Y-m-d') . "
  573.             Nationalité: " $userForm->getNationality() . "
  574.             Email: " $userForm->getEmail() . "
  575.             Téléphone: " $userForm->getPhone() . "
  576.             Ville: " $userForm->getCity() . "
  577.             Type de logement: " $userForm->getType() . "
  578.             Budget: " $userForm->getBudget() . "
  579.             Durée de location (nombre de mois): " $userForm->getRentalDuration() . "
  580.             Date de début de location: " $userForm->getRentalDate()->format('Y-m-d') . "
  581.             Autre information: " $userForm->getAdditionalInformation() . "
  582.             Inscription à la newsletter: " . ($userForm->getAcceptNewsletter() ? 'Oui' 'Non') . "
  583.             ";
  584.             $emailRoomlers = (new Email())
  585.                 ->from('noreply@roomlers.com')
  586.                 ->to('mohamedouzammad@appyness.fr')
  587.                 ->cc('contact@roomlers.com''julie@roomlers.com')
  588.                 ->subject('Formulaire de réservation de logement')
  589.                 ->text('Formulaire de réservation de logement : colocation, coliving, studio, appartement… ' $messageContent);
  590.             $mailer->send($emailRoomlers);
  591.             $messageContent "Votre demande a bien été prise en compte. Nous vous remercions pour votre confiance.
  592.             Un membre de notre équipe prendra rapidement contact avec vous.";
  593.             $emailCustomer = (new Email())
  594.                 ->from('noreply@roomlers.com')
  595.                 ->to($email)
  596.                 ->subject('Formulaire de réservation de logement')
  597.                 ->text('Formulaire de réservation de logement : colocation, coliving, studio, appartement… ' $messageContent);
  598.             $mailer->send($emailCustomer);
  599.             return new JsonResponse(['success' => 'Formulaire soumis et email envoyé avec succès!'], 200);
  600.         }
  601.         return $this->render('userForm/tenant.html.twig', [
  602.             'form' => $form->createView(),
  603.         ]);
  604.     }
  605.   
  606. // #[Route('/userForm', name: 'userForm')]
  607. // public function userForm(Request $request): Response
  608. // {
  609. //     $formChoice = $request->get('form_choice');
  610. //     if ($formChoice) {
  611. //         switch ($formChoice) {
  612. //             case 'attestation':
  613. //                 return $this->redirectToRoute('userFormAttestation');
  614. //             case 'tenant':
  615. //                 return $this->redirectToRoute('userFormTenant');
  616. //             case 'owner':
  617. //                 return $this->redirectToRoute('userFormOwner');
  618. //             default:
  619. //                 $this->addFlash('error', 'Choix de formulaire invalide.');
  620. //                 return $this->redirectToRoute('userForm'); 
  621. //         }
  622. //     }
  623. //     // 🛠️ Ajout du formulaire manquant
  624. //     $userForm = new UserForm();
  625. //     $form = $this->createForm(NewsletterUserFormType::class, $userForm);
  626. //     return $this->render('userForm/index.html.twig', [
  627. //         'form' => $form->createView(), // Assurez-vous que la variable "form" est bien transmise
  628. //     ]);
  629. // }
  630.     #[Route('/userForm/newsletter'name'userFormNewsletter')]
  631.     public function userFormNewsletter(Request $requestMailerInterface $mailer)
  632.     {
  633.         $userForm = new UserForm();
  634.         $form $this->createForm(NewsletterUserFormType::class, $userForm);
  635.         $form->handleRequest($request);
  636.         $honeypot $request->request->get('input');
  637.         if (!empty($honeypot)) {
  638.             return new JsonResponse(['error' => 'Error'], 400);
  639.         }
  640.         $captchaResponse $request->request->get('g-recaptcha-response');
  641.         $secretKey '6LdBVfEqAAAAAOLSsi_uSd3Hfh7aySkQpnwqbOWY';
  642.         $url 'https://www.google.com/recaptcha/api/siteverify';
  643.         $data = [
  644.             'secret' => $secretKey,
  645.             'response' => $captchaResponse
  646.         ];
  647.     
  648.         $options = [
  649.             'http' => [
  650.                 'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
  651.                 'method'  => 'POST',
  652.                 'content' => http_build_query($data),
  653.             ],
  654.         ];
  655.     
  656.         $context  stream_context_create($options);
  657.         $verify file_get_contents($urlfalse$context);
  658.         $captchaSuccess json_decode($verify);
  659.     
  660.         if (!$captchaSuccess->success) {
  661.             return new JsonResponse([
  662.                 'error' => 'Captcha invalide',
  663.             ], 400);
  664.         }
  665.         if ($form->isSubmitted() && $form->isValid()) {
  666.             $email $userForm->getEmail();
  667.             $emailExists $this->userFormRepository->findByEmailFormNewsletter($email);
  668.             if ($emailExists) {
  669.                 return new JsonResponse([
  670.                     'error' => 'Veuillez vérifier vos informations. ❌',
  671.                     'errors' => ['email' => 'Veuillez vérifier vos informations. ❌']
  672.                 ], 400);
  673.             }
  674.             $userForm->setNewsletter(true);
  675.             $this->entityManager->persist($userForm);
  676.             $this->entityManager->flush();
  677.             $messageContent "
  678.             Nom: " $userForm->getFirstName() . "
  679.             Prénom: " $userForm->getLastName() . "
  680.             Email: " $userForm->getEmail() . "
  681.             ";
  682.             $emailRoomlers = (new Email())
  683.                 ->from('noreply@roomlers.com')
  684.                 ->to('julie@roomlers.com')
  685.                 ->cc('contact@roomlers.com''hello@appyness.fr')
  686.                 ->subject('Inscription à la newsletter Roomlers')
  687.                 ->text('Nouvelle inscription à la newsletter : ' $messageContent);
  688.             $mailer->send($emailRoomlers);
  689.             $messageContent "Merci de vous être inscrit à la newsletter Roomlers. Vous recevrez bientôt des informations exclusives et des offres spéciales.";
  690.             $emailCustomer = (new Email())
  691.                 ->from('noreply@roomlers.com')
  692.                 ->to($email)
  693.                 ->subject('Confirmation d\'inscription à la newsletter Roomlers')
  694.                 ->text($messageContent);
  695.             $mailer->send($emailCustomer);
  696.             return new JsonResponse(['success' => 'Inscription à la newsletter confirmée!'], 200);
  697.         }
  698.         return $this->render('userForm/index.html.twig', [
  699.             'form' => $form->createView(),
  700.         ]);
  701.     }
  702.     #[Route(path: [
  703.         "fr" => "/home",
  704.         "en" => "/en/home",
  705.     ], name'landing')]
  706.     public function landing(): Response
  707.     {
  708.         // Récupérer les 50 derniers logements
  709.         $recentBuildings $this->entityManager->getRepository(Building::class)
  710.             ->findBy([], ['createdAt' => 'DESC'], 50);
  711.     
  712.         // Filtrer les logements actifs
  713.         $activeBuildings array_filter($recentBuildings, function($building) {
  714.             return $building->getIsActive();
  715.         });
  716.     
  717.         // Trier les logements actifs par date de création et limiter à 8
  718.         usort($activeBuildings, function($a$b) {
  719.             return $b->getCreatedAt() <=> $a->getCreatedAt();
  720.         });
  721.     
  722.         $activeBuildings array_slice($activeBuildings08);
  723.     
  724.         // Récupérer les documents associés aux bâtiments actifs
  725.         $buildingDocuments = [];
  726.         foreach ($activeBuildings as $building) {
  727.             $buildingDocuments[$building->getId()] = $building->getBuildingDocuments();
  728.         }
  729.     
  730.         return $this->render('home/landing_page.html.twig', [
  731.             'recentBuildings' => $activeBuildings,
  732.             'buildingDocuments' => $buildingDocuments,
  733.         ]);
  734.     }
  735. }