src/Controller/CentreController.php line 225

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use App\Entity\AccessCentre;
  4. use App\Entity\Audio;
  5. use App\Entity\Audiometrie\Setting;
  6. use App\Entity\Factures;
  7. use App\Entity\AudioCentre;
  8. use App\Entity\AudioDiplome;
  9. use App\Entity\AudioMotif;
  10. use App\Entity\CancellationRecord;
  11. use App\Entity\AudioSpecialite;
  12. use App\Entity\CenterImported;
  13. use App\Entity\AtoLauditionPartner;
  14. use App\Entity\Centre;
  15. use App\Entity\CentreMutuelle;
  16. use App\Entity\SpecificSubscription;
  17. use App\Entity\CentrePrestation;
  18. use App\Entity\CentreTier;
  19. use App\Entity\CenterImage;
  20. use App\Entity\Client;
  21. use App\Entity\Diplome;
  22. use App\Entity\ContractCategory;
  23. use App\Entity\ExperiencePro;
  24. use App\Entity\Lieu;
  25. use App\Entity\Ville;
  26. use App\Entity\LieuPrestation;
  27. use App\Service\Billing\BillingCdaService;
  28. use App\Entity\Motif;
  29. use App\Entity\Station;
  30. use App\Entity\Partner\PartnerSubscription;
  31. use App\Entity\Mutuelle;
  32. use App\Repository\RegionDepartmentRepository;
  33. use App\Service\AdsCompany\GoogleSheetsService;
  34. use App\Service\Payment\SubscriptionService;
  35. use App\Service\Subscription\StripeService;
  36. use App\Service\Order\OrderPatient;
  37. use App\Service\Billing\BillingAtolService;
  38. use App\Entity\Plan;
  39. use App\Entity\Prestation;
  40. use App\Entity\Specialite;
  41. use App\Entity\Tier;
  42. use App\Entity\Payment\Subscription;
  43. use App\Entity\ClientTemp;
  44. use App\Entity\Token;
  45. use App\Entity\Rdv;
  46. use App\Service\FileUploader;
  47. use App\Service\PublicFunction;
  48. use DateInterval;
  49. use DateTimeZone;
  50. use App\Entity\Audio\Role;
  51. use Psr\Log\LoggerInterface;
  52. use Doctrine\Common\Collections\ArrayCollection;
  53. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  54. use Symfony\Component\HttpFoundation\Request;
  55. use Symfony\Component\HttpFoundation\Response;
  56. use Symfony\Component\Routing\Annotation\Route;
  57. use DateTime;
  58. use Symfony\Contracts\HttpClient\HttpClientInterface;
  59. use Symfony\Component\String\Slugger\SluggerInterface;
  60. use App\Service\Notification\EmailNotificationDemoService;
  61. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  62. class CentreController extends AbstractController
  63. {
  64.     private $logger;
  65.     private $slugger;
  66.     private $orderPatient;
  67.     private $emailNotificationDemoService;
  68.     public function __construct(LoggerInterface $loggerOrderPatient $orderPatient,GoogleSheetsService $googleSheetsService,RegionDepartmentRepository $regionDepartmentRepositoryEmailNotificationDemoService $emailNotificationDemoServiceHttpClientInterface $clientSluggerInterface $slugger)
  69.     {
  70.         $this->logger $logger;
  71.         $this->client $client;
  72.         $this->slugger $slugger;
  73.         $this->orderPatient $orderPatient;
  74.         $this->emailNotificationDemoService $emailNotificationDemoService;
  75.         $this->regionDepartmentRepository $regionDepartmentRepository;
  76.         $this->googleSheetsService $googleSheetsService;
  77.     }
  78.     /**
  79.      * @Route("/centre/{id}", name="deleteCentreByID", methods={"DELETE"})
  80.      */
  81.     public function deleteCentreByID(Request $requestCentre $centre)
  82.     {
  83.         if (!$request->query->get('token'))
  84.             return new Response(json_encode([
  85.                 "message" => "Pas de token n'a été spécifié",
  86.                 "status" => 401,
  87.             ]), 401);
  88.         $entityManager $this->getDoctrine()->getManager();
  89.         /** @var Token */
  90.         $token $this->getDoctrine()
  91.             ->getRepository(Token::class)
  92.             ->findOneBy(['token' => $request->query->get('token'), 'id_audio' => $centre->getIdGerant()]);
  93.         if (!$token)
  94.             return new Response(json_encode([
  95.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  96.                 "status" => 404,
  97.             ]), 404);
  98.         // get token age
  99.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  100.         // if the token if older than 7 days
  101.         if ($dateDiff->7) {
  102.             $entityManager->remove($token);
  103.             $entityManager->flush();
  104.             return $this->json([
  105.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  106.                 'path' => 'src/Controller/ClientController.php',
  107.                 "status" => 401
  108.             ], 401);
  109.         }
  110.         $accessCentre $this->getDoctrine()->getRepository(AccessCentre::class)
  111.         ->findBy(array('id_centre' => $centre->getId()));
  112.         $centerParent $this->getDoctrine()
  113.             ->getRepository(Centre::class)
  114.             ->findOneBy(['id_gerant' => $centre->getIdGerant()]);
  115.         $meetings $this->getDoctrine()
  116.             ->getRepository(Rdv::class)
  117.             ->findBy(['id_centre' => $centre->getId()]);
  118.         $clients $this->getDoctrine()
  119.             ->getRepository(ClientTemp::class)
  120.             ->findBy(['id_centre' => $centre->getId()]);
  121.         $mutuels $this->getDoctrine()
  122.             ->getRepository(CentreMutuelle::class)
  123.             ->findBy(['id_centre' => $centre->getId()]);
  124.         /*  $tiers = $this->getDoctrine()
  125.         ->getRepository(CentreTier::class)
  126.         ->findBy(['id_centre' => $centre->getId()]);*/
  127.         $prestations $this->getDoctrine()
  128.             ->getRepository(CentrePrestation::class)
  129.             ->findBy(['id_centre' => $centre->getId()]);
  130.         $entityManager $this->getDoctrine()->getManager();
  131.         // return $this->json(["id" => $tiers]);
  132.         /*  foreach ($tiers as $tier) {
  133.             $entityManager->remove($tier);
  134.             }*/
  135.         foreach ($meetings as $meeting) {
  136.             $entityManager->remove($meeting);
  137.         }
  138.         foreach ($mutuels as $mutuel) {
  139.             $entityManager->remove($mutuel);
  140.         }
  141.         foreach ($prestations as $prestation) {
  142.             $entityManager->remove($prestation);
  143.         }
  144.        
  145.         foreach ($accessCentre as $access) {
  146.             $entityManager->remove($access);
  147.         }
  148.         foreach ($clients as $client) {
  149.             $entityManager->remove($client);
  150.         }
  151.         foreach ($meetings as $meeting) {
  152.             $meeting->setIdCentre($centerParent);
  153.             $entityManager->persist($meeting);
  154.         }
  155.         foreach ($clients as $client) {
  156.             $client->setIdCentre($centerParent);
  157.             $entityManager->persist($client);
  158.         }
  159.         $entityManager $this->getDoctrine()->getManager();
  160.         $audioCentres $entityManager->getRepository(AudioCentre::class)->findOneBy(['id_centre' => $centre->getId()]);
  161.         $entityManager->remove($audioCentres);
  162.         $entityManager->remove($centre);
  163.         $entityManager->flush();
  164.         return $this->json(["id" => $centerParent->getId(), "name" => $centerParent->getName()]);
  165.         //  return new Response($centre->getId() . " has been successfully deleted");
  166.     }
  167.     /**
  168.      * @Route("/centres/query", name="getCentresSearchQuery", methods={"GET","HEAD"})
  169.      */
  170.     public function getCentresSearchQuery(Request $request): Response
  171.     {
  172.         /** @var ActivityRepository */
  173.         $activityRepo $this->getDoctrine();
  174.         if (strlen($request->query->get('query')) == && is_numeric($request->query->get('query'))) {
  175.             /** @var Centre[] */
  176.             $centres $this->getDoctrine()->getRepository(Centre::class)
  177.                 ->findBy(["postale" => (int)$request->query->get('query')]);
  178.         } else {
  179.             /** @var Centre[] */
  180.             $centres $this->getDoctrine()->getRepository(Centre::class)
  181.                 ->findByQuery($request->query->get('query'));
  182.         }
  183.         $result = new ArrayCollection();
  184.         foreach ($centres as $centre) {
  185.             $result->add([
  186.                 "id" => $centre->getId(),
  187.                 "name" => $centre->getName() . ", " $centre->getAddress() . ", " $centre->getPostale() . " " $centre->getCity(),
  188.             ]);
  189.         }
  190.         return new Response(json_encode([
  191.             "content" => $result->toArray(),
  192.             "status" => 200,
  193.         ]));
  194.     }
  195.     /**
  196.      * @Route("/centres", name="getCentresSearch", methods={"GET","HEAD"})
  197.      */
  198.     public function getCentresSearch(Request $requestPublicFunction $publicFunction): Response
  199.     {
  200.         // Récupérer les paramètres de la requête
  201.         // $queryParams = $request->query->all();
  202.         // // Ajouter les paramètres dans la réponse pour les afficher
  203.         // return new Response(
  204.         //     json_encode([
  205.         //         'data' => $queryParams, // Afficher les paramètres de la requête
  206.         //     ]),
  207.         //     200
  208.         // );
  209.         /*
  210.         /** @var ActivityRepository */
  211.         $activityRepo $this->getDoctrine();
  212.         $date = new DateTime();
  213.         $centres = [];
  214.         $lieux = [];
  215.         $centreCoord = [];
  216.         $lieuxCoord = [];
  217.         $centreName = [];
  218.         $lieuxName = [];
  219.         setlocale(LC_TIME'fr_FR');
  220.         $city $request->query->get('ville');
  221.         $name $request->query->get('name');
  222.         $address $request->query->get('address');
  223.         $page $request->query->getInt('page'1);
  224.         $limit $request->query->get('limit'); // Number of results per page
  225.         $longitude $request->query->get('longitude');
  226.         $latitude $request->query->get('latitude');
  227.         /*   $formattedAddress = "21,avenue du Maine,70015 Paris";
  228.         $response = $this->client->request('GET','https://maps.googleapis.com/maps/api/geocode/json', [
  229.             'query' => [
  230.                 'address' => $formattedAddress,
  231.                 'key' => 'AIzaSyB-w9vBKJ9IYNPevzRu4sxhfZ2O4FAPOZc'
  232.             ]
  233.         ]);
  234.     
  235.         $data = $response->toArray();
  236.         dd($data);*/
  237.         // $request->query->get('longitude') && $request->query->get('latitude');
  238.         // dd($request->query->get('longitude'));
  239.         $repository $this->getDoctrine()->getRepository(CenterImported::class);
  240.         $resultsImportded $repository->findByCoordinates($name$longitude$latitude$page$limit);
  241.         //   $resultsImportded = $repository->findByCityOrPostalCodeAndName($city, $name, $address, $page, $limit ,$longitude,$latitude);
  242.         $totalResults $repository->getTotalCountByCityOrPostalCodeAndName($name$longitude$latitude$page$limit);
  243.         /*  $repository = $this->getDoctrine()->getRepository(CenterImported::class);
  244.         $resultsImportded = $repository->findByCityOrPostalCodeAndName($city, $name, $address, $page, $limit);
  245.     
  246.         $totalResults = $repository->getTotalCountByCityOrPostalCodeAndName($city, $name, $address);*/
  247.         if (is_numeric($totalResults) && is_numeric($limit) && $limit !== && $totalResults !== 0) {
  248.             $totalPages ceil($totalResults $limit);
  249.         } elseif ($totalResults === 0) {
  250.             $totalPages 0;
  251.         } else {
  252.             $totalPages 1;
  253.         }
  254.         //  dd( ceil($totalResults / $limit));
  255.         $centerImportedArray array_map(function ($session) {
  256.             return [
  257.                 "id" => $session->getId(),
  258.                 "nom" => $session->getNom(),
  259.                 "slug" => $session->getSlug(),
  260.                 "adresse" => $session->getAdresse(),
  261.                 "latitude" => $session->getLatitude(),
  262.                 "longitude" => $session->getLongitude(),
  263.                 "codePostal" => $session->getcodePostal(),
  264.                 "ville" => $session->getVille(),
  265.             ];
  266.         }, $resultsImportded);
  267.         //dd($centerImportedArray);
  268.         //if the user searched by coordinates
  269.         if ($request->query->get('address')) {
  270.             /** @var Centre[] */
  271.             $centreCoord $this->getDoctrine()->getRepository(Centre::class)
  272.                 ->findByAdress($request->query->get('address'));
  273.         }
  274.         if ($request->query->get('longitude') && $request->query->get('latitude')) {
  275.             /** @var Centre[] */
  276.             $centreCoord $this->getDoctrine()->getRepository(Centre::class)
  277.                 ->findByCoordonates($request->query->get('longitude'), $request->query->get('latitude'), $page$limit);
  278.             /** @var Lieu[] */
  279.             $lieuxCoord $this->getDoctrine()->getRepository(Lieu::class)
  280.                 ->findByCoordonates($request->query->get('longitude'), $request->query->get('latitude'), $page$limit);
  281.         }
  282.         if ($request->query->get('name')) {
  283.             $centresID $this->getDoctrine()->getRepository(Centre::class)
  284.                 ->findByName($request->query->get('name'));
  285.             /** @var Centre[] */
  286.             foreach ($centresID as $centreID) {
  287.                 $centre $this->getDoctrine()->getRepository(Centre::class)
  288.                     ->find($centreID);
  289.                 if ($centre)
  290.                     array_push($centreName,  $centre);
  291.             }
  292.             /** @var int[] */
  293.             $lieuxID $this->getDoctrine()->getRepository(Lieu::class)
  294.                 ->findByName($request->query->get('name'));
  295.             /** @var Lieux[] */
  296.             foreach ($lieuxID as $lieuID) {
  297.                 $lieu $this->getDoctrine()->getRepository(Lieu::class)
  298.                     ->find($lieuID);
  299.                 if ($lieu)
  300.                     array_push($lieuxName,  $lieu);
  301.             }
  302.         }
  303.         if ($request->query->get('longitude') &&  $request->query->get('name') && !$request->query->get('address')) {
  304.             //$centres = array_intersect($centreCoord, $centreName);
  305.             $centres array_uintersect($centreName$centreCoord, function ($centreName$centreCoord) {
  306.                 return spl_object_hash($centreName) <=> spl_object_hash($centreCoord);
  307.             });
  308.             $lieux array_uintersect($lieuxName$lieuxCoord, function ($lieuxName$lieuxCoord) {
  309.                 return spl_object_hash($lieuxName) <=> spl_object_hash($lieuxCoord);
  310.             });
  311.         } else {
  312.             if ($request->query->get('name')) {
  313.                 $centres $centreName;
  314.                 $lieux $lieuxName;
  315.             } else {
  316.                 $centres $centreCoord;
  317.                 $lieux $lieuxCoord;
  318.             }
  319.         }
  320.         if (!$request->query->get('longitude') && !$request->query->get('name') && !$request->query->get('address')) {
  321.             // basic search of paris coordinates
  322.             /** @var Centre[] */
  323.             $centres $this->getDoctrine()->getRepository(Centre::class)
  324.                 ->findByCoordonates(2.3448.85$page$limit);
  325.             /** @var Lieu[] */
  326.             $lieux $this->getDoctrine()->getRepository(Lieu::class)
  327.                 ->findByCoordonates(2.3448.85$page$limit);
  328.         }
  329.         if (count($centres) < && count($lieux) < 1) {
  330.             // dd('dd');
  331.             return new Response(json_encode([
  332.                 "content" => [],
  333.                 "centerImported" => $centerImportedArray,
  334.                 "totalPages" => $totalPages,
  335.                 "message" => "Aucun centre/lieu n'a été trouvé avec le nom fournit.",
  336.                 "status" => 404,
  337.             ]), 200);
  338.         }
  339.         // secondly filters all of the other filters
  340.         // checks if there is any result with the search
  341.         if (count($centres) != || count($lieux) != 0) {
  342.             $result = new ArrayCollection();
  343.             $resultAudioMulti = array();
  344.             //gets through all centres given by the function
  345.             foreach ($centres as $centre) {
  346.                 if ($centre->getIsValid() != true)
  347.                     continue;
  348.                 if ($centre->getIsBlocked() == true)
  349.                     continue;
  350.                 //isDomicile filter
  351.                 if (($request->query->get('isDomicile')) && ($request->query->get('isDomicile') == "true")) {
  352.                     if ($centre->getIsRdvDomicile() != true)
  353.                         continue;
  354.                 }
  355.                 // Prestation
  356.                 /** @var CentrePrestation[] */
  357.                 $prestations $this->getDoctrine()->getRepository(CentrePrestation::class)
  358.                     ->findBy(array('id_centre' => $centre->getId()));
  359.                 /** @var Rdv[] */
  360.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  361.                     ->findAllReviewsCentre($centre->getId());
  362.                 //prestation filter
  363.                 if ($request->query->get('prestations') && $request->query->get('prestations') != '') {
  364.                     /** @var int[] */
  365.                     $prestationsToCheck json_decode($request->query->get('prestations'));
  366.                     //test all prestations
  367.                     $allPrestation true;
  368.                     foreach ($prestationsToCheck as $prestationToCheck) {
  369.                         $isContained false;
  370.                         //test if the prestation given is part of the skillset of the centre
  371.                         foreach ($prestations as $prestation) {
  372.                             if ($prestation->getIdPrestation()->getId() == $prestationToCheck) {
  373.                                 $isContained true;
  374.                                 continue;
  375.                             }
  376.                         }
  377.                         // if the prestation isn't contained then stop the loop and toggle the value to false
  378.                         if ($isContained == false) {
  379.                             $allPrestation false;
  380.                             continue;
  381.                         }
  382.                     }
  383.                     // if the user doesn't have all the prestations then skip the work
  384.                     if ($allPrestation == false) continue;
  385.                 }
  386.                 $resultPrestation = new ArrayCollection();
  387.                 foreach ($prestations as $prestation) {
  388.                     $resultPrestation->add([
  389.                         "id" => $prestation->getIdPrestation()->getId(),
  390.                         "titre" => $prestation->getIdPrestation()->getLibelle(),
  391.                     ]);
  392.                 }
  393.                 /** @var AudioCentre[] */
  394.                 $liaisons $this->getDoctrine()->getRepository(AudioCentre::class)
  395.                     ->findBy(array('id_centre' => $centre'isConfirmed' => true));
  396.                 $resultAudio = new ArrayCollection();
  397.                 // goes though the each audio of the center
  398.                 foreach ($liaisons as $liaison) {
  399.                     /** @var Audio */
  400.                     $audio $this->getDoctrine()->getRepository(Audio::class)
  401.                         ->findOneBy(array('id' => $liaison->getIdAudio()));
  402.                     if ($audio->getIsIndieValid() != true && $audio->getIsIndie() != false)
  403.                         continue;
  404.                     /** @var Rdv[] */
  405.                     $audioRdvs $this->getDoctrine()->getRepository(Rdv::class)
  406.                         ->findAllReviewsAudio($audio->getId());
  407.                     // Name filter
  408.                     /*if ($request->query->get('name')) {
  409.                         // if it's the name **isn't** contained in any way, skip the worker
  410.                         $fullname = $publicFunction->normalize($audio->getName() . " " . $audio->getLastname());
  411.                         $namefull = $publicFunction->normalize($audio->getName() . " " . $audio->getLastname());
  412.                         $nameToCheck = $publicFunction->normalize($request->query->get('name'));
  413.                         if (!(str_contains($fullname, $nameToCheck) || str_contains($namefull, $nameToCheck)))
  414.                             continue;
  415.                     }*/
  416.                     // Motif filter
  417.                     /** @var AudioMotif[] */
  418.                     $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  419.                         ->findBy(array('id_audio' => $liaison->getIdAudio()));
  420.                     // will test whether or not the audio has the necessery motif to be added
  421.                     if ($request->query->get('motif')) {
  422.                         $motifID = (int) $request->query->get('motif');
  423.                         $hasMotif false;
  424.                         foreach ($motifs as $motif) {
  425.                             if ($motif->getIdMotif()->getId() == $motifID$hasMotif true;
  426.                         }
  427.                         if ($hasMotif == false) continue;
  428.                     }
  429.                     $resultMotif = new ArrayCollection();
  430.                     foreach ($motifs as $motif) {
  431.                         $resultMotif->add([
  432.                             "id" => $motif->getIdMotif()->getId(),
  433.                             "titre" => $motif->getIdMotif()->getTitre(),
  434.                             "consigne" => $motif->getConsigne(),
  435.                             "duration" => $motif->getDuration(),
  436.                             "isRdvonline" => $motif->getIsRdvonline(),
  437.                         ]);
  438.                     }
  439.                     // Specialities
  440.                     /** @var AudioSpecialite[] */
  441.                     $specialities $this->getDoctrine()->getRepository(AudioSpecialite::class)
  442.                         ->findBy(array('id_audio' => $liaison->getIdAudio()));
  443.                     //speciality filter
  444.                     if ($request->query->get('specialities') && $request->query->get('specialities') != '') {
  445.                         /** @var int[] */
  446.                         $specialitiesToCheck json_decode($request->query->get('specialities'));
  447.                         //test all specialities
  448.                         $allSpecialities true;
  449.                         foreach ($specialitiesToCheck as $specialityToCheck) {
  450.                             $isContained false;
  451.                             //test if the speciality given is part of the skillset of the audio
  452.                             foreach ($specialities as $speciality) {
  453.                                 if ($speciality->getIdSpecialite()->getId() == $specialityToCheck) {
  454.                                     $isContained true;
  455.                                     continue;
  456.                                 }
  457.                             }
  458.                             // if the speciality isn't contained then stop the loop and toggle the value to false
  459.                             if ($isContained == false) {
  460.                                 $allSpecialities false;
  461.                                 continue;
  462.                             }
  463.                         }
  464.                         // if the user doesn't have all the specialities then skip the work
  465.                         if ($allSpecialities == false) continue;
  466.                     }
  467.                     $resultSpeciality = new ArrayCollection();
  468.                     foreach ($specialities as $speciality) {
  469.                         if ($speciality->getIdSpecialite() !== null) {
  470.                             $resultSpeciality->add([
  471.                                 "id" => $speciality->getIdSpecialite()->getId(),
  472.                                 "titre" => $speciality->getIdSpecialite()->getLibelle(),
  473.                             ]);
  474.                         }
  475.                     }
  476.                     //Filter Day
  477.                     if ($request->query->get('day') && $request->query->get('day') != '0') {
  478.                         $day $request->query->get('day');
  479.                         setlocale(LC_TIME'fr_FR.utf8');
  480.                         if ($day == "1") {
  481.                             $dayDispo $publicFunction->calculSchedule($audio, new \DateTime(), $centre);
  482.                             if (count($dayDispo[strftime('%A')]) == 0) {
  483.                                 continue;
  484.                             }
  485.                         }
  486.                         if ($day == "3") {
  487.                             if ((strftime('%A') == "samedi") || (strftime('%A') == "dimanche")) {
  488.                                 $dateAfterWeek = new DateTime();
  489.                                 $dayDispo $publicFunction->calculSchedule($audio, new \DateTime(), $centre);
  490.                                 $day2Dispo $publicFunction->calculSchedule($audio$dateAfterWeek->add(new DateInterval('P7D')), $centre);
  491.                                 if (strftime('%A') == "samedi") {
  492.                                     $nb count($dayDispo[strftime('%A')]) + count($dayDispo[strftime("%A"strtotime("+1 day"))]);
  493.                                     $nb $nb count($day2Dispo['lundi']);
  494.                                     if ($nb == 0) {
  495.                                         continue;
  496.                                     }
  497.                                 }
  498.                                 if (strftime('%A') == "dimanche") {
  499.                                     $nb count($dayDispo[strftime('%A')]);
  500.                                     $nb $nb count($day2Dispo['lundi']) + count($day2Dispo['mardi']);
  501.                                     if ($nb == 0) {
  502.                                         continue;
  503.                                     }
  504.                                 }
  505.                             } else {
  506.                                 $dayDispo $publicFunction->calculSchedule($audio, new \DateTime(), $centre);
  507.                                 //dd($dayDispo);
  508.                                 $nb count($dayDispo[strftime('%A')]) + count($dayDispo[strftime("%A"strtotime("+1 day"))]) + count($dayDispo[strftime("%A"strtotime("+2 day"))]);
  509.                                 if ($nb == 0) {
  510.                                     continue;
  511.                                 }
  512.                             }
  513.                         }
  514.                     }
  515.                     if ($audio->getIsIndie()) {
  516.                         $isNewWorker true;
  517.                         foreach ($resultAudioMulti as $key => $audioMulti) {
  518.                             if ($audioMulti["id"] == $audio->getId()) {
  519.                                 $isNewWorker false;
  520.                                 break;
  521.                             }
  522.                         }
  523.                         $date1 = new DateTime();
  524.                         $date2 = new DateTime();
  525.                         if ($isNewWorkerarray_push($resultAudioMulti, [
  526.                             "id" => $audio->getId(),
  527.                             "civilite" => $audio->getCivilite(),
  528.                             "name" => $audio->getName(),
  529.                             "lastname" => $audio->getLastname(),
  530.                             "birthdate" => $audio->getBirthdate(),
  531.                             "mail" => $audio->getMail(),
  532.                             "phone" => $audio->getPhone(),
  533.                             "adeli" => $audio->getAdeli(),
  534.                             "pin" => $audio->getPin(),
  535.                             "description" => $audio->getDescription(),
  536.                             "imgUrl" => $audio->getImgUrl(),
  537.                             "isRdvDomicileIndie" => $audio->getIsRdvDomicileIndie(),
  538.                             "averageRating" => $publicFunction->calculateRating($audioRdvs),
  539.                             "nbrReview" => count($audioRdvs),
  540.                             "motifs" => $resultMotif->toArray(),
  541.                             "specialities" => $resultSpeciality->toArray(),
  542.                             "centres" => array([
  543.                                 "id" => $centre->getId(),
  544.                                 "address" => $centre->getAddress(),
  545.                                 "postale" => $centre->getPostale(),
  546.                                 "city" => $centre->getCity(),
  547.                                 "finess" => $centre->getFiness(),
  548.                                 "siret" => $centre->getSiret(),
  549.                                 "website" => $centre->getWebsite(),
  550.                                 "phone" => $centre->getPhone(),
  551.                                 "latitude" => $centre->getLatitude(),
  552.                                 "longitude" => $centre->getLongitude(),
  553.                                 "schedule" => [
  554.                                     $publicFunction->calculSchedule($audio, new \DateTime(), $centre),
  555.                                     $publicFunction->calculSchedule($audio$date1->add(new DateInterval('P7D')), $centre),
  556.                                     $publicFunction->calculSchedule($audio$date2->add(new DateInterval('P14D')), $centre)
  557.                                 ],
  558.                                 "isLieu" => false
  559.                             ])
  560.                         ]);
  561.                         else array_push(
  562.                             $resultAudioMulti[$key]["centres"],
  563.                             [
  564.                                 "id" => $centre->getId(),
  565.                                 "address" => $centre->getAddress(),
  566.                                 "postale" => $centre->getPostale(),
  567.                                 "city" => $centre->getCity(),
  568.                                 "finess" => $centre->getFiness(),
  569.                                 "siret" => $centre->getSiret(),
  570.                                 "website" => $centre->getWebsite(),
  571.                                 "phone" => $centre->getPhone(),
  572.                                 "latitude" => $centre->getLatitude(),
  573.                                 "longitude" => $centre->getLongitude(),
  574.                                 "schedule" => [
  575.                                     $publicFunction->calculSchedule($audio, new \DateTime(), $centre),
  576.                                     $publicFunction->calculSchedule($audio$date->add(new DateInterval('P7D')), $centre),
  577.                                     $publicFunction->calculSchedule($audio$date->add(new DateInterval('P14D')), $centre)
  578.                                 ],
  579.                                 "isLieu" => false
  580.                             ]
  581.                         );
  582.                         continue;
  583.                     }
  584.                     //add audio in the result
  585.                     $date1 = new DateTime();
  586.                     $date2 = new DateTime();
  587.                     if ($centre->getHoraire() == null || $centre->getHoraire() == []) continue;
  588.                     $resultAudio->add([
  589.                         "id" => $audio->getId(),
  590.                         "civilite" => $audio->getCivilite(),
  591.                         "name" => $audio->getName(),
  592.                         "lastname" => $audio->getLastname(),
  593.                         "birthdate" => $audio->getBirthdate(),
  594.                         "mail" => $audio->getMail(),
  595.                         "phone" => $audio->getPhone(),
  596.                         "adeli" => $audio->getAdeli(),
  597.                         "pin" => $audio->getPin(),
  598.                         "description" => $audio->getDescription(),
  599.                         "imgUrl" => $audio->getImgUrl(),
  600.                         "averageRating" => $publicFunction->calculateRating($audioRdvs),
  601.                         "nbrReview" => count($audioRdvs),
  602.                         "motifs" => $resultMotif->toArray(),
  603.                         "specialities" => $resultSpeciality->toArray(),
  604.                         "schedule" => [
  605.                             $publicFunction->calculSchedule($audio, new \DateTime(), $centre),
  606.                             $publicFunction->calculSchedule($audio$date1->add(new DateInterval('P7D')), $centre),
  607.                             $publicFunction->calculSchedule($audio$date2->add(new DateInterval('P14D')), $centre)
  608.                         ],
  609.                     ]);
  610.                 }
  611.                 if (count($resultAudio) > 0)
  612.                     $result->add([
  613.                         "id" => $centre->getId(),
  614.                         "audio_id" => $centre->getIdGerant()->getId(),
  615.                         "name" => $centre->getName(),
  616.                         "slug" => $centre->getSlug(),
  617.                         "imgUrl" => $centre->getImgUrl(),
  618.                         "isRdvDomicile" => $centre->getIsRdvDomicile(),
  619.                         "address" => $centre->getAddress(),
  620.                         "postale" => $centre->getPostale(),
  621.                         "city" => $centre->getCity(),
  622.                         "finess" => $centre->getFiness(),
  623.                         "siret" => $centre->getSiret(),
  624.                         "website" => $centre->getWebsite(),
  625.                         "phone" => $centre->getPhone(),
  626.                         "isHandicap" => $centre->getIsHandicap(),
  627.                         "latitude" => $centre->getLatitude(),
  628.                         "longitude" => $centre->getLongitude(),
  629.                         "averageRating" => $publicFunction->calculateRating($centreRdvs),
  630.                         "nbrReview" => count($centreRdvs),
  631.                         "prestations" => $resultPrestation->toArray(),
  632.                         "audio" => $resultAudio->toArray(),
  633.                     ]);
  634.             }
  635.             if (count($result) > || count($resultAudioMulti) > 0)
  636.                 return new Response(json_encode([
  637.                     "content" => array_merge($result->toArray(), $resultAudioMulti),
  638.                     "centerImported" => $centerImportedArray,
  639.                     "totalPages" => $totalPages,
  640.                     "day" => strftime("%A"),
  641.                     "status" => 200,
  642.                 ]));
  643.             else
  644.                 return new Response(json_encode([
  645.                     "content" => [],
  646.                     "message" => "Aucun centre n'a été trouvé avec ces critères.",
  647.                     "centerImported" => $centerImportedArray,
  648.                     "totalPages" => $totalPages,
  649.                     "status" => 404,
  650.                 ]), 200);
  651.         } else {
  652.             return new Response(json_encode([
  653.                 "content" => [],
  654.                 "message" => "Aucun centre n'a été trouvé à cette adresse.",
  655.                 "status" => 404,
  656.             ]), 200);
  657.         }
  658.     }
  659.     /**
  660.      * @Route("/centres/client/{id}", name="getCentresByClient", methods={"GET","HEAD"})
  661.      */
  662.     public function getCentresByClient(Request $requestClient $clientPublicFunction $publicFunction): Response
  663.     {
  664.         /** @var ActivityRepository */
  665.         $activityRepo $this->getDoctrine();
  666.         if (!$request->query->get('token'))
  667.             return new Response(json_encode([
  668.                 "message" => "Pas de token n'a été spécifié",
  669.                 "status" => 401,
  670.             ]), 401);
  671.         $entityManager $this->getDoctrine()->getManager();
  672.         /** @var Token */
  673.         $token $this->getDoctrine()
  674.             ->getRepository(Token::class)
  675.             ->findOneBy(['token' => $request->query->get('token'), "id_client" => $client]);
  676.         if (!$token)
  677.             return new Response(json_encode([
  678.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  679.                 "status" => 404,
  680.             ]), 404);
  681.         // get token age
  682.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  683.         // if the token if older than 7 days
  684.         if ($dateDiff->7) {
  685.             $entityManager->remove($token);
  686.             $entityManager->flush();
  687.             return $this->json([
  688.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  689.                 'path' => 'src/Controller/ClientController.php',
  690.                 "status" => 401
  691.             ], 401);
  692.         }
  693.         $resultRdv = new ArrayCollection();
  694.         $resultNear = new ArrayCollection();
  695.         /** @var int[] */
  696.         $centresID $this->getDoctrine()->getRepository(Centre::class)
  697.             ->findByRdvTaken($client);
  698.         foreach ($centresID as $centreID) {
  699.             /** @var Centre[] */
  700.             $centres $this->getDoctrine()->getRepository(Centre::class)
  701.                 ->find($centreID);
  702.         }
  703.         foreach ($centres as $centre) {
  704.             /** @var Rdv[] */
  705.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  706.                 ->findAllReviewsCentre($centre->getId());
  707.             $resultRdv->add([
  708.                 "id" => $centre->getId(),
  709.                 "audio_id" => $centre->getIdGerant()->getId(),
  710.                 "name" => $centre->getName(),
  711.                 "imgUrl" => $centre->getImgUrl(),
  712.                 "isRdvDomicile" => $centre->getIsRdvDomicile(),
  713.                 "address" => $centre->getAddress(),
  714.                 "postale" => $centre->getPostale(),
  715.                 "city" => $centre->getCity(),
  716.                 "finess" => $centre->getFiness(),
  717.                 "siret" => $centre->getSiret(),
  718.                 "website" => $centre->getWebsite(),
  719.                 "phone" => $centre->getPhone(),
  720.                 "isHandicap" => $centre->getIsHandicap(),
  721.                 "longitude" => $centre->getLongitude(),
  722.                 "latitude" => $centre->getLatitude(),
  723.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  724.                 "nbrReview" => count($centreRdvs),
  725.             ]);
  726.         }
  727.         //if the user searched by coordinates
  728.         if ($request->query->get('longitude') && $request->query->get('latitude')) {
  729.             /** @var Centre[] */
  730.             $centresNear $this->getDoctrine()->getRepository(Centre::class)
  731.                 ->findByCoordonates($request->query->get('longitude'), $request->query->get('latitude'), $page$limit);
  732.             // checks if there is any result with the search
  733.             //gets through all centres given by the function
  734.             foreach ($centresNear as $centre) {
  735.                 /** @var Rdv[] */
  736.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  737.                     ->findAllReviewsCentre($centre->getId());
  738.                 $resultNear->add([
  739.                     "id" => $centre->getId(),
  740.                     "audio_id" => $centre->getIdGerant()->getId(),
  741.                     "name" => $centre->getName(),
  742.                     "imgUrl" => $centre->getImgUrl(),
  743.                     "isRdvDomicile" => $centre->getIsRdvDomicile(),
  744.                     "address" => $centre->getAddress(),
  745.                     "postale" => $centre->getPostale(),
  746.                     "city" => $centre->getCity(),
  747.                     "finess" => $centre->getFiness(),
  748.                     "siret" => $centre->getSiret(),
  749.                     "website" => $centre->getWebsite(),
  750.                     "phone" => $centre->getPhone(),
  751.                     "isHandicap" => $centre->getIsHandicap(),
  752.                     "longitude" => $centre->getLongitude(),
  753.                     "latitude" => $centre->getLatitude(),
  754.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  755.                     "nbrReview" => count($centreRdvs),
  756.                 ]);
  757.             }
  758.         }
  759.         if ((count($resultNear) > 0) || (count($resultRdv) > 0)) {
  760.             return new Response(json_encode([
  761.                 "resultNear" => $resultNear->toArray(),
  762.                 "resultRdv" => $resultRdv->toArray(),
  763.                 "status" => 200,
  764.             ]));
  765.         } else {
  766.             return new Response(json_encode([
  767.                 "message" => "Aucun centre n'a été trouvé.",
  768.                 "status" => 404,
  769.             ]), 404);
  770.         }
  771.     }
  772.     /**
  773.      * @Route("/centre/image/{id}", name="getCentreImage", methods={"GET"})
  774.      */
  775.     public function getCentreImage(Centre $centrePublicFunction $publicFunction): Response
  776.     {
  777.         if (!$centre->getImgUrl()) {
  778.             return $publicFunction->replyWithFile('images/centre/'"imgOreille.png");
  779.         }
  780.         return $publicFunction->replyWithFile('images/centre/'$centre->getImgUrl());
  781.     }
  782.     /**
  783.      * @Route("/centre/document/finess/{id}", name="getCentreFinessDocument", methods={"GET"})
  784.      */
  785.     public function getCentreFinessDocument(Centre $centrePublicFunction $publicFunction): Response
  786.     {
  787.         if (!$centre->getFinessUrl()) {
  788.             return $publicFunction->replyWithFile('images/centre/'"imgOreille.png");
  789.         }
  790.         return $publicFunction->replyWithFile('document/centre/finess/'$centre->getFinessUrl());
  791.     }
  792.     /**
  793.      * @Route("/centre/{id}/audios/", name="getAudiosByCentreId", methods={"GET"})
  794.      */
  795.     public function getAudiosByCentreId(Centre $centre): Response
  796.     {
  797.         $audios $this->getDoctrine()
  798.             ->getRepository(AudioCentre::class)
  799.             ->findBy(array('id_centre' => $centre));
  800.         $resultatAudios = new ArrayCollection();
  801.         foreach ($audios as $audio) {
  802.             $resultatAudios->add([
  803.                 "id" => $audio->getIdAudio()->getId(),
  804.                 "nom" => $audio->getIdAudio()->getLastName(),
  805.                 "prenom" => $audio->getIdAudio()->getName()
  806.             ]);
  807.         }
  808.         return $this->json([
  809.             "audios" => $resultatAudios->toArray(),
  810.         ]);
  811.     }
  812.     /**
  813.      * @Route("/centre/horaire/{id}", name="getCentreHoraire", methods={"GET"})
  814.      */
  815.     public function getCentreHoraire(Centre $centrePublicFunction $publicFunction): Response
  816.     {
  817.         return new Response(json_encode($centre->getHoraire()));
  818.     }
  819.     /**
  820.      * @Route("/centre/holiday-horaire/{id}", name="getCentreHolidayHoraire", methods={"GET"})
  821.      */
  822.     public function getCentreHolidayHoraire(Centre $centrePublicFunction $publicFunction): Response
  823.     {
  824.         return new Response(json_encode($centre->getHorairesHoliday()));
  825.     }
  826.     /**
  827.      * @Route("/centre/horaire/{id}", name="setCentreHoraire", methods={"PUT"})
  828.      */
  829.     public function setCentreHoraire(Centre $centrePublicFunction $publicFunctionRequest $request)
  830.     {
  831.         if (!$request->query->get('token')) {
  832.             return new Response(json_encode([
  833.                 "message" => "Pas de token n'a été spécifié",
  834.                 "status" => 401,
  835.             ]), 401);
  836.         }
  837.         $entityManager $this->getDoctrine()->getManager();
  838.         /** @var Token */
  839.         $token $this->getDoctrine()
  840.             ->getRepository(Token::class)
  841.             ->findOneBy(['token' => $request->query->get('token'), 'id_audio' => $request->query->get('audio')]);
  842.         if (!$token) {
  843.             return new Response(json_encode([
  844.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  845.                 "status" => 404,
  846.             ]), 404);
  847.         }
  848.         // get token age
  849.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  850.         // if the token if older than 7 days
  851.         if ($dateDiff->7) {
  852.             $entityManager->remove($token);
  853.             $entityManager->flush();
  854.             return $this->json([
  855.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  856.                 'path' => 'src/Controller/AudioController.php',
  857.                 "status" => 401,
  858.             ], 401);
  859.         }
  860.         $entityManager $this->getDoctrine()->getManager();
  861.         $data json_decode($request->getContent(), true);
  862.         $days = ["lundi""mardi""mercredi""jeudi""vendredi""samedi""dimanche"];
  863.         // Extract center IDs from the "fixed" section
  864.         if (isset($data['horaires']['fixed'])) {
  865.             foreach ($data['horaires']['fixed'] as $dayData) {
  866.                 foreach ($dayData as $timeData) {
  867.                     $centerIds[] = $timeData['centerId'];
  868.                 }
  869.             }
  870.         }
  871.         // Extract color from the "fixed" section
  872.         if (isset($data['horaires']['fixed'])) {
  873.             foreach ($data['horaires']['fixed'] as $dayData) {
  874.                 foreach ($dayData as $timeData) {
  875.                     $centerColors[] = $timeData['centerColor'];
  876.                 }
  877.             }
  878.         }
  879.         //dd($centerIds);
  880.         if (isset($centerIds)) {
  881.             // Remove duplicate center IDs and convert to array
  882.             $centerIds array_values(array_unique($centerIds));
  883.             // Remove duplicate center IDs and convert to array
  884.             $centerColors array_values(array_unique($centerColors));
  885.             // dd( $centerColors);
  886.             // Use $centerIds for further processing
  887.             // Step 1: Clear empty days
  888.             $myCenters $this->getDoctrine()
  889.                 ->getRepository(Centre::class)->findBy(['id_gerant' => $request->query->get('audio')]);
  890.             // dd( $audioCentre);
  891.             $centerIds array_values(array_unique($centerIds));
  892.             //dd($centerIds);
  893.             // Fetch the centers based on id_gerant
  894.             $myCenters $this->getDoctrine()
  895.                 ->getRepository(Centre::class)
  896.                 ->findBy(['id' => $centre]);
  897.             //dd($myCenters);
  898.             // Create an array of center IDs from $myCenters
  899.             $myCenterIds = [];
  900.             foreach ($myCenters as $myCenter) {
  901.                 $myCenterIds[] = $myCenter->getId();
  902.             }
  903.             //dd($myCenterIds);
  904.             // Check for unexisting centers between $centerIds and $myCenterIds
  905.             $unexistingCenters array_diff($myCenterIds$centerIds);
  906.             //dd($unexistingCenters);
  907.             foreach ($unexistingCenters as $centerId) {
  908.                 // Create a new instance of Centre and set its properties
  909.                 $center $this->getDoctrine()
  910.                     ->getRepository(Centre::class)
  911.                     ->find($centerId);
  912.                 $centerAudio $this->getDoctrine()
  913.                     ->getRepository(AudioCentre::class)
  914.                     ->findOneBy(['id_centre' => $centerId]);
  915.                 $horaireArray = [
  916.                     'fixed' => [
  917.                         'lundi' => [],
  918.                         'mardi' => [],
  919.                         'mercredi' => [],
  920.                         'jeudi' => [],
  921.                         'vendredi' => [],
  922.                         'samedi' => [],
  923.                         'dimanche' => [],
  924.                     ],
  925.                     'exceptionalOpened' => [],
  926.                     'exceptionalClosed' => [],
  927.                 ];
  928.                 if ($center) {
  929.                     $center->setHoraire($horaireArray);
  930.                     $entityManager->persist($center);
  931.                 }
  932.                 if ($centerAudio) {
  933.                     $centerAudio->setHoraire($horaireArray);
  934.                     $entityManager->persist($centerAudio);
  935.                 }
  936.                 $entityManager->flush();
  937.             }
  938.             $results = [];
  939.             foreach ($centerIds as $key => $centerId) {
  940.                 // Step 1: Clear empty days
  941.                 $clearedData = ["fixed" => [], "exceptionalOpened" => [], "exceptionalClosed" => []];
  942.                 foreach ($days as $day) {
  943.                     if (isset($data['horaires']['fixed'][$day])) {
  944.                         $clearedData['fixed'][$day] = $data['horaires']['fixed'][$day];
  945.                     } else {
  946.                         $clearedData['fixed'][$day] = [];
  947.                     }
  948.                 }
  949.                 $clearedData['exceptionalOpened'] = $data['horaires']['exceptionalOpened'];
  950.                 $clearedData['exceptionalClosed'] = $data['horaires']['exceptionalClosed'];
  951.                 // Step 2: Find the center by centerId
  952.                 $centerData = [];
  953.                 $centreExist false;
  954.                 foreach ($days as $day) {
  955.                     $centerData[$day] = [];
  956.                     if (isset($clearedData['fixed'][$day])) {
  957.                         foreach ($clearedData['fixed'][$day] as $timeData) {
  958.                             if ($timeData['centerId'] == $centerId) {
  959.                                 $centerData[$day][] = [
  960.                                     'open' => $timeData['open'],
  961.                                     'close' => $timeData['close']
  962.                                 ];
  963.                                 $centreExist true;
  964.                             }
  965.                         }
  966.                     }
  967.                 }
  968.                 $center $this->getDoctrine()
  969.                     ->getRepository(Centre::class)
  970.                     ->find($centerId);
  971.                 $centerAudio $this->getDoctrine()
  972.                     ->getRepository(AudioCentre::class)
  973.                     ->findOneBy(['id_centre' => $centerId]);
  974.                 $result = [
  975.                     'fixed' => $centerData,
  976.                     'exceptionalOpened' => $clearedData['exceptionalOpened'],
  977.                     'exceptionalClosed' => $clearedData['exceptionalClosed']
  978.                 ];
  979.                 $center->setHoraire($result); // Use $result instead of $results
  980.                 $centerAudio->setHoraire($result); // Use $result instead of $results
  981.                 $center->setCalendarColor($centerColors[$key]); // Use $result instead of $results
  982.                 $entityManager->persist($center);
  983.                 $entityManager->persist($centerAudio);
  984.                 $entityManager->flush();
  985.                 $results[$centerId] = $result;
  986.             }
  987.             $resultsJson json_encode($results);
  988.         } else {
  989.             $myCenters $this->getDoctrine()
  990.                 ->getRepository(Centre::class)
  991.                 ->findBy(['id_gerant' => $request->query->get('audio')]);
  992.             foreach ($myCenters as $centerId) {
  993.                 // Create a new instance of Centre and set its properties
  994.                 $center $this->getDoctrine()
  995.                     ->getRepository(Centre::class)
  996.                     ->find($centerId);
  997.                 $centerAudio $this->getDoctrine()
  998.                     ->getRepository(AudioCentre::class)
  999.                     ->findOneBy(['id_centre' => $centerId]);
  1000.                 $horaireArray = [
  1001.                     'fixed' => [
  1002.                         'lundi' => [],
  1003.                         'mardi' => [],
  1004.                         'mercredi' => [],
  1005.                         'jeudi' => [],
  1006.                         'vendredi' => [],
  1007.                         'samedi' => [],
  1008.                         'dimanche' => [],
  1009.                     ],
  1010.                     'exceptionalOpened' => [],
  1011.                     'exceptionalClosed' => [],
  1012.                 ];
  1013.                 $center->setHoraire($horaireArray);
  1014.                 $centerAudio->setHoraire($horaireArray);
  1015.                 // Persist the center
  1016.                 $entityManager->persist($center);
  1017.                 $entityManager->persist($centerAudio);
  1018.                 $entityManager->flush();
  1019.             }
  1020.         }
  1021.         // dd($results);
  1022.         //  $centre->setHoraire($data["horaires"]);
  1023.         // $entityManager->flush();
  1024.         return $this->json([
  1025.             "id" => $centre->getId(),
  1026.             "horaires" => $data["horaires"]
  1027.         ]);
  1028.     }
  1029.     /**
  1030.      * @Route("/centre/horaire-holiday/{id}", name="setCentreHoraireHoliday", methods={"PUT"})
  1031.      */
  1032.     public function setCentreHoraireHoliday(Centre $centrePublicFunction $publicFunctionRequest $request)
  1033.     {
  1034.         if (!$request->query->get('token')) {
  1035.             return new Response(json_encode([
  1036.                 "message" => "Pas de token n'a été spécifié",
  1037.                 "status" => 401,
  1038.             ]), 401);
  1039.         }
  1040.         $entityManager $this->getDoctrine()->getManager();
  1041.         /** @var Token */
  1042.         $token $this->getDoctrine()
  1043.             ->getRepository(Token::class)
  1044.             ->findOneBy(['token' => $request->query->get('token'), 'id_audio' => $request->query->get('audio')]);
  1045.         if (!$token) {
  1046.             return new Response(json_encode([
  1047.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1048.                 "status" => 404,
  1049.             ]), 404);
  1050.         }
  1051.         // get token age
  1052.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1053.         // if the token if older than 7 days
  1054.         if ($dateDiff->7) {
  1055.             $entityManager->remove($token);
  1056.             $entityManager->flush();
  1057.             return $this->json([
  1058.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1059.                 'path' => 'src/Controller/AudioController.php',
  1060.                 "status" => 401,
  1061.             ], 401);
  1062.         }
  1063.         $entityManager $this->getDoctrine()->getManager();
  1064.         $data json_decode($request->getContent(), true);
  1065.         //dd($data);
  1066.         //$days = ["lundi", "mardi", "mercredi", "jeudi", "vendredi", "samedi", "dimanche"];
  1067.         $days = ["JourdelAn""LundidePâques""FêteduTravail""Victoire1945""Ascension""LundidePentecôte""FêteNationale""Assomption""Toussaint""Armistice1918""Noël"];
  1068.         //dd($data);
  1069.         // Extract center IDs from the "fixed" section
  1070.         if (isset($data['horaires']['fixed'])) {
  1071.             foreach ($data['horaires']['fixed'] as $dayData) {
  1072.                 foreach ($dayData as $timeData) {
  1073.                     $centerIds[] = $timeData['centerId'];
  1074.                 }
  1075.             }
  1076.         }
  1077.         // Extract color from the "fixed" section
  1078.         if (isset($data['horaires']['fixed'])) {
  1079.             foreach ($data['horaires']['fixed'] as $dayData) {
  1080.                 foreach ($dayData as $timeData) {
  1081.                     $centerColors[] = $timeData['centerColor'];
  1082.                 }
  1083.             }
  1084.         }
  1085.         //dd($centerIds);
  1086.         if (isset($centerIds)) {
  1087.             // Remove duplicate center IDs and convert to array
  1088.             $centerIds array_values(array_unique($centerIds));
  1089.             // Remove duplicate center IDs and convert to array
  1090.             $centerColors array_values(array_unique($centerColors));
  1091.             // dd( $centerColors);
  1092.             // Use $centerIds for further processing
  1093.             // Step 1: Clear empty days
  1094.             $myCenters $this->getDoctrine()
  1095.                 ->getRepository(Centre::class)->findBy(['id_gerant' => $request->query->get('audio')]);
  1096.             // dd( $audioCentre);
  1097.             $centerIds array_values(array_unique($centerIds));
  1098.             //dd($centerIds);
  1099.             // Fetch the centers based on id_gerant
  1100.             $myCenters $this->getDoctrine()
  1101.                 ->getRepository(Centre::class)
  1102.                 ->findBy(['id_gerant' => $request->query->get('audio')]);
  1103.             //dd($myCenters);
  1104.             // Create an array of center IDs from $myCenters
  1105.             $myCenterIds = [];
  1106.             foreach ($myCenters as $myCenter) {
  1107.                 $myCenterIds[] = $myCenter->getId();
  1108.             }
  1109.             //dd($myCenterIds);
  1110.             // Check for unexisting centers between $centerIds and $myCenterIds
  1111.             $unexistingCenters array_diff($myCenterIds$centerIds);
  1112.             //dd($unexistingCenters);
  1113.             foreach ($unexistingCenters as $centerId) {
  1114.                 // Create a new instance of Centre and set its properties
  1115.                 $center $this->getDoctrine()
  1116.                     ->getRepository(Centre::class)
  1117.                     ->find($centerId);
  1118.                 $centerAudio $this->getDoctrine()
  1119.                     ->getRepository(AudioCentre::class)
  1120.                     ->findOneBy(['id_centre' => $centerId]);
  1121.                 $horaireArray = [
  1122.                     'fixed' => [
  1123.                         'JourdelAn' => [],
  1124.                         'LundidePâques' => [],
  1125.                         'FêteduTravail' => [],
  1126.                         'Victoire1945' => [],
  1127.                         'Ascension' => [],
  1128.                         'LundidePentecôte' => [],
  1129.                         'FêteNationale' => [],
  1130.                         'Assomption' => [],
  1131.                         'Toussaint' => [],
  1132.                         'Armistice1918' => [],
  1133.                         'Noël' => [],
  1134.                     ],
  1135.                     'exceptionalOpened' => [],
  1136.                     'exceptionalClosed' => [],
  1137.                 ];
  1138.                 if ($center) {
  1139.                     $center->setHorairesHoliday($horaireArray);
  1140.                     $entityManager->persist($center);
  1141.                 }
  1142.                 if ($centerAudio) {
  1143.                     $centerAudio->setHorairesHoliday($horaireArray);
  1144.                     $entityManager->persist($centerAudio);
  1145.                 }
  1146.             }
  1147.             $results = [];
  1148.             foreach ($centerIds as $key => $centerId) {
  1149.                 // Step 1: Clear empty days
  1150.                 $clearedData = ["fixed" => [], "exceptionalOpened" => [], "exceptionalClosed" => []];
  1151.                 foreach ($days as $day) {
  1152.                     if (isset($data['horaires']['fixed'][$day])) {
  1153.                         $clearedData['fixed'][$day] = $data['horaires']['fixed'][$day];
  1154.                     } else {
  1155.                         $clearedData['fixed'][$day] = [];
  1156.                     }
  1157.                 }
  1158.                 $clearedData['exceptionalOpened'] = $data['horaires']['exceptionalOpened'];
  1159.                 $clearedData['exceptionalClosed'] = $data['horaires']['exceptionalClosed'];
  1160.                 // Step 2: Find the center by centerId
  1161.                 $centerData = [];
  1162.                 $centreExist false;
  1163.                 foreach ($days as $day) {
  1164.                     $centerData[$day] = [];
  1165.                     if (isset($clearedData['fixed'][$day])) {
  1166.                         foreach ($clearedData['fixed'][$day] as $timeData) {
  1167.                             if ($timeData['centerId'] == $centerId) {
  1168.                                 $centerData[$day][] = [
  1169.                                     'open' => $timeData['open'],
  1170.                                     'close' => $timeData['close']
  1171.                                 ];
  1172.                                 $centreExist true;
  1173.                             }
  1174.                         }
  1175.                     }
  1176.                 }
  1177.                 $center $this->getDoctrine()
  1178.                     ->getRepository(Centre::class)
  1179.                     ->find($centerId);
  1180.                 $centerAudio $this->getDoctrine()
  1181.                     ->getRepository(AudioCentre::class)
  1182.                     ->findOneBy(['id_centre' => $centerId]);
  1183.                 $result = [
  1184.                     'fixed' => $centerData,
  1185.                     'exceptionalOpened' => $clearedData['exceptionalOpened'],
  1186.                     'exceptionalClosed' => $clearedData['exceptionalClosed']
  1187.                 ];
  1188.                 //dd($result);
  1189.                 $center->setHorairesHoliday($result); // Use $result instead of $results
  1190.                 $centerAudio->setHorairesHoliday($result); // Use $result instead of $results
  1191.                 $center->setCalendarColor($centerColors[$key]); // Use $result instead of $results
  1192.                 $entityManager->persist($center);
  1193.                 $entityManager->persist($centerAudio);
  1194.                 $entityManager->flush();
  1195.                 $results[$centerId] = $result;
  1196.             }
  1197.             $resultsJson json_encode($results);
  1198.         } else {
  1199.             $myCenters $this->getDoctrine()
  1200.                 ->getRepository(Centre::class)
  1201.                 ->findBy(['id_gerant' => $request->query->get('audio')]);
  1202.             foreach ($myCenters as $centerId) {
  1203.                 // Create a new instance of Centre and set its properties
  1204.                 $center $this->getDoctrine()
  1205.                     ->getRepository(Centre::class)
  1206.                     ->find($centerId);
  1207.                 $centerAudio $this->getDoctrine()
  1208.                     ->getRepository(AudioCentre::class)
  1209.                     ->findOneBy(['id_centre' => $centerId]);
  1210.                 $horaireArray = [
  1211.                     'fixed' => [
  1212.                         'JourdelAn' => [],
  1213.                         'LundidePâques' => [],
  1214.                         'FêteduTravail' => [],
  1215.                         'Victoire1945' => [],
  1216.                         'Ascension' => [],
  1217.                         'LundidePentecôte' => [],
  1218.                         'FêteNationale' => [],
  1219.                         'Assomption' => [],
  1220.                         'Toussaint' => [],
  1221.                         'Armistice1918' => [],
  1222.                         'Noël' => [],
  1223.                     ],
  1224.                     'exceptionalOpened' => [],
  1225.                     'exceptionalClosed' => [],
  1226.                 ];
  1227.                 $center->setHorairesHoliday($horaireArray);
  1228.                 $centerAudio->setHorairesHoliday($horaireArray);
  1229.                 // Persist the center
  1230.                 $entityManager->persist($center);
  1231.                 $entityManager->persist($centerAudio);
  1232.                 $entityManager->flush();
  1233.             }
  1234.         }
  1235.         // dd($results);
  1236.         //  $centre->setHoraire($data["horaires"]);
  1237.         // $entityManager->flush();
  1238.         return $this->json([
  1239.             "id" => $centre->getId(),
  1240.             "horaires" => $data["horaires"]
  1241.         ]);
  1242.     }
  1243.     /**
  1244.      * @Route("/centre/image", name="getNewCentreImage", methods={"GET"})
  1245.      */
  1246.     public function getNewCentreImage(PublicFunction $publicFunctionRequest $request): Response
  1247.     {
  1248.         return $publicFunction->replyWithFile('images/centre/'$request->query->get('imgUrl'));
  1249.     }
  1250.     /**
  1251.      * @Route("/centre/{id}", name="getCentre", methods={"GET","HEAD"})
  1252.      */
  1253.     public function getCentre(Centre $centrePublicFunction $publicFunction): Response
  1254.     {
  1255.         /** @var CentrePrestation[]*/
  1256.         $prestations $this->getDoctrine()->getRepository(CentrePrestation::class)
  1257.             ->findBy(array('id_centre' => $centre->getId()));
  1258.         $resultPrestation = new ArrayCollection();
  1259.         foreach ($prestations as $prestation) {
  1260.             $resultPrestation->add([
  1261.                 "id" => $prestation->getIdPrestation()->getId(),
  1262.                 "titre" => $prestation->getIdPrestation()->getLibelle(),
  1263.             ]);
  1264.         }
  1265.         /** @var CentreMutuelle[]*/
  1266.         $mutuelles $this->getDoctrine()->getRepository(CentreMutuelle::class)
  1267.             ->findBy(array('id_centre' => $centre->getId()));
  1268.         $resultMutuelle = new ArrayCollection();
  1269.         foreach ($mutuelles as $mutuelle) {
  1270.             $resultMutuelle->add([
  1271.                 "id" => $mutuelle->getIdMutuelle()->getId(),
  1272.                 "titre" => $mutuelle->getIdMutuelle()->getLibelle(),
  1273.             ]);
  1274.         }
  1275.         /** @var CentreTier[]*/
  1276.         $tiers $this->getDoctrine()->getRepository(CentreTier::class)
  1277.             ->findBy(array('id_centre' => $centre->getId()));
  1278.         $resultTier = new ArrayCollection();
  1279.         foreach ($tiers as $tier) {
  1280.             $resultTier->add([
  1281.                 "id" => $tier->getIdTier()->getId(),
  1282.                 "titre" => $tier->getIdTier()->getLibelle(),
  1283.             ]);
  1284.         }
  1285.         /** @var AudioCentre[] */
  1286.         $liaisons $this->getDoctrine()->getRepository(AudioCentre::class)
  1287.             ->findBy(array('id_centre' => $centre'isConfirmed' => true));
  1288.         $resultAudio = new ArrayCollection();
  1289.         foreach ($liaisons as $liaison) {
  1290.             /** @var Audio */
  1291.             $audio $this->getDoctrine()->getRepository(Audio::class)
  1292.                 ->findOneBy(array('id' => $liaison->getIdAudio()));
  1293.             // Motifs
  1294.             /** @var AudioMotif[] */
  1295.             $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  1296.                 ->findBy(array('id_audio' => $liaison->getIdAudio()));
  1297.             // will test whether or not the audio has the necessery motif to be added
  1298.             $resultMotif = new ArrayCollection();
  1299.             foreach ($motifs as $motif) {
  1300.                 // ignore deleted motif
  1301.                 if (!$motif->getIsDeleted() && $motif->getType() !== 2)
  1302.                     $resultMotif->add([
  1303.                         "id" => $motif->getIdMotif()->getId(),
  1304.                         "titre" => $motif->getIdMotif()->getTitre(),
  1305.                         "consigne" => $motif->getConsigne(),
  1306.                         "duration" => $motif->getDuration(),
  1307.                     ]);
  1308.             }
  1309.             // Specialities
  1310.             /** @var AudioSpecialite[] */
  1311.             $specialities $this->getDoctrine()->getRepository(AudioSpecialite::class)
  1312.                 ->findBy(array('id_audio' => $liaison->getIdAudio()));
  1313.             //speciality filter
  1314.             $resultSpeciality = new ArrayCollection();
  1315.             foreach ($specialities as $speciality) {
  1316.                 if ($speciality->getIdSpecialite() !== null) {
  1317.                     $resultSpeciality->add([
  1318.                         "id" => $speciality->getIdSpecialite()->getId(),
  1319.                         "titre" => $speciality->getIdSpecialite()->getLibelle(),
  1320.                     ]);
  1321.                 }
  1322.             }
  1323.             //schedule
  1324.             $date = new DateTime();
  1325.             //add audio in the result 
  1326.             if ($centre->getHoraire() == null || $centre->getHoraire() == []) continue;
  1327.             /** @var Rdv[] */
  1328.             $audioRdvs $this->getDoctrine()->getRepository(Rdv::class)
  1329.                 ->findAllReviewsAudio($audio->getId());
  1330.             $resultAudio->add([
  1331.                 "id" => $audio->getId(),
  1332.                 "civilite" => $audio->getCivilite(),
  1333.                 "name" => $audio->getName(),
  1334.                 "lastname" => $audio->getLastname(),
  1335.                 "birthdate" => $audio->getBirthdate(),
  1336.                 "mail" => $audio->getMail(),
  1337.                 "phone" => $audio->getPhone(),
  1338.                 "adeli" => $audio->getAdeli(),
  1339.                 "pin" => $audio->getPin(),
  1340.                 "description" => $audio->getDescription(),
  1341.                 "imgUrl" => $audio->getImgUrl(),
  1342.                 "averageRating" => $publicFunction->calculateRating($audioRdvs),
  1343.                 "nbrReview" => count($audioRdvs),
  1344.                 "motifs" => $resultMotif->toArray(),
  1345.                 "specialities" => $resultSpeciality->toArray(),
  1346.                 "schedule" => [
  1347.                     $publicFunction->calculSchedule($audio, new \DateTime(), $centre),
  1348.                     $publicFunction->calculSchedule($audio$date->add(new DateInterval('P7D')), $centre),
  1349.                     $publicFunction->calculSchedule($audio$date->add(new DateInterval('P14D')), $centre)
  1350.                 ],
  1351.             ]);
  1352.         }
  1353.         /** @var AccessCentre*/
  1354.         $accessCentre $this->getDoctrine()->getRepository(AccessCentre::class)
  1355.             ->findOneBy(array('id_centre' => $centre->getId()));
  1356.         if (!$accessCentre)
  1357.             return new Response(json_encode([
  1358.                 'message' => 'Error, no accessCentre found at this id',
  1359.                 'path' => 'src/Controller/CentreController.php',
  1360.             ]), 404);
  1361.         $metroIDs json_decode($accessCentre->getMetro(), true);
  1362.         $metroNames = array();
  1363.         if ($metroIDs) {
  1364.             foreach ($metroIDs as $key => $stationID) {
  1365.                 $station $this->getDoctrine()->getRepository(Station::class)->find($stationID);
  1366.                 if ($station) {
  1367.                     $metroNames[$key] = $station->getName();
  1368.                 } else {
  1369.                     $metroNames[$key] = "Station Not Found";
  1370.                 }
  1371.             }
  1372.         }
  1373.         /** @var Rdv[] */
  1374.         $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  1375.             ->findAllReviewsCentre($centre->getId());
  1376.         // Comment
  1377.         /** @var Rdv[] */
  1378.         $rdvs $this->getDoctrine()->getRepository(Rdv::class)
  1379.             ->findBy(array('id_centre' => $centre));
  1380.         $comments = [];
  1381.         foreach ($rdvs as $rdv)
  1382.             if ($rdv->getComment() && $rdv->getReview() && $rdv->getIdClient())
  1383.                 array_push($comments, [
  1384.                     "id" => $rdv->getIdClient()->getId(),
  1385.                     "name" => $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname()[0] . ".",
  1386.                     "comment" => $rdv->getComment(),
  1387.                     "isMale" => $rdv->getIdClient()->getCivilite() == "Monsieur",
  1388.                     "review" => $rdv->getReview(),
  1389.                 ]);
  1390.         return new Response(json_encode([
  1391.             "id" => $centre->getId(),
  1392.             "audio_id" => $centre->getIdGerant()->getId(),
  1393.             "name" => $centre->getName(),
  1394.             "imgUrl" => $centre->getImgUrl(),
  1395.             "isRdvDomicile" => $centre->getIsRdvDomicile(),
  1396.             "address" => $centre->getAddress(),
  1397.             "numero" => $centre->getNumero(),
  1398.             "voie" => $centre->getVoie(),
  1399.             "rue" => $centre->getRue(),
  1400.             "description" => $centre->getDescription(),
  1401.             "postale" => $centre->getPostale(),
  1402.             "city" => $centre->getCity(),
  1403.             "finess" => $centre->getFiness(),
  1404.             "siret" => $centre->getSiret(),
  1405.             "website" => $centre->getWebsite(),
  1406.             "phone" => $centre->getPhone(),
  1407.             "isHandicap" => $centre->getIsHandicap(),
  1408.             "longitude" => $centre->getLongitude(),
  1409.             "latitude" => $centre->getLatitude(),
  1410.             "averageRating" => $publicFunction->calculateRating($centreRdvs),
  1411.             "nbrReview" => count($centreRdvs),
  1412.             "tram" => $accessCentre->getTram(),
  1413.             "rer" => $accessCentre->getRer(),
  1414.             "metro" => $metroNames,
  1415.             "bus" => $accessCentre->getBus(),
  1416.             "parking" => $accessCentre->getParkingPublic(),
  1417.             "parkingPrivate" => $accessCentre->getParkingPrivate(),
  1418.             "other" => $accessCentre->getOther(),
  1419.             "comments" => $comments,
  1420.             "mutuelles" => $resultMutuelle->toArray(),
  1421.             "prestations" => $resultPrestation->toArray(),
  1422.             "tiers" => $resultTier->toArray(),
  1423.             "audio" => $resultAudio->toArray(),
  1424.             "schedule" => $centre->getHoraire(),
  1425.             "status" => 200,
  1426.         ]));
  1427.     }
  1428.     /**
  1429.      * @Route("/centre-slug/{slug}", name="getCentreBySlug", methods={"GET","HEAD"})
  1430.      */
  1431.     public function getCentreBySlug(string $slugPublicFunction $publicFunctionRequest $request): Response
  1432.     {
  1433.         $centre $this->getDoctrine()->getRepository(Centre::class)
  1434.             ->findOneBy(array('slug' => $slug));
  1435.         if (!$centre) {
  1436.             $postale $request->query->get('postale');
  1437.             $centre $this->getDoctrine()->getRepository(CenterImported::class)
  1438.                 ->findOneBy(['slug' => $slug'codePostal' => $postale]);
  1439.             /*$repository = $this->getDoctrine()->getRepository(CenterImported::class);
  1440.      
  1441.             $slugify = $this->slugger->slug($slug)->lower();
  1442.             //dd($)
  1443.             $centre = $repository->findOneBySlug(str_replace('-', ' ', $slugify));*/
  1444.             // dd($centre);
  1445.             return new Response(json_encode([
  1446.                 "id" => $centre->getId(),
  1447.                 //"audio_id" => $centre->getIdGerant()->getId(),
  1448.                 "name" => $centre->getNom(),
  1449.                 //"imgUrl" => $centre->getImgUrl(),
  1450.                 //"isRdvDomicile" => $centre->getIsRdvDomicile(),
  1451.                 "address" => $centre->getAdresse(),
  1452.                 //"numero" => $centre->getNumero(),
  1453.                 //"voie" => $centre->getVoie(),
  1454.                 //"rue" => $centre->getRue(),
  1455.                 //"description" => $centre->getDescription(),
  1456.                 "postale" => $centre->getCodePostal(),
  1457.                 "city" => $centre->getVille(),
  1458.                 "siret" => $centre->getSiret(),
  1459.                 "phone" => $centre->getTelephone(),
  1460.                 //"isHandicap" => $centre->getIsHandicap(),
  1461.                 "longitude" => $centre->getLongitude(),
  1462.                 "latitude" => $centre->getLatitude(),
  1463.                 //"averageRating" => $publicFunction->calculateRating($centreRdvs),
  1464.                 //"nbrReview" => count($centreRdvs),
  1465.                 //"tram" => $accessCentre->getTram(),
  1466.                 //"rer" => $accessCentre->getRer(),
  1467.                 //"metro" => $metroNames,
  1468.                 //"bus" => $accessCentre->getBus(),
  1469.                 //"parking" => $accessCentre->getParkingPublic(),
  1470.                 //"parkingPrivate" => $accessCentre->getParkingPrivate(),
  1471.                 //"other" => $accessCentre->getOther(),
  1472.                 //"comments" => $comments,
  1473.                 //"mutuelles" => $resultMutuelle->toArray(),
  1474.                 //"prestations" => $resultPrestation->toArray(),
  1475.                 //"tiers" => $resultTier->toArray(),
  1476.                 //"audio" => $resultAudio->toArray(),
  1477.                 //"schedule" => $centre->getHoraire(),
  1478.                 "status" => 200,
  1479.             ]));
  1480.         }
  1481.         /** @var CentrePrestation[]*/
  1482.         $prestations $this->getDoctrine()->getRepository(CentrePrestation::class)
  1483.             ->findBy(array('id_centre' => $centre->getId()));
  1484.         $resultPrestation = new ArrayCollection();
  1485.         foreach ($prestations as $prestation) {
  1486.             $resultPrestation->add([
  1487.                 "id" => $prestation->getIdPrestation()->getId(),
  1488.                 "titre" => $prestation->getIdPrestation()->getLibelle(),
  1489.             ]);
  1490.         }
  1491.         /** @var CentreMutuelle[]*/
  1492.         $mutuelles $this->getDoctrine()->getRepository(CentreMutuelle::class)
  1493.             ->findBy(array('id_centre' => $centre->getId()));
  1494.         $resultMutuelle = new ArrayCollection();
  1495.         foreach ($mutuelles as $mutuelle) {
  1496.             $resultMutuelle->add([
  1497.                 "id" => $mutuelle->getIdMutuelle()->getId(),
  1498.                 "titre" => $mutuelle->getIdMutuelle()->getLibelle(),
  1499.             ]);
  1500.         }
  1501.         /** @var CentreTier[]*/
  1502.         $tiers $this->getDoctrine()->getRepository(CentreTier::class)
  1503.             ->findBy(array('id_centre' => $centre->getId()));
  1504.         $resultTier = new ArrayCollection();
  1505.         foreach ($tiers as $tier) {
  1506.             $resultTier->add([
  1507.                 "id" => $tier->getIdTier()->getId(),
  1508.                 "titre" => $tier->getIdTier()->getLibelle(),
  1509.             ]);
  1510.         }
  1511.         $resultDiplome = new ArrayCollection();
  1512.         $resultExperience = new ArrayCollection();
  1513.         /** @var AudioCentre[] */
  1514.         $liaisons $this->getDoctrine()->getRepository(AudioCentre::class)
  1515.             ->findBy(array('id_centre' => $centre'isConfirmed' => true));
  1516.         $resultAudio = new ArrayCollection();
  1517.         foreach ($liaisons as $liaison) {
  1518.             /** @var Audio */
  1519.             $audio $this->getDoctrine()->getRepository(Audio::class)
  1520.                 ->findOneBy(array('id' => $liaison->getIdAudio()));
  1521.             // Motifs
  1522.             /** @var AudioMotif[] */
  1523.             $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  1524.                 ->findBy(array('id_audio' => $liaison->getIdAudio()));
  1525.             // will test whether or not the audio has the necessery motif to be added
  1526.             $resultMotif = new ArrayCollection();
  1527.             foreach ($motifs as $motif) {
  1528.                 // ignore deleted motif
  1529.                 if (!$motif->getIsDeleted() && $motif->getType() !== 2)
  1530.                     $resultMotif->add([
  1531.                         "id" => $motif->getIdMotif()->getId(),
  1532.                         "titre" => $motif->getIdMotif()->getTitre(),
  1533.                         "consigne" => $motif->getConsigne(),
  1534.                         "duration" => $motif->getDuration(),
  1535.                         "isRdvonline" => $motif->getIsRdvonline(),
  1536.                     ]);
  1537.             }
  1538.             // Specialities
  1539.             /** @var AudioSpecialite[] */
  1540.             $specialities $this->getDoctrine()->getRepository(AudioSpecialite::class)
  1541.                 ->findBy(array('id_audio' => $liaison->getIdAudio()));
  1542.             //speciality filter
  1543.             $resultSpeciality = new ArrayCollection();
  1544.             foreach ($specialities as $speciality) {
  1545.                 if ($speciality->getIdSpecialite() !== null) {
  1546.                     $resultSpeciality->add([
  1547.                         "id" => $speciality->getIdSpecialite()->getId(),
  1548.                         "titre" => $speciality->getIdSpecialite()->getLibelle(),
  1549.                     ]);
  1550.                 }
  1551.             }
  1552.             // Experience
  1553.             /** @var AudioExperience[] */
  1554.             $experiences $this->getDoctrine()->getRepository(ExperiencePro::class)
  1555.                 ->findBy(array('id_audio' => $liaison->getIdAudio()));
  1556.             //speciality filter
  1557.             foreach ($experiences as $experience) {
  1558.                 // if ($speciality->getIdSpecialite() !== null) {
  1559.                 $resultExperience->add([
  1560.                     "audioId" => $experience->getIdAudio()->getId(),
  1561.                     "id" => $experience->getId(),
  1562.                     "date" => $experience->getDate(),
  1563.                     "post" => $experience->getPoste(),
  1564.                     "company" => $experience->getCompany()
  1565.                 ]);
  1566.                 //}
  1567.             }
  1568.             //dd($resultExperience);
  1569.             // Diplome
  1570.             /** @var AudioDiplomes[] */
  1571.             $diplomes $this->getDoctrine()->getRepository(AudioDiplome::class)
  1572.                 ->findBy(array('id_audio' => $liaison->getIdAudio()));
  1573.             //speciality filter
  1574.             foreach ($diplomes as $diplome) {
  1575.                 $audioId $liaison->getIdAudio();
  1576.                 // if ($speciality->getIdSpecialite() !== null) {
  1577.                 $resultDiplome->add([
  1578.                     "audioId" => $diplome->getIdAudio()->getId(),
  1579.                     "id" => $diplome->getIdDiplome()->getId(),
  1580.                     "date" => $diplome->getYear(),
  1581.                     "title" => $diplome->getIdDiplome()->getLibelle(),
  1582.                 ]);
  1583.                 //}
  1584.             }
  1585.             /** @var CentreImages[]*/
  1586.             $centerImages $this->getDoctrine()->getRepository(CenterImage::class)
  1587.                 ->findBy(array('center' => $centre->getId()));
  1588.             $resultCenterImage = new ArrayCollection();
  1589.             foreach ($centerImages as $centerImage) {
  1590.                 $resultCenterImage->add([
  1591.                     "id" => $centerImage->getId(),
  1592.                     "url" => $centerImage->getUrl(),
  1593.                     "type" => $centerImage->getType(),
  1594.                 ]);
  1595.             }
  1596.             //schedule
  1597.             $date = new DateTime();
  1598.             //add audio in the result 
  1599.             if ($centre->getHoraire() == null || $centre->getHoraire() == []) continue;
  1600.             /** @var Rdv[] */
  1601.             $audioRdvs $this->getDoctrine()->getRepository(Rdv::class)
  1602.                 ->findAllReviewsAudio($audio->getId());
  1603.             $resultAudio->add([
  1604.                 "id" => $audio->getId(),
  1605.                 "civilite" => $audio->getCivilite(),
  1606.                 "name" => $audio->getName(),
  1607.                 "lastname" => $audio->getLastname(),
  1608.                 "birthdate" => $audio->getBirthdate(),
  1609.                 "mail" => $audio->getMail(),
  1610.                 "phone" => $audio->getPhone(),
  1611.                 "adeli" => $audio->getAdeli(),
  1612.                 "pin" => $audio->getPin(),
  1613.                 "description" => $audio->getDescription(),
  1614.                 "imgUrl" => $audio->getImgUrl(),
  1615.                 "averageRating" => $publicFunction->calculateRating($audioRdvs),
  1616.                 "nbrReview" => count($audioRdvs),
  1617.                 "motifs" => $resultMotif->toArray(),
  1618.                 "specialities" => $resultSpeciality->toArray(),
  1619.                 "experiences" => $resultExperience->toArray(),
  1620.                 "centerImages" => $resultCenterImage->toArray(),
  1621.                 "diplomes" => $resultDiplome->toArray(),
  1622.                 "schedule" => [
  1623.                     $publicFunction->calculSchedule($audio, new \DateTime(), $centre),
  1624.                     $publicFunction->calculSchedule($audio$date->add(new DateInterval('P7D')), $centre),
  1625.                     $publicFunction->calculSchedule($audio$date->add(new DateInterval('P14D')), $centre)
  1626.                 ],
  1627.             ]);
  1628.             //dd($resultDiplome);
  1629.         }
  1630.         /** @var AccessCentre*/
  1631.         $accessCentre $this->getDoctrine()->getRepository(AccessCentre::class)
  1632.             ->findOneBy(array('id_centre' => $centre->getId()));
  1633.         if (!empty($accessCentre)) {
  1634.             /*return new Response(json_encode([
  1635.                 'message' => 'Error, no accessCentre found at this id',
  1636.                 'path' => 'src/Controller/CentreController.php',
  1637.             ]), 404);*/
  1638.             $metroIDs json_decode($accessCentre->getMetro(), true);
  1639.             $metroNames = array();
  1640.             if ($metroIDs) {
  1641.                 foreach ($metroIDs as $key => $stationID) {
  1642.                     $station $this->getDoctrine()->getRepository(Station::class)->find($stationID);
  1643.                     if ($station) {
  1644.                         $metroNames[$key] = $station->getName();
  1645.                     } else {
  1646.                         $metroNames[$key] = "Station Not Found";
  1647.                     }
  1648.                 }
  1649.             }
  1650.         }
  1651.         /** @var Rdv[] */
  1652.         $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  1653.             ->findAllReviewsCentre($centre->getId());
  1654.         // Comment
  1655.         /** @var Rdv[] */
  1656.         $rdvs $this->getDoctrine()->getRepository(Rdv::class)
  1657.             ->findBy(array('id_centre' => $centre));
  1658.         $comments = [];
  1659.         foreach ($rdvs as $rdv)
  1660.             if ($rdv->getComment() && $rdv->getReview() && $rdv->getIdClient())
  1661.                 array_push($comments, [
  1662.                     "id" => $rdv->getIdClient()->getId(),
  1663.                     "name" => $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname()[0] . ".",
  1664.                     "comment" => $rdv->getComment(),
  1665.                     "isMale" => $rdv->getIdClient()->getCivilite() == "Monsieur",
  1666.                     "review" => $rdv->getReview(),
  1667.                 ]);
  1668.         // dd($resultDiplome->toArray());
  1669.         return new Response(json_encode([
  1670.             "id" => $centre->getId(),
  1671.             "audio_id" => $centre->getIdGerant()->getId(),
  1672.             "name" => $centre->getName(),
  1673.             "imgUrl" => $centre->getImgUrl(),
  1674.             "isRdvDomicile" => $centre->getIsRdvDomicile(),
  1675.             "address" => $centre->getAddress(),
  1676.             "numero" => $centre->getNumero(),
  1677.             "voie" => $centre->getVoie(),
  1678.             "rue" => $centre->getRue(),
  1679.             "description" => $centre->getDescription(),
  1680.             "postale" => $centre->getPostale(),
  1681.             "city" => $centre->getCity(),
  1682.             "finess" => $centre->getFiness(),
  1683.             "siret" => $centre->getSiret(),
  1684.             "website" => $centre->getWebsite(),
  1685.             "phone" => $centre->getPhone(),
  1686.             "isHandicap" => $centre->getIsHandicap(),
  1687.             "longitude" => $centre->getLongitude(),
  1688.             "latitude" => $centre->getLatitude(),
  1689.             "averageRating" => $publicFunction->calculateRating($centreRdvs),
  1690.             "nbrReview" => count($centreRdvs),
  1691.             "tram" => !empty($accessCentre) ? $accessCentre->getTram() : null,
  1692.             "rer" => !empty($accessCentre) ? $accessCentre->getRer() : null,
  1693.             "experiences" => $resultExperience->toArray(),
  1694.             "diplomes" => $resultDiplome->toArray(),
  1695.             "centerImages" => $resultCenterImage->toArray(),
  1696.             "metro" => !empty($accessCentre) ? $metroNames null,
  1697.             "bus" => !empty($accessCentre) ? $accessCentre->getBus() : null,
  1698.             "parking" => !empty($accessCentre) ? $accessCentre->getParkingPublic() : null,
  1699.             "parkingPrivate" => !empty($accessCentre) ? $accessCentre->getParkingPrivate() : null,
  1700.             "other" => !empty($accessCentre) ? $accessCentre->getOther() : null,
  1701.             "comments" => $comments,
  1702.             "mutuelles" => $resultMutuelle->toArray(),
  1703.             "prestations" => $resultPrestation->toArray(),
  1704.             "tiers" => $resultTier->toArray(),
  1705.             "audio" => $resultAudio->toArray(),
  1706.             "schedule" => $centre->getHoraire(),
  1707.             "aditionnelInfo" => $centre->getAditionnelInfo(),
  1708.             "status" => 200,
  1709.         ]));
  1710.     }
  1711.     /**
  1712.      * @Route("/centreImported/{id}", name="getCentreimported", methods={"GET","HEAD"})
  1713.      */
  1714.     public function getCentreImorted(CenterImported $centrePublicFunction $publicFunction): Response
  1715.     {
  1716.         if (!$centre) {
  1717.             return $this->json([
  1718.                 'error' => 'Center not found'
  1719.             ], 404);
  1720.         }
  1721.         return $this->json([
  1722.             "center" => $centre,
  1723.             "status" => 200
  1724.         ]);
  1725.     }
  1726.     /**
  1727.      * @Route("/centre/{id}/withoutSchedule", name="getCentreWithoutSchedule", methods={"GET","HEAD"})
  1728.      */
  1729.     public function getCentreWithoutSchedule(Centre $centrePublicFunction $publicFunction): Response
  1730.     {
  1731.         /** @var CentrePrestation[]*/
  1732.         $prestations $this->getDoctrine()->getRepository(CentrePrestation::class)
  1733.             ->findBy(array('id_centre' => $centre->getId()));
  1734.         $resultPrestation = new ArrayCollection();
  1735.         foreach ($prestations as $prestation) {
  1736.             $resultPrestation->add([
  1737.                 "id" => $prestation->getIdPrestation()->getId(),
  1738.                 "titre" => $prestation->getIdPrestation()->getLibelle(),
  1739.             ]);
  1740.         }
  1741.         /** @var CentreMutuelle[]*/
  1742.         $mutuelles $this->getDoctrine()->getRepository(CentreMutuelle::class)
  1743.             ->findBy(array('id_centre' => $centre->getId()));
  1744.         $resultMutuelle = new ArrayCollection();
  1745.         foreach ($mutuelles as $mutuelle) {
  1746.             $resultMutuelle->add([
  1747.                 "id" => $mutuelle->getIdMutuelle()->getId(),
  1748.                 "titre" => $mutuelle->getIdMutuelle()->getLibelle(),
  1749.             ]);
  1750.         }
  1751.         /** @var CentreTier[]*/
  1752.         $tiers $this->getDoctrine()->getRepository(CentreTier::class)
  1753.             ->findBy(array('id_centre' => $centre->getId()));
  1754.         $resultTier = new ArrayCollection();
  1755.         foreach ($tiers as $tier) {
  1756.             $resultTier->add([
  1757.                 "id" => $tier->getIdTier()->getId(),
  1758.                 "titre" => $tier->getIdTier()->getLibelle(),
  1759.             ]);
  1760.         }
  1761.         /** @var AudioCentre[] */
  1762.         $liaisons $this->getDoctrine()->getRepository(AudioCentre::class)
  1763.             ->findBy(array('id_centre' => $centre'isConfirmed' => true));
  1764.         $resultAudio = new ArrayCollection();
  1765.         foreach ($liaisons as $liaison) {
  1766.             /** @var Audio */
  1767.             $audio $this->getDoctrine()->getRepository(Audio::class)
  1768.                 ->findOneBy(array('id' => $liaison->getIdAudio()));
  1769.             // Motifs
  1770.             /** @var AudioMotif[] */
  1771.             $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  1772.                 ->findBy(array('id_audio' => $liaison->getIdAudio()));
  1773.             // will test whether or not the audio has the necessery motif to be added
  1774.             $resultMotif = new ArrayCollection();
  1775.             foreach ($motifs as $motif) {
  1776.                 $resultMotif->add([
  1777.                     "id" => $motif->getIdMotif()->getId(),
  1778.                     "titre" => $motif->getIdMotif()->getTitre(),
  1779.                     "consigne" => $motif->getConsigne(),
  1780.                     "duration" => $motif->getDuration(),
  1781.                 ]);
  1782.             }
  1783.             // Specialities
  1784.             /** @var AudioSpecialite[] */
  1785.             $specialities $this->getDoctrine()->getRepository(AudioSpecialite::class)
  1786.                 ->findBy(array('id_audio' => $liaison->getIdAudio()));
  1787.             //speciality filter
  1788.             $resultSpeciality = new ArrayCollection();
  1789.             foreach ($specialities as $speciality) {
  1790.                 if ($speciality->getIdSpecialite() !== null) {
  1791.                     $resultSpeciality->add([
  1792.                         "id" => $speciality->getIdSpecialite()->getId(),
  1793.                         "titre" => $speciality->getIdSpecialite()->getLibelle(),
  1794.                     ]);
  1795.                 }
  1796.             }
  1797.             //schedule
  1798.             $date = new DateTime();
  1799.             //add audio in the result 
  1800.             if ($centre->getHoraire() == null || $centre->getHoraire() == []) continue;
  1801.             /** @var Rdv[] */
  1802.             $audioRdvs $this->getDoctrine()->getRepository(Rdv::class)
  1803.                 ->findAllReviewsAudio($audio->getId());
  1804.             $resultAudio->add([
  1805.                 "id" => $audio->getId(),
  1806.                 "civilite" => $audio->getCivilite(),
  1807.                 "name" => $audio->getName(),
  1808.                 "lastname" => $audio->getLastname(),
  1809.                 "birthdate" => $audio->getBirthdate(),
  1810.                 "mail" => $audio->getMail(),
  1811.                 "phone" => $audio->getPhone(),
  1812.                 "adeli" => $audio->getAdeli(),
  1813.                 "pin" => $audio->getPin(),
  1814.                 "description" => $audio->getDescription(),
  1815.                 "imgUrl" => $audio->getImgUrl(),
  1816.                 "averageRating" => $publicFunction->calculateRating($audioRdvs),
  1817.                 "nbrReview" => count($audioRdvs),
  1818.                 "motifs" => $resultMotif->toArray(),
  1819.                 "specialities" => $resultSpeciality->toArray(),
  1820.             ]);
  1821.         }
  1822.         /** @var AccessCentre*/
  1823.         $accessCentre $this->getDoctrine()->getRepository(AccessCentre::class)
  1824.             ->findOneBy(array('id_centre' => $centre->getId()));
  1825.         if (!$accessCentre)
  1826.             return new Response(json_encode([
  1827.                 'message' => 'Error, no accessCentre found at this id',
  1828.                 'path' => 'src/Controller/CentreController.php',
  1829.             ]), 404);
  1830.         /** @var Rdv[] */
  1831.         $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  1832.             ->findAllReviewsCentre($centre->getId());
  1833.         // Comment
  1834.         /** @var Rdv[] */
  1835.         $rdvs $this->getDoctrine()->getRepository(Rdv::class)
  1836.             ->findBy(array('id_centre' => $centre));
  1837.         $comments = [];
  1838.         foreach ($rdvs as $rdv)
  1839.             if ($rdv->getComment() && $rdv->getReview() && $rdv->getIdClient())
  1840.                 array_push($comments, [
  1841.                     "id" => $rdv->getIdClient()->getId(),
  1842.                     "name" => $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname()[0] . ".",
  1843.                     "comment" => $rdv->getComment(),
  1844.                     "isMale" => $rdv->getIdClient()->getCivilite() == "Monsieur",
  1845.                     "review" => $rdv->getReview(),
  1846.                 ]);
  1847.         $metroIDs json_decode($accessCentre->getMetro(), true);
  1848.         $metroNames = array();
  1849.         if ($metroIDs) {
  1850.             foreach ($metroIDs as $key => $stationID) {
  1851.                 $station $this->getDoctrine()->getRepository(Station::class)->find($stationID);
  1852.                 if ($station) {
  1853.                     $metroNames[$key]["name"] = $station->getName();
  1854.                     $metroNames[$key]["value"] = $station->getId();
  1855.                 }
  1856.             }
  1857.         }
  1858.         return new Response(json_encode([
  1859.             "id" => $centre->getId(),
  1860.             "audio_id" => $centre->getIdGerant()->getId(),
  1861.             "name" => $centre->getName(),
  1862.             "imgUrl" => $centre->getImgUrl(),
  1863.             "isRdvDomicile" => $centre->getIsRdvDomicile(),
  1864.             "address" => $centre->getAddress(),
  1865.             "numero" => $centre->getNumero(),
  1866.             "voie" => $centre->getVoie(),
  1867.             "rue" => $centre->getRue(),
  1868.             "description" => $centre->getDescription(),
  1869.             "postale" => $centre->getPostale(),
  1870.             "city" => $centre->getCity(),
  1871.             "finess" => $centre->getFiness(),
  1872.             "siret" => $centre->getSiret(),
  1873.             "website" => $centre->getWebsite(),
  1874.             "phone" => $centre->getPhone(),
  1875.             "isHandicap" => $centre->getIsHandicap(),
  1876.             "longitude" => $centre->getLongitude(),
  1877.             "latitude" => $centre->getLatitude(),
  1878.             "averageRating" => $publicFunction->calculateRating($centreRdvs),
  1879.             "nbrReview" => count($centreRdvs),
  1880.             "tram" => $accessCentre->getTram(),
  1881.             "rer" => $accessCentre->getRer(),
  1882.             "metro" => $metroNames,
  1883.             "bus" => $accessCentre->getBus(),
  1884.             "parking" => $accessCentre->getParkingPublic(),
  1885.             "parkingPrivate" => $accessCentre->getParkingPrivate(),
  1886.             "other" => $accessCentre->getOther(),
  1887.             "comments" => $comments,
  1888.             "mutuelles" => $resultMutuelle->toArray(),
  1889.             "prestations" => $resultPrestation->toArray(),
  1890.             "tiers" => $resultTier->toArray(),
  1891.             "audio" => $resultAudio->toArray(),
  1892.             "schedule" => $centre->getHoraire(),
  1893.             "status" => 200,
  1894.         ]));
  1895.     }
  1896.     /**
  1897.      * @Route("/centre/{id}/prestations", name="deleteAllCentrePrestations", methods={"DELETE"})
  1898.      */
  1899.     public function deleteAllCentrePrestations(Request $requestCentre $centre): Response
  1900.     {
  1901.         $centrePrestations $this->getDoctrine()
  1902.             ->getRepository(CentrePrestation::class)
  1903.             ->findBy(array('id_centre' => $centre->getId()));
  1904.         if (!$request->query->get('token')) {
  1905.             return new Response(json_encode([
  1906.                 "message" => "Pas de token n'a été spécifié",
  1907.                 "status" => 401,
  1908.             ]), 401);
  1909.         }
  1910.         $entityManager $this->getDoctrine()->getManager();
  1911.         /** @var Token */
  1912.         $token $this->getDoctrine()
  1913.             ->getRepository(Token::class)
  1914.             ->findOneBy(['token' => $request->query->get('token'), 'id_audio' => $centre->getIdGerant()]);
  1915.         if (!$token) {
  1916.             return new Response(json_encode([
  1917.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1918.                 "status" => 404,
  1919.             ]), 404);
  1920.         }
  1921.         // get token age
  1922.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1923.         // if the token if older than 7 days
  1924.         if ($dateDiff->7) {
  1925.             $entityManager->remove($token);
  1926.             $entityManager->flush();
  1927.             return $this->json([
  1928.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1929.                 'path' => 'src/Controller/ClientController.php',
  1930.                 "status" => 401,
  1931.             ], 401);
  1932.         }
  1933.         $entityManager $this->getDoctrine()->getManager();
  1934.         foreach ($centrePrestations as $centrePrestation) {
  1935.             $entityManager->remove($centrePrestation);
  1936.         }
  1937.         $entityManager->flush();
  1938.         return new Response("Prestations from centre " $centre->getId() . " correctly deleted.");
  1939.     }
  1940.     /**
  1941.      * @Route("/centre/prestations", name="postMultipleCentrePrestations", methods={"POST"})
  1942.      */
  1943.     public function postMultipleCentrePrestations(Request $request): Response
  1944.     {
  1945.         $data json_decode($request->getContent(), true);
  1946.         $centre $this->getDoctrine()
  1947.             ->getRepository(Centre::class)
  1948.             ->findOneBy(['id' => $data["id_centre"]]);
  1949.         if (!$centre) {
  1950.             return $this->json([
  1951.                 'message' => 'Error, no Centre found at this id',
  1952.                 'path' => 'src/Controller/CentreController.php',
  1953.             ]);
  1954.         }
  1955.         /** @var Token */
  1956.         $token $this->getDoctrine()
  1957.             ->getRepository(Token::class)
  1958.             ->findOneBy(['token' => $data["token"], 'id_audio' => $centre->getIdGerant()]);
  1959.         if (!$token) {
  1960.             return new Response(json_encode([
  1961.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1962.                 "status" => 404,
  1963.             ]), 404);
  1964.         }
  1965.         // get token age
  1966.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1967.         // if the token if older than 7 days
  1968.         if ($dateDiff->7) {
  1969.             $entityManager $this->getDoctrine()->getManager();
  1970.             $entityManager->remove($token);
  1971.             $entityManager->flush();
  1972.             return $this->json([
  1973.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1974.                 'path' => 'src/Controller/AudioController.php',
  1975.                 "status" => 401,
  1976.             ], 401);
  1977.         }
  1978.         foreach ($data["prestationList"] as $prestation) {
  1979.             $centrePrestation = new centrePrestation();
  1980.             $prestation $this->getDoctrine()
  1981.                 ->getRepository(Prestation::class)
  1982.                 ->findOneBy(['id' => $prestation]);
  1983.             if (!$prestation) {
  1984.                 return $this->json([
  1985.                     'message' => 'Error, no prestation found at this id',
  1986.                     'path' => 'src/Controller/CentreController.php',
  1987.                 ]);
  1988.             }
  1989.             $centrePrestation->setIdPrestation($prestation);
  1990.             $centrePrestation->setIdCentre($centre);
  1991.             $checkIfNull $this->getDoctrine()->getRepository(CentrePrestation::class)
  1992.                 ->findOneBy(['id_prestation' => $prestation'id_centre' => $data["id_centre"]]);
  1993.             if ($checkIfNull) {
  1994.                 return $this->json([
  1995.                     'message' => 'Error, prestation already found at this id',
  1996.                     'path' => 'src/Controller/CentreController.php',
  1997.                 ]);
  1998.             }
  1999.             $entityManager $this->getDoctrine()->getManager();
  2000.             $entityManager->persist($centrePrestation);
  2001.         }
  2002.         $entityManager->flush();
  2003.         return $this->json([
  2004.             "centre" => $centre->getId(),
  2005.             "prestations" => $data["prestationList"],
  2006.         ]);
  2007.     }
  2008.     /**
  2009.      * @Route("/centre/{id}/mutuelles", name="deleteAllCentreMutuelles", methods={"DELETE"})
  2010.      */
  2011.     public function deleteAllCentreMutuelles(Request $requestCentre $centre): Response
  2012.     {
  2013.         $centreMutuelles $this->getDoctrine()
  2014.             ->getRepository(CentreMutuelle::class)
  2015.             ->findBy(array('id_centre' => $centre->getId()));
  2016.         if (!$request->query->get('token')) {
  2017.             return new Response(json_encode([
  2018.                 "message" => "Pas de token n'a été spécifié",
  2019.                 "status" => 401,
  2020.             ]), 401);
  2021.         }
  2022.         $entityManager $this->getDoctrine()->getManager();
  2023.         /** @var Token */
  2024.         $token $this->getDoctrine()
  2025.             ->getRepository(Token::class)
  2026.             ->findOneBy(['token' => $request->query->get('token'), 'id_audio' => $centre->getIdGerant()]);
  2027.         if (!$token) {
  2028.             return new Response(json_encode([
  2029.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2030.                 "status" => 404,
  2031.             ]), 404);
  2032.         }
  2033.         // get token age
  2034.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2035.         // if the token if older than 7 days
  2036.         if ($dateDiff->7) {
  2037.             $entityManager->remove($token);
  2038.             $entityManager->flush();
  2039.             return $this->json([
  2040.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2041.                 'path' => 'src/Controller/ClientController.php',
  2042.                 "status" => 401,
  2043.             ], 401);
  2044.         }
  2045.         $entityManager $this->getDoctrine()->getManager();
  2046.         foreach ($centreMutuelles as $centreMutuelle) {
  2047.             $entityManager->remove($centreMutuelle);
  2048.         }
  2049.         $entityManager->flush();
  2050.         return new Response("Mutuelles from centre " $centre->getId() . " correctly deleted.");
  2051.     }
  2052.     /**
  2053.      * @Route("/centre/mutuelles", name="postMultipleCentreMutuelles", methods={"POST"})
  2054.      */
  2055.     public function postMultipleCentreMutuelles(Request $request): Response
  2056.     {
  2057.         $data json_decode($request->getContent(), true);
  2058.         $centre $this->getDoctrine()
  2059.             ->getRepository(Centre::class)
  2060.             ->findOneBy(['id' => $data["id_centre"]]);
  2061.         if (!$centre) {
  2062.             return $this->json([
  2063.                 'message' => 'Error, no Centre found at this id',
  2064.                 'path' => 'src/Controller/CentreController.php',
  2065.             ]);
  2066.         }
  2067.         /** @var Token */
  2068.         $token $this->getDoctrine()
  2069.             ->getRepository(Token::class)
  2070.             ->findOneBy(['token' => $data["token"], 'id_audio' => $centre->getIdGerant()]);
  2071.         if (!$token) {
  2072.             return new Response(json_encode([
  2073.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2074.                 "status" => 404,
  2075.             ]), 404);
  2076.         }
  2077.         // get token age
  2078.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2079.         // if the token if older than 7 days
  2080.         if ($dateDiff->7) {
  2081.             $entityManager $this->getDoctrine()->getManager();
  2082.             $entityManager->remove($token);
  2083.             $entityManager->flush();
  2084.             return $this->json([
  2085.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2086.                 'path' => 'src/Controller/AudioController.php',
  2087.                 "status" => 401,
  2088.             ], 401);
  2089.         }
  2090.         foreach ($data["mutuelleList"] as $mutuelle) {
  2091.             $centreMutuelle = new centreMutuelle();
  2092.             $mutuelle $this->getDoctrine()
  2093.                 ->getRepository(Mutuelle::class)
  2094.                 ->findOneBy(['id' => $mutuelle]);
  2095.             if (!$mutuelle) {
  2096.                 return $this->json([
  2097.                     'message' => 'Error, no mutuelle found at this id',
  2098.                     'path' => 'src/Controller/CentreController.php',
  2099.                 ]);
  2100.             }
  2101.             $centreMutuelle->setIdMutuelle($mutuelle);
  2102.             $centreMutuelle->setIdCentre($centre);
  2103.             $checkIfNull $this->getDoctrine()->getRepository(CentreMutuelle::class)
  2104.                 ->findOneBy(['id_mutuelle' => $mutuelle'id_centre' => $data["id_centre"]]);
  2105.             if ($checkIfNull) {
  2106.                 return $this->json([
  2107.                     'message' => 'Error, mutuelle already found at this id',
  2108.                     'path' => 'src/Controller/CentreController.php',
  2109.                 ]);
  2110.             }
  2111.             $entityManager $this->getDoctrine()->getManager();
  2112.             $entityManager->persist($centreMutuelle);
  2113.         }
  2114.         $entityManager->flush();
  2115.         return $this->json([
  2116.             "centre" => $centre->getId(),
  2117.             "mutuelles" => $data["mutuelleList"],
  2118.         ]);
  2119.     }
  2120.     /**
  2121.      * @Route("/update/audio-center", name="updateAudioCentre", methods={"POST"})
  2122.      */
  2123.     public function updateAudioCentre(Request $requestPublicFunction $publicFunctionStripeService $stripeService): Response
  2124.     {
  2125.         /*return $this->json([
  2126.             'message' => '',
  2127.             "status" => 200
  2128.         ], 200);
  2129. */
  2130.         $data json_decode($request->getContent(), true);
  2131.         $entityManager $this->getDoctrine()->getManager();
  2132.         /* "adeli": ""!empty,
  2133.             "civilite": "",
  2134.             "lastname": "",
  2135.             "name": "",
  2136.             "imgUrl": "",
  2137. */
  2138.         $audio =  $this->getDoctrine()
  2139.             ->getRepository(Audio::class)
  2140.             ->find($data['audioId']);
  2141.         $centre =  $this->getDoctrine()
  2142.             ->getRepository(Centre::class)
  2143.             ->find($data['centerId']);
  2144.         $audio->setDescription($data['descriptionAudio']);
  2145.         // diplomes
  2146.         if (isset($data["audio"]["0"]["diplome"]) && !empty($data["audio"]["0"]["diplome"])) {
  2147.             foreach ($data["audio"]["0"]["diplome"] as $diplomeObject) {
  2148.                 $diplome $this->getDoctrine()
  2149.                     ->getRepository(Diplome::class)
  2150.                     ->findOneBy(['id' => $diplomeObject["id"]]);
  2151.                 if ($diplome == null) {
  2152.                     /*$audioDiplome = new AudioDiplome();
  2153.                 if(isset($diplomeObject["year"]))
  2154.                 {
  2155.                     if(!empty($diplomeObject["year"]))
  2156.                     {
  2157.                         $audioDiplome->setYear($diplomeObject["year"]);
  2158.                     }
  2159.                 }
  2160.                 $audioDiplome->setUrl($diplomeObject["url"]);
  2161.                 $audioDiplome->setOther($data['otherdDiplom'][$key]);
  2162.                 $audioDiplome->setIdAudio($audio);
  2163.                 $entityManager->persist($audioDiplome);*/
  2164.                     return $this->json([
  2165.                         'message' => 'Error, no diplome found at this id ' $diplomeObject["id"],
  2166.                         'path' => 'src/Controller/AudioController.php',
  2167.                         "status" => 401
  2168.                     ], 401);
  2169.                 } else {
  2170.                     $audioDiplome = new AudioDiplome();
  2171.                     if (isset($diplomeObject["year"])) {
  2172.                         if (!empty($diplomeObject["year"])) {
  2173.                             $audioDiplome->setYear($diplomeObject["year"]);
  2174.                         }
  2175.                     }
  2176.                     //$audioDiplome->setUrl($diplomeObject["url"]);
  2177.                     $audioDiplome->setIdDiplome($diplome);
  2178.                     $audioDiplome->setIdAudio($audio);
  2179.                     $entityManager->persist($audioDiplome);
  2180.                 }
  2181.             }
  2182.         }
  2183.         // experiences
  2184.         if (isset($data["audio"]["0"]["experiences"]) && !empty($data["audio"]["0"]["experiences"])) {
  2185.             foreach ($data["audio"]["0"]["experiences"] as $experience) {
  2186.                 $audioSpecialite = new ExperiencePro();
  2187.                 $audioSpecialite->setDate(\DateTime::createFromFormat("d/m/Y"$experience["date"]));
  2188.                 $audioSpecialite->setPoste($experience["poste"]);
  2189.                 $audioSpecialite->setCompany($experience["company"]);
  2190.                 $audioSpecialite->setIdAudio($audio);
  2191.                 $entityManager->persist($audioSpecialite);
  2192.             }
  2193.         }
  2194.         // prestation
  2195.         if (isset($data["prestation"]) && !empty($data["prestation"])) {
  2196.             foreach ($data["prestation"] as $prestationId) {
  2197.                 $prestation $this->getDoctrine()
  2198.                     ->getRepository(Prestation::class)
  2199.                     ->findOneBy(['id' => $prestationId]);
  2200.                 $centrePrestation = new CentrePrestation();
  2201.                 $centrePrestation->setIdPrestation($prestation);
  2202.                 $centrePrestation->setIdCentre($centre);
  2203.                 $entityManager->persist($centrePrestation);
  2204.             }
  2205.         }
  2206.         // spetialites
  2207.         foreach ($data["audio"]["0"]["specialite"] as $specialiteId) {
  2208.             $specialite $this->getDoctrine()
  2209.                 ->getRepository(Specialite::class)
  2210.                 ->findOneBy(['id' => $specialiteId]);
  2211.             if (isset($data["autre_special_text"]) && !empty($data["autre_special_text"])) {
  2212.                 $audioSpecialite = new AudioSpecialite();
  2213.                 // $audioSpecialite->setIdSpecialite($specialite);
  2214.                 $audioSpecialite->setIdAudio($audio);
  2215.                 $audioSpecialite->setIdAudio($audio);
  2216.                 $entityManager->persist($audioSpecialite);
  2217.             }
  2218.             if ($specialite == null) {
  2219.                 return $this->json([
  2220.                     'message' => 'Error, no specialite found at this id ' $specialiteId,
  2221.                     'path' => 'src/Controller/AudioController.php',
  2222.                     "status" => 401
  2223.                 ], 401);
  2224.             } else {
  2225.                 $audioSpecialite = new AudioSpecialite();
  2226.                 $audioSpecialite->setIdSpecialite($specialite);
  2227.                 $audioSpecialite->setIdAudio($audio);
  2228.                 $entityManager->persist($audioSpecialite);
  2229.             }
  2230.         }
  2231.         if (isset($data["mutuelle"]))
  2232.             foreach ($data["mutuelle"] as $mutuelleObject) {
  2233.                 $mutuelle $this->getDoctrine()
  2234.                     ->getRepository(Mutuelle::class)
  2235.                     ->findOneBy(['id' => $mutuelleObject]);
  2236.                 if ($mutuelle == null) {
  2237.                     return new Response(json_encode([
  2238.                         'message' => 'Error, no mutuelle found at this id ' $mutuelleObject,
  2239.                         'path' => 'src/Controller/CentreController.php',
  2240.                     ]));
  2241.                 } else {
  2242.                     $centreMutuelle = new CentreMutuelle();
  2243.                     $centreMutuelle->setIdMutuelle($mutuelle);
  2244.                     $centreMutuelle->setIdCentre($centre);
  2245.                     if (isset($data["otherMutuelle"]) && $mutuelle->getLibelle() == "Autres")
  2246.                         $centreMutuelle->setOther(json_encode($data["otherMutuelle"], JSON_FORCE_OBJECT));
  2247.                     $entityManager->persist($centreMutuelle);
  2248.                 }
  2249.             }
  2250.         //other spetiality 
  2251.         if (isset($data["otherSpetiality"]) && !empty($data["otherSpetiality"])) {
  2252.             $audioSpecialite = new AudioSpecialite();
  2253.             // $audioSpecialite->setIdSpecialite($specialite);
  2254.             $audioSpecialite->setIdAudio($audio);
  2255.             $audioSpecialite->setOther(json_encode($data["otherSpetiality"], JSON_FORCE_OBJECT));
  2256.             $entityManager->persist($audioSpecialite);
  2257.         }
  2258.         if (isset($data["tier"]))
  2259.             foreach ($data["tier"] as $tierObject) {
  2260.                 $tier $this->getDoctrine()
  2261.                     ->getRepository(Tier::class)
  2262.                     ->findOneBy(['id' => $tierObject]);
  2263.                 if ($tier == null) {
  2264.                     return new Response(json_encode([
  2265.                         'message' => 'Error, no tier found at this id ' $tierObject,
  2266.                         'path' => 'src/Controller/CentreController.php',
  2267.                     ]));
  2268.                 } else {
  2269.                     $centreTier = new CentreTier();
  2270.                     $centreTier->setIdTier($tier);
  2271.                     $centreTier->setIdCentre($centre);
  2272.                     $entityManager->persist($centreTier);
  2273.                 }
  2274.             }
  2275.         if (isset($data["access"]) && !empty($data["access"])) {
  2276.             $accessCentre $this->getDoctrine()
  2277.                 ->getRepository(AccessCentre::class)
  2278.                 ->findOneBy(['id_centre' => $centre]);
  2279.             if (!$accessCentre) {
  2280.                 $accessCentre = new AccessCentre();
  2281.             }                // add the acces to center 
  2282.             foreach ($data["access"] as $accessData) {
  2283.                 if (isset($accessData["metro"]))
  2284.                     $accessCentre->setMetro(json_encode($accessData["metro"], JSON_FORCE_OBJECT));
  2285.                 if (isset($accessData["bus"]))
  2286.                     $accessCentre->setBus(json_encode($accessData["bus"], JSON_FORCE_OBJECT));
  2287.                 if (isset($accessData["tram"]))
  2288.                     $accessCentre->setTram(json_encode($accessData["tram"], JSON_FORCE_OBJECT));
  2289.                 if (isset($accessData["rer"]))
  2290.                     $accessCentre->setRer(json_encode($accessData["rer"], JSON_FORCE_OBJECT));
  2291.                 if (isset($accessData["parkingPublic"]))
  2292.                     $accessCentre->setParkingPublic(json_encode($accessData["parkingPublic"], JSON_FORCE_OBJECT));
  2293.                 if (isset($accessData["parkingPrive"]))
  2294.                     $accessCentre->setParkingPrivate(json_encode($accessData["parkingPrive"], JSON_FORCE_OBJECT));
  2295.                 if (isset($accessData["other"]))
  2296.                     $accessCentre->setOther(json_encode($accessData["other"], JSON_FORCE_OBJECT));
  2297.             }
  2298.             $accessCentre->setIdCentre($centre);
  2299.             $entityManager->persist($accessCentre);
  2300.         }
  2301.         $centre->setDescription($data['descriptionCentre']);
  2302.         $entityManager->persist($audio);
  2303.         $entityManager->flush();
  2304.         return $this->json([
  2305.             'message' => '',
  2306.             "status" => 200
  2307.         ], 200);
  2308.     }
  2309.     /**
  2310.      * @Route("/centre", name="postCentre", methods={"POST"})
  2311.      */
  2312.     public function postCentre(Request $requestPublicFunction $publicFunctionStripeService $stripeService): Response
  2313.     {
  2314.         $data json_decode($request->getContent(), true);
  2315.         $requestData = [
  2316.             "name" => $data["audio"][0]["name"],
  2317.             "email" => $data["audio"][0]["mail"],
  2318.             "address" => $data["address"],
  2319.             "quantity" => $data["quantity"],
  2320.             "price" => $data["price"]["finalPrice"] ?? $data["price"],
  2321.             "recurring" => ($data["price"]["recurring"] === "monthly") ? "month" : (($data["price"]["recurring"] === "yearly") ? "year" $data["price"]["recurring"]),
  2322.             "paymentMethodId" => $data["paymentMethodId"],
  2323.             "offerName" => $data["plan"]["planName"]
  2324.         ];
  2325.         $createSubscription $stripeService->createSubscriptionStripe($requestData);
  2326.         $centre = new Centre();
  2327.         $resultAudio = new ArrayCollection();
  2328.         $gerant null;
  2329.         if ($data['gerant'] !== "") {
  2330.             $gerant $this->getDoctrine()
  2331.                 ->getRepository(Audio::class)
  2332.                 ->find($data['gerant']);
  2333.         }
  2334.         if (isset($data["audio"])) {
  2335.             $entityManager $this->getDoctrine()->getManager();
  2336.             foreach ($data["audio"] as $key => $audioMap) {
  2337.                 // check if audio exist to collect on new center 
  2338.                 if ($audioMap['registredAudio'] !== "") {
  2339.                     $audio $this->getDoctrine()
  2340.                         ->getRepository(Audio::class)
  2341.                         ->find($audioMap['registredAudio']);
  2342.                     $audioCentre = new AudioCentre();
  2343.                     $audioCentre->setIdAudio($audio);
  2344.                     $audioCentre->setIdCentre($centre);
  2345.                     $audioCentre->setIsConfirmed(true);
  2346.                     $audioCentre->setHoraire($publicFunction->centreHoraire2);
  2347.                     $entityManager->persist($audioCentre);
  2348.                 } else {
  2349.                     $role $this->getDoctrine()
  2350.                         ->getRepository(Role::class)
  2351.                         ->find($audioMap["role"]);
  2352.                     $audio = new Audio();
  2353.                     $audio->setCivilite($audioMap["civilite"]);
  2354.                     $audio->setName($audioMap["lastname"]);
  2355.                     $audio->setLastname($audioMap["name"]);
  2356.                     $audio->setBirthdate(\DateTime::createFromFormat("d/m/Y"$audioMap["birthdate"]));
  2357.                     $audio->setRole($role);
  2358.                     $audio->setSignupDate(new \DateTime());
  2359.                     // set notification by default selected
  2360.                     $audio->setConfirmRdvMail(true);
  2361.                     $audio->setConfirmRdvSms(true);
  2362.                     $audio->setModifRdvMail(true);
  2363.                     $audio->setModifRdvSms(true);
  2364.                     $audio->setModifNote(true);
  2365.                     $audioMailTest $this->getDoctrine()
  2366.                         ->getRepository(Audio::class)
  2367.                         ->findOneBy(['mail' => $audioMap["mail"]]);
  2368.                     if ($audioMailTest)
  2369.                         return $this->json([
  2370.                             'message' => 'Audio mail',
  2371.                             'mail' => $audioMap["mail"],
  2372.                             'path' => 'src/Controller/AudioController.php',
  2373.                             "status" => 402
  2374.                         ], 401);
  2375.                     $audio->setMail($audioMap["mail"]);
  2376.                     $audioPhoneTest $this->getDoctrine()
  2377.                         ->getRepository(Audio::class)
  2378.                         ->findOneBy(['phone' => $audioMap["phone"]]);
  2379.                     if ($audioPhoneTest)
  2380.                         return $this->json([
  2381.                             'message' => 'Audio phone',
  2382.                             'phone' => $audioMap["phone"],
  2383.                             'path' => 'src/Controller/AudioController.php',
  2384.                             "status" => 403
  2385.                         ], 401);
  2386.                     $audio->setPhone($audioMap["phone"]);
  2387.                     //$audio->setAdeli($audioMap["adeli"]);
  2388.                     if ($data["isImported"] !== '')
  2389.                         $audio->setCodeParrainage($data["isImported"]);
  2390.                     $audio->setIsIndie(false);
  2391.                     // set default pass for audio inserted
  2392.                     $audioMap["password"] !== "" $audio->setPassword(password_hash($audioMap["password"], PASSWORD_DEFAULT)) : $audio->setPassword(password_hash("myaudio2023"PASSWORD_DEFAULT));
  2393.                     $audio->setPin($audioMap["pin"]);
  2394.                     // $audio->setDescription($audioMap["description"]);
  2395.                     if (isset($audioMap["imgUrl"]))
  2396.                         $audio->setImgUrl($audioMap["imgUrl"]);
  2397.                     $entityManager $this->getDoctrine()->getManager();
  2398.                     foreach ($audioMap["diplome"] as $diplomeObject) {
  2399.                         $diplome $this->getDoctrine()
  2400.                             ->getRepository(Diplome::class)
  2401.                             ->findOneBy(['id' => $diplomeObject["id"]]);
  2402.                         if ($diplome == null) {
  2403.                             /*$audioDiplome = new AudioDiplome();
  2404.                         if(isset($diplomeObject["year"]))
  2405.                         {
  2406.                             if(!empty($diplomeObject["year"]))
  2407.                             {
  2408.                                 $audioDiplome->setYear($diplomeObject["year"]);
  2409.                             }
  2410.                         }
  2411.                         $audioDiplome->setUrl($diplomeObject["url"]);
  2412.                         $audioDiplome->setOther($data['otherdDiplom'][$key]);
  2413.                         $audioDiplome->setIdAudio($audio);
  2414.                         $entityManager->persist($audioDiplome);*/
  2415.                             return $this->json([
  2416.                                 'message' => 'Error, no diplome found at this id ' $diplomeObject["id"],
  2417.                                 'path' => 'src/Controller/AudioController.php',
  2418.                                 "status" => 401
  2419.                             ], 401);
  2420.                         } else {
  2421.                             $audioDiplome = new AudioDiplome();
  2422.                             if (isset($diplomeObject["year"])) {
  2423.                                 if (!empty($diplomeObject["year"])) {
  2424.                                     $audioDiplome->setYear($diplomeObject["year"]);
  2425.                                 }
  2426.                             }
  2427.                             $audioDiplome->setUrl($diplomeObject["url"]);
  2428.                             $audioDiplome->setIdDiplome($diplome);
  2429.                             $audioDiplome->setIdAudio($audio);
  2430.                             $entityManager->persist($audioDiplome);
  2431.                         }
  2432.                     }
  2433.                     foreach ($audioMap["experiences"] as $experience) {
  2434.                         $audioSpecialite = new ExperiencePro();
  2435.                         $audioSpecialite->setDate(\DateTime::createFromFormat("d/m/Y"$experience["date"]));
  2436.                         $audioSpecialite->setPoste($experience["poste"]);
  2437.                         $audioSpecialite->setCompany($experience["company"]);
  2438.                         $audioSpecialite->setIdAudio($audio);
  2439.                         $entityManager->persist($audioSpecialite);
  2440.                     }
  2441.                     foreach ($audioMap["specialite"] as $specialiteId) {
  2442.                         $specialite $this->getDoctrine()
  2443.                             ->getRepository(Specialite::class)
  2444.                             ->findOneBy(['id' => $specialiteId]);
  2445.                         if (isset($audioMap["autre_special_text"])) {
  2446.                             $audioSpecialite = new AudioSpecialite();
  2447.                             // $audioSpecialite->setIdSpecialite($specialite);
  2448.                             $audioSpecialite->setIdAudio($audio);
  2449.                             $audioSpecialite->setIdAudio($audio);
  2450.                             $entityManager->persist($audioSpecialite);
  2451.                         }
  2452.                         if ($specialite == null) {
  2453.                             return $this->json([
  2454.                                 'message' => 'Error, no specialite found at this id ' $specialiteId,
  2455.                                 'path' => 'src/Controller/AudioController.php',
  2456.                                 "status" => 401
  2457.                             ], 401);
  2458.                         } else {
  2459.                             $audioSpecialite = new AudioSpecialite();
  2460.                             $audioSpecialite->setIdSpecialite($specialite);
  2461.                             $audioSpecialite->setIdAudio($audio);
  2462.                             $entityManager->persist($audioSpecialite);
  2463.                         }
  2464.                     }
  2465.                     // $entityManager->persist($audio);
  2466.                     $entityManager->persist($this->createPermanantMotif(60"#FF00FF"$audio,  11));
  2467.                     $entityManager->persist($this->createPermanantMotif(90"#00FFFF"$audio,  21));
  2468.                     $entityManager->persist($this->createPermanantMotif(30"#FFFF00"$audio,  31));
  2469.                     $entityManager->persist($this->createPermanantMotif(60"#FF0000"$audio,  41));
  2470.                     $entityManager->persist($this->createPermanantMotif(60"#FFCC59"$audio692));
  2471.                     $entityManager->persist($this->createPermanantMotif(30"#33B679"$audio1061));
  2472.                     $entityManager->persist($this->createPermanantMotif(30"#F6BF25"$audio1071));
  2473.                     $entityManager->persist($this->createPermanantMotif(30"#E67C73"$audio1081));
  2474.                     $entityManager->persist($this->createPermanantMotif(30"#7886CB"$audio1091));
  2475.                     //  $entityManager->persist($this->createPermanantMotif(60, "#FF0000", $audio,  5));
  2476.                     $entityManager->persist($audio);
  2477.                     if ($gerant == null$gerant $audio;
  2478.                     $audioCentre = new AudioCentre();
  2479.                     $audioCentre->setIdAudio($audio);
  2480.                     $audioCentre->setIdCentre($centre);
  2481.                     $audioCentre->setIsConfirmed(true);
  2482.                     $audioCentre->setHoraire($publicFunction->centreHoraire2);
  2483.                     $centerHoliday json_decode($publicFunction->centreHoraire4true);
  2484.                     $audioCentre->setHorairesHoliday($centerHoliday);
  2485.                     $entityManager->persist($audioCentre);
  2486.                     // SEN MAIL NOTIF JUST FOR AUDIOS ADDED NOT FOR GERANT
  2487.                     if ($key !== 0) {
  2488.                         // GENERATE TOKEN & AUDIO ADDED MAIL CONFIRM
  2489.                         $tokenString $publicFunction->generateRandomString(30);
  2490.                         $params = array(
  2491.                             "lien" => "{$_ENV['BASE_client']}confirmation_email/{$audio->getMail()}?token={$tokenString}",
  2492.                             "nom" => "{$audio->getLastName()}",
  2493.                             "texte" => "Veuillez cliquer sur le bouton ci-dessous pour confirmer votre adresse mail",
  2494.                             "titre" => "Confirmer mon email",
  2495.                             "bouton" => "Confirmer mon Email",
  2496.                         );
  2497.                         $publicFunction->sendEmail($params$audio->getMail(), $audio->getName() . ' ' $audio->getLastName(), "Confirmation d'inscription sur My Audio Pro"122);
  2498.                         $token = new Token();
  2499.                         $token->setCreationDate(new DateTime());
  2500.                         $token->setToken($tokenString);
  2501.                         $token->setMail($audio->getMail());
  2502.                         $entityManager $this->getDoctrine()->getManager();
  2503.                         $entityManager->persist($token);
  2504.                         // $entityManager->flush();
  2505.                     }
  2506.                 }
  2507.                 $resultAudio->add([
  2508.                     "id" => $audio->getId(),
  2509.                     "civilite" => $audio->getCivilite(),
  2510.                     "name" => $audio->getName(),
  2511.                     "lastname" => $audio->getLastname(),
  2512.                     "birthdate" => $audio->getBirthdate(),
  2513.                     "mail" => $audio->getMail(),
  2514.                     "phone" => $audio->getPhone(),
  2515.                     "adeli" => $audio->getAdeli(),
  2516.                     "pin" => $audio->getPin(),
  2517.                     "description" => $audio->getDescription(),
  2518.                     "imgUrl" => $audio->getImgUrl(),
  2519.                 ]);
  2520.             }
  2521.         } else {
  2522.             return new Response(json_encode([
  2523.                 'message' => 'Error, no audio found',
  2524.                 'path' => 'src/Controller/CentreController.php',
  2525.             ]), 404);
  2526.         }
  2527.         // generate color code 
  2528.         $colors = array(
  2529.             "#FFC0CB"// Pink
  2530.             "#FFD700"// Gold
  2531.             "#90EE90"// Light Green
  2532.             "#87CEFA"// Light Sky Blue
  2533.             "#FFA07A"// Light Salmon
  2534.             "#F0E68C"// Khaki
  2535.             "#B0C4DE"// Light Steel Blue
  2536.             "#98FB98"// Pale Green
  2537.             "#FFB6C1"// Light Pink
  2538.             "#ADD8E6"// Light Blue
  2539.             "#FF69B4"// Hot Pink
  2540.             "#FFA500"// Orange
  2541.             "#00FF7F"// Spring Green
  2542.             "#AFEEEE"// Pale Turquoise
  2543.             "#FF8C00"// Dark Orange
  2544.             "#FFE4B5"// Moccasin
  2545.             "#00CED1"// Dark Turquoise
  2546.             "#7FFFD4"// Aquamarine
  2547.             "#FF4500"// Orange Red
  2548.             "#00FA9A"// Medium Spring Green
  2549.             "#FFF0F5"// Lavender Blush
  2550.             "#00BFFF"// Deep Sky Blue
  2551.             "#FF6347"// Tomato
  2552.             "#20B2AA"// Light Sea Green
  2553.             "#FFFF00"// Yellow
  2554.             "#32CD32"// Lime Green
  2555.             "#FFF5EE"// Seashell
  2556.             "#1E90FF"// Dodger Blue
  2557.             "#CD5C5C"// Indian Red
  2558.             "#8FBC8F"// Dark Sea Green
  2559.             "#F0FFFF"// Azure
  2560.             "#4169E1"// Royal Blue
  2561.             "#FF8B00"// Dark Orange
  2562.             "#66CDAA"// Medium Aquamarine
  2563.             "#FFFACD"// Lemon Chiffon
  2564.             "#6495ED"// Cornflower Blue
  2565.             "#FF7F50"// Coral
  2566.             "#00FF00"// Lime
  2567.             "#FAFAD2"// Light Goldenrod Yellow
  2568.             "#87CEEB"// Sky Blue
  2569.             "#DC143C"// Crimson
  2570.             "#2E8B57"// Sea Green
  2571.             "#F5DEB3"// Wheat
  2572.             "#4682B4"// Steel Blue
  2573.             "#CD853F"// Peru
  2574.             "#8A2BE2"// Blue Violet
  2575.             "#D2691E"// Chocolate
  2576.             "#6A5ACD"// Slate Blue
  2577.             "#F5F5DC"// Beige
  2578.             "#7B68EE"// Medium Slate Blue
  2579.         );
  2580.         // short initial 
  2581.         $name $data['name'];
  2582.         $words explode(' '$name);
  2583.         $initials '';
  2584.         foreach ($words as $word) {
  2585.             $initials .= strtoupper(substr($word01));
  2586.         }
  2587.         $initials strtoupper($initials);
  2588.         $shortName substr($initials02);
  2589.         $randomColor $colors[array_rand($colors)];
  2590.         // generate slug url 
  2591.         $slug $this->slugger->slug($data["name"])->lower();
  2592.         $centre->setName($data["name"]);
  2593.         $slugify $this->getDoctrine()
  2594.             ->getRepository(Centre::class)
  2595.             ->findOneBy(array('slug' => $slug));
  2596.         if ($slugify) {
  2597.             $centre->setSlug($slug "-1");
  2598.         } else {
  2599.             $centre->setSlug($slug);
  2600.         }
  2601.         if (isset($data["imgUrl"]))
  2602.             $centre->setImgUrl($data["imgUrl"]);
  2603.         if (isset($data["finessURL"]))
  2604.             $centre->setFinessUrl($data["finessURL"]);
  2605.         $centre->setIsRdvDomicile($data["isRdvDomicile"]);
  2606.         $centre->setIdGerant($gerant);
  2607.         $centre->setAddress($data["address"]);
  2608.         $centre->setPostale($data["postal"]);
  2609.         $centre->setCity($data["city"]);
  2610.         $centre->setFiness($data["finess"]);
  2611.         $centre->setSiret($data["siret"]);
  2612.         $centre->setInitial($shortName);
  2613.         $centre->setWebsite($data["website"]);
  2614.         $centre->setSignupDate(new \DateTime());
  2615.         $centre->setCalendarColor($randomColor);
  2616.         // set the galeries for images by default
  2617.         // Define an array of default image URLs
  2618.         $defaultImages = ["by-default-1.jpeg""by-default-2.jpeg""by-default-3.jpeg"];
  2619.         // Iterate through each default image
  2620.         foreach ($defaultImages as $imageUrl) {
  2621.             $centerImage = new CenterImage();
  2622.             $centerImage->setType("image");
  2623.             $centerImage->setUrl($imageUrl);
  2624.             // Associate the center image with the current center
  2625.             $centerImage->setCenter($centre);
  2626.             $entityManager->persist($centerImage);
  2627.         }
  2628.         /*$centrePhoneTest = $this->getDoctrine()
  2629.             ->getRepository(Centre::class)
  2630.             ->findOneBy(['phone' => $data["phone"]]);
  2631.         if ($centrePhoneTest)
  2632.             return $this->json([
  2633.                 'message' => 'Centre phone',
  2634.                 'path' => 'src/Controller/CentreController.php',
  2635.                 "status" => 401
  2636.             ], 401);*/
  2637.         $centre->setPhone($data["phone"]);
  2638.         $centre->setIsHandicap($data["isHandicap"]);
  2639.         $centre->setLongitude($data["longitude"]);
  2640.         $centre->setLatitude($data["latitude"]);
  2641.         $centre->setHoraire($publicFunction->centreHoraire2);
  2642.         $centerHoliday json_decode($publicFunction->centreHoraire4true);
  2643.         $centre->setHorairesHoliday($centerHoliday);
  2644.         $entityManager $this->getDoctrine()->getManager();
  2645.         //add the centre access
  2646.         if (isset($data["mutuelle"]))
  2647.             foreach ($data["mutuelle"] as $mutuelleObject) {
  2648.                 $mutuelle $this->getDoctrine()
  2649.                     ->getRepository(Mutuelle::class)
  2650.                     ->findOneBy(['id' => $mutuelleObject]);
  2651.                 if ($mutuelle == null) {
  2652.                     return new Response(json_encode([
  2653.                         'message' => 'Error, no mutuelle found at this id ' $mutuelleObject,
  2654.                         'path' => 'src/Controller/CentreController.php',
  2655.                     ]));
  2656.                 } else {
  2657.                     $centreMutuelle = new CentreMutuelle();
  2658.                     $centreMutuelle->setIdMutuelle($mutuelle);
  2659.                     $centreMutuelle->setIdCentre($centre);
  2660.                     if (isset($data["otherMutuelle"]) && $mutuelle->getLibelle() == "Autres")
  2661.                         $centreMutuelle->setOther(json_encode($data["otherMutuelle"], JSON_FORCE_OBJECT));
  2662.                     $entityManager->persist($centreMutuelle);
  2663.                 }
  2664.             }
  2665.         //other spetiality 
  2666.         if (isset($data["otherSpetiality"])) {
  2667.             $audioSpecialite = new AudioSpecialite();
  2668.             // $audioSpecialite->setIdSpecialite($specialite);
  2669.             $audioSpecialite->setIdAudio($audio);
  2670.             $audioSpecialite->setOther(json_encode($data["otherSpetiality"], JSON_FORCE_OBJECT));
  2671.             $entityManager->persist($audioSpecialite);
  2672.         }
  2673.         if (isset($data["tier"]))
  2674.             foreach ($data["tier"] as $tierObject) {
  2675.                 $tier $this->getDoctrine()
  2676.                     ->getRepository(Tier::class)
  2677.                     ->findOneBy(['id' => $tierObject]);
  2678.                 if ($tier == null) {
  2679.                     return new Response(json_encode([
  2680.                         'message' => 'Error, no tier found at this id ' $tierObject,
  2681.                         'path' => 'src/Controller/CentreController.php',
  2682.                     ]));
  2683.                 } else {
  2684.                     $centreTier = new CentreTier();
  2685.                     $centreTier->setIdTier($tier);
  2686.                     $centreTier->setIdCentre($centre);
  2687.                     $entityManager->persist($centreTier);
  2688.                 }
  2689.             }
  2690.         /*  if (isset($data["prestation"]))
  2691.             foreach ($data["prestation"] as $prestationId) {
  2692.                 $prestation = $this->getDoctrine()
  2693.                     ->getRepository(Prestation::class)
  2694.                     ->findOneBy(['id' => $prestationId]);
  2695.                 if ($prestation == null) {
  2696.                     return new Response(json_encode([
  2697.                         'message' => 'Error, no prestation found at this id ' . $prestationId,
  2698.                         'path' => 'src/Controller/CentreController.php',
  2699.                     ]));
  2700.                 } else {
  2701.                     $centrePrestation = new CentrePrestation();
  2702.                     $centrePrestation->setIdPrestation($prestation);
  2703.                     $centrePrestation->setIdCentre($centre);
  2704.                     $entityManager->persist($centrePrestation);
  2705.                 }
  2706.             }*/
  2707.         $entityManager->persist($centre);
  2708.         // for audio on multi centre creation
  2709.         $accessCentre = new AccessCentre();
  2710.         //  $accessData = $data["access"];
  2711.         // add the acces to center 
  2712.         foreach ($data["access"] as $accessData) {
  2713.             if (isset($accessData["metro"]))
  2714.                 $accessCentre->setMetro(json_encode($accessData["metro"], JSON_FORCE_OBJECT));
  2715.             if (isset($accessData["bus"]))
  2716.                 $accessCentre->setBus(json_encode($accessData["bus"], JSON_FORCE_OBJECT));
  2717.             if (isset($accessData["tram"]))
  2718.                 $accessCentre->setTram(json_encode($accessData["tram"], JSON_FORCE_OBJECT));
  2719.             if (isset($accessData["rer"]))
  2720.                 $accessCentre->setRer(json_encode($accessData["rer"], JSON_FORCE_OBJECT));
  2721.             if (isset($accessData["parkingPublic"]))
  2722.                 $accessCentre->setParkingPublic(json_encode($accessData["parkingPublic"], JSON_FORCE_OBJECT));
  2723.             if (isset($accessData["parkingPrivate"]))
  2724.                 $accessCentre->setParkingPrivate(json_encode($accessData["parkingPrivate"], JSON_FORCE_OBJECT));
  2725.             if (isset($accessData["other"]))
  2726.                 $accessCentre->setOther(json_encode($accessData["other"], JSON_FORCE_OBJECT));
  2727.         }
  2728.         $accessCentre->setIdCentre($centre);
  2729.         $entityManager->persist($accessCentre);
  2730.         $entityManager->flush();
  2731.         // save print setting 
  2732.         $setting = new Setting();
  2733.         $setting->setName($data["name"]);
  2734.         $setting->setAddress($data["address"]);
  2735.         $setting->setPhone($data["phone"]);
  2736.         $setting->setLogoUrl($centre->getImgUrl());
  2737.         $setting->setWebsite($data["website"]);
  2738.         $setting->setFirstname($audio->getName());
  2739.         $setting->setLastname($audio->getLastname());
  2740.         $setting->setEmail($gerant->getMail());
  2741.         $setting->setSeuilCaDroite(true);
  2742.         $setting->setSeuilCaGauche(true);
  2743.         $setting->setSeuilConfortDroite(true);
  2744.         $setting->setSeuilConfortGauche(true);
  2745.         $setting->setSeuilinconfortDroite(true);
  2746.         $setting->setSeuilInConfortGauche(true);
  2747.         $setting->setSeuilCoDroite(true);
  2748.         $setting->setSeuilCoGauche(true);
  2749.         $setting->setSeuilCaMaskingDroite(true);
  2750.         $setting->setSeuilCaMaskingGauche(true);
  2751.         $setting->setSeuilCoMaskingDroite(true);
  2752.         $setting->setSeuilCoMaskingGauche(true);
  2753.         /* $setting->setCasqueDroite(false);
  2754.         $setting->setCasqueGauche(false);
  2755.         $setting->setCasqueBinaural(false);
  2756.         $setting->setChampsLibreDroite(false);
  2757.         $setting->setChampsLibreGauche(false);
  2758.         $setting->setChampsLibreBinaural(false);
  2759.         $setting->setChampsLibreAppDroite(false);
  2760.         $setting->setChampsLibreAppGauche(false);
  2761.         $setting->setChampsLibreAppBinaural(false);*/
  2762.         $setting->setCasqueDroite(true);
  2763.         $setting->setCasqueGauche(true);
  2764.         $setting->setCasqueBinaural(true);
  2765.         $setting->setChampsLibreDroite(true);
  2766.         $setting->setChampsLibreGauche(true);
  2767.         $setting->setChampsLibreBinaural(true);
  2768.         $setting->setChampsLibreAppDroite(true);
  2769.         $setting->setChampsLibreAppGauche(true);
  2770.         $setting->setChampsLibreAppBinaural(true);
  2771.         $setting->setCentre($centre);
  2772.         $entityManager->persist($setting);
  2773.         $entityManager->flush();
  2774.         //envoi mail de confirmation d'email au gérant.
  2775.         $tokenString $publicFunction->generateRandomString(30);
  2776.         $params = array(
  2777.             "lien" => "{$_ENV['BASE_client']}confirmation_email/{$gerant->getMail()}?token={$tokenString}",
  2778.             "nom" => "{$gerant->getLastName()}",
  2779.             "texte" => "Veuillez cliquer sur le bouton ci-dessous pour confirmer votre adresse mail",
  2780.             "titre" => "Confirmer mon email",
  2781.             "bouton" => "Confirmer mon Email",
  2782.         );
  2783.         $publicFunction->sendEmail($params$gerant->getMail(), $gerant->getName() . ' ' $gerant->getLastName(), "Confirmation d'inscription sur My Audio Pro"122);
  2784.         $token = new Token();
  2785.         $token->setCreationDate(new DateTime());
  2786.         $token->setToken($tokenString);
  2787.         $token->setMail($gerant->getMail());
  2788.         $entityManager $this->getDoctrine()->getManager();
  2789.         $entityManager->persist($token);
  2790.         $entityManager->flush();
  2791.         $user = [
  2792.             "prenomAudioprothesiste" => $gerant->getName(),
  2793.             "urlDemo" => "https://calendar.google.com/calendar/u/0/appointments/schedules/AcZssZ0Ry72UDE9m8d2IylSycOMQVerlY0jHt1DLWFD6Pso4hg79sQ9nUAlxtZYOPH6wSubDX4vqVQWh",
  2794.         ];
  2795.         // we send parametre for the trait methid
  2796.         $params $this->emailNotificationDemoService->prepareEmailParams($user);
  2797.         // send email notifcation
  2798.         $this->emailNotificationDemoService->sendEmail($params$gerant->getMail(), 'Organisez votre Démo personnalisée de My Audio Pro'143);
  2799.         // set order datable patient 
  2800.         $this->orderPatient->createOrderPatient($audio);
  2801.         return new Response(json_encode([
  2802.             "id" => $centre->getId(),
  2803.             "name" => $centre->getName(),
  2804.             "imgUrl" => $centre->getImgUrl(),
  2805.             "isRdvDomicile" => $centre->getIsRdvDomicile(),
  2806.             "audio_id" => $centre->getIdGerant()->getId(),
  2807.             "address" => $centre->getAddress(),
  2808.             "postale" => $centre->getPostale(),
  2809.             "city" => $centre->getCity(),
  2810.             "finess" => $centre->getFiness(),
  2811.             "siret" => $centre->getSiret(),
  2812.             "website" => $centre->getWebsite(),
  2813.             "phone" => $centre->getPhone(),
  2814.             "isHandicap" => $centre->getIsHandicap(),
  2815.             "audio" => $resultAudio->toArray(),
  2816.             "centerId" => $centre->getId(),
  2817.             "audioId" => $audio->getId(),
  2818.             "status" => 200,
  2819.         ]));
  2820.     }
  2821. /**
  2822.  * @Route("/centre/create-subscription", name="postCentreCreateSubscription", methods={"POST"})
  2823.  */
  2824. public function createSubscription(Request $requestStripeService $stripeService): Response
  2825. {
  2826.     $data json_decode($request->getContent(), true);
  2827. //dd($data);
  2828.     // Assurez-vous que paymentMethodId est présent
  2829.     if (empty($data['paymentMethodId'])) {
  2830.         return new JsonResponse(['error' => 'paymentMethodId manquant'], 400);
  2831.     }
  2832.     $name = isset($data["audio"][0]["name"]) ? $data["audio"][0]["name"] : '';
  2833.     $lastname = isset($data["audio"][0]["lastname"]) ? $data["audio"][0]["lastname"] : '';
  2834.     $email = isset($data["audio"][0]["mail"]) ? $data["audio"][0]["mail"] : 'email@inconnu.com';
  2835.     $requestData = [
  2836.         "name" => trim($name ' ' $lastname) ?: 'Nom inconnu',
  2837.         "email" => $email,
  2838.         "address" => $data["address"] ?? '',
  2839.         "quantity" => $data["quantity"] ?? 1,
  2840.         "price" => $data["price"]["finalPrice"] ?? $data["price"] ?? 0,
  2841.         "recurring" => isset($data["price"]["recurring"]) && $data["price"]["recurring"] === "monthly"
  2842.         "month"
  2843.         : ($data["price"]["recurring"] === "yearly" "year" $data["price"]["recurring"]),
  2844.         "paymentMethodId" => $data["paymentMethodId"],
  2845.         "offerName" => $data["plan"]["planName"],
  2846.     ];
  2847.     try {
  2848.         // Appelle ton service pour créer la souscription Stripe
  2849.         $subscription $stripeService->createSubscriptionStripe($requestData);
  2850.            return $this->json([
  2851.         'status' => 'success',
  2852.         'subscriptionId' => $subscription->id,
  2853.         'customerId' => $subscription->customer,
  2854.         'clientSecret' => $subscription->latest_invoice->payment_intent->client_secret ?? null,
  2855.         'created' => $subscription->created,
  2856.         'current_period_start' => $subscription->current_period_start,
  2857.         'current_period_end' => $subscription->current_period_end,
  2858.         'invoiceId' => $subscription->latest_invoice->id ?? null,
  2859.         'default_payment_method' => $subscription->default_payment_method,
  2860.         'requiresAction' => isset($subscription->latest_invoice->payment_intent->status)
  2861.         && $subscription->latest_invoice->payment_intent->status === 'requires_action',
  2862.     ]);
  2863.     } catch (\Exception $e) {
  2864.         return $this->json([
  2865.             'status' => 'error',
  2866.             'message' => $e->getMessage(),
  2867.         ], 500);
  2868.     }
  2869. }
  2870. /**
  2871.  * @Route("/centre/create-subscription-atol", name="postCentreCreateSubscriptionAtol", methods={"POST"})
  2872.  */
  2873. public function createSubscriptionAtol(Request $requestStripeService $stripeService): Response
  2874. {
  2875.     $data json_decode($request->getContent(), true);
  2876. //dd($data);
  2877.     // Assurez-vous que paymentMethodId est présent
  2878.     if (empty($data['paymentMethodId'])) {
  2879.         return new JsonResponse(['error' => 'paymentMethodId manquant'], 400);
  2880.     }
  2881.     $name = isset($data["audio"][0]["name"]) ? $data["audio"][0]["name"] : '';
  2882.     $lastname = isset($data["audio"][0]["lastname"]) ? $data["audio"][0]["lastname"] : '';
  2883.     $email = isset($data["audio"][0]["mail"]) ? $data["audio"][0]["mail"] : 'email@inconnu.com';
  2884.     $quantity = ($data["quantity"] ?? 1) - 2;
  2885.     $requestData = [
  2886.         "name" => trim($name ' ' $lastname) ?: 'Nom inconnu',
  2887.         "email" => $email,
  2888.         "address" => $data["address"] ?? '',
  2889.         "quantity" => $quantity,
  2890.         "price" => $data["price"]["finalPrice"] ?? $data["price"] ?? 0,
  2891.         "recurring" => isset($data["price"]["recurring"]) && $data["price"]["recurring"] === "monthly"
  2892.         "month"
  2893.         : ($data["price"]["recurring"] === "yearly" "year" $data["price"]["recurring"]),
  2894.         "paymentMethodId" => $data["paymentMethodId"],
  2895.         "offerName" => $data["plan"]["planName"],
  2896.     ];
  2897.     try {
  2898.         // Appelle ton service pour créer la souscription Stripe
  2899.         $subscription $stripeService->createSubscriptionStripeAtol($requestData);
  2900.            return $this->json([
  2901.         'status' => 'success',
  2902.         'subscriptionId' => $subscription->id,
  2903.         'customerId' => $subscription->customer,
  2904.         'clientSecret' => $subscription->latest_invoice->payment_intent->client_secret ?? null,
  2905.         'created' => $subscription->created,
  2906.         'current_period_start' => $subscription->current_period_start,
  2907.         'current_period_end' => $subscription->current_period_end,
  2908.         'invoiceId' => $subscription->latest_invoice->id ?? null,
  2909.         'default_payment_method' => $subscription->default_payment_method,
  2910.         'requiresAction' => isset($subscription->latest_invoice->payment_intent->status)
  2911.         && $subscription->latest_invoice->payment_intent->status === 'requires_action',
  2912.     ]);
  2913.     } catch (\Exception $e) {
  2914.         return $this->json([
  2915.             'status' => 'error',
  2916.             'message' => $e->getMessage(),
  2917.         ], 500);
  2918.     }
  2919. }
  2920.     /**
  2921.      * @Route("/centre/new-inscription", name="postCentreNewInscription", methods={"POST"})
  2922.      */
  2923.     public function postCentreNewInscription(Request $requestPublicFunction $publicFunctionStripeService $stripeServiceSubscriptionService $subscrition): Response
  2924.     {
  2925.         $data json_decode($request->getContent(), true);
  2926.        /* $requestData = [
  2927.             "name" => $data["audio"][0]["name"],
  2928.             "email" => $data["audio"][0]["mail"],
  2929.             "address" => $data["address"],
  2930.             "quantity" => $data["quantity"],
  2931.             "price" => $data["price"]["finalPrice"] ?? $data["price"],
  2932.             "recurring" => ($data["price"]["recurring"] === "monthly") ? "month" : (($data["price"]["recurring"] === "yearly") ? "year" : $data["price"]["recurring"]),
  2933.             "paymentMethodId" => $data["paymentMethodId"],
  2934.             "offerName" => $data["plan"]["planName"],
  2935.         ];
  2936.         $createSubscription = $stripeService->createSubscriptionStripe($requestData);*/
  2937.         // dd($createSubscription);
  2938.         $subscriptionData $data['subscription'];
  2939.         $centre = new Centre();
  2940.         $resultAudio = new ArrayCollection();
  2941.         $gerant null;
  2942.         if ($data['gerant'] !== "") {
  2943.             $gerant $this->getDoctrine()
  2944.                 ->getRepository(Audio::class)
  2945.                 ->find($data['gerant']);
  2946.         }
  2947.         if (isset($data["audio"])) {
  2948.             $entityManager $this->getDoctrine()->getManager();
  2949.             foreach ($data["audio"] as $key => $audioMap) {
  2950.                 // check if audio exist to collect on new center 
  2951.                 if ($audioMap['registredAudio'] !== "") {
  2952.                     $audio $this->getDoctrine()
  2953.                         ->getRepository(Audio::class)
  2954.                         ->find($audioMap['registredAudio']);
  2955.                     $audioCentre = new AudioCentre();
  2956.                     $audioCentre->setIdAudio($audio);
  2957.                     $audioCentre->setIdCentre($centre);
  2958.                     $audioCentre->setIsConfirmed(true);
  2959.                     $audioCentre->setHoraire($publicFunction->centreHoraire2);
  2960.                     $entityManager->persist($audioCentre);
  2961.                 } else {
  2962.                     $role $this->getDoctrine()
  2963.                         ->getRepository(Role::class)
  2964.                         ->find($audioMap["role"]);
  2965.                     $audio = new Audio();
  2966.                     $audio->setBirthdate(\DateTime::createFromFormat("d/m/Y"$audioMap["birthdate"]));
  2967.                     $audio->setRole($role);
  2968.                     $audio->setSignupDate(new \DateTime());
  2969.                     $audio->setAdeli($data["audio"]["0"]["adeli"]);
  2970.                     $audio->setCivilite($data["audio"]["0"]["civilite"]);
  2971.                     $audio->setLastName($data["audio"]["0"]["lastname"]);
  2972.                     $audio->setName($data["audio"]["0"]["name"]);
  2973.                     // set notification by default selected
  2974.                     $audio->setConfirmRdvMail(true);
  2975.                     $audio->setConfirmRdvSms(true);
  2976.                     $audio->setModifRdvMail(true);
  2977.                     $audio->setModifRdvSms(true);
  2978.                     $audio->setModifNote(true);
  2979.                     $audioMailTest $this->getDoctrine()
  2980.                         ->getRepository(Audio::class)
  2981.                         ->findOneBy(['mail' => $audioMap["mail"]]);
  2982.                     /*if ($audioMailTest)
  2983.                 return $this->json([
  2984.                     'message' => "L'adresse e-mail est déjà enregistrée.",
  2985.                     'mail' => $audioMap["mail"],
  2986.                     'code' => "mail_exist",
  2987.                     'status' => 409 
  2988.                 ], 500); */
  2989.                     $audio->setMail($audioMap["mail"]);
  2990.                     $audioPhoneTest $this->getDoctrine()
  2991.                         ->getRepository(Audio::class)
  2992.                         ->findOneBy(['phone' => $audioMap["phone"]]);
  2993.                     /*if ($audioPhoneTest)
  2994.                 return $this->json([
  2995.                     'message' => 'Le numéro de téléphone est déjà enregistré.',
  2996.                     'phone' => $audioMap["phone"],
  2997.                     'code' => "phone_exist",
  2998.                     'status' => 409 
  2999.                 ], 500); */
  3000.                     $audio->setPhone($audioMap["phone"]);
  3001.                     //$audio->setAdeli($audioMap["adeli"]);
  3002.                     if ($data["isImported"] !== '')
  3003.                         $audio->setCodeParrainage($data["isImported"]);
  3004.                     $audio->setIsIndie(false);
  3005.                     // set default pass for audio inserted
  3006.                     $audioMap["password"] !== "" $audio->setPassword(password_hash($audioMap["password"], PASSWORD_DEFAULT)) : $audio->setPassword(password_hash("myaudio2023"PASSWORD_DEFAULT));
  3007.                     $audio->setPin($audioMap["pin"]);
  3008.                     // $audio->setDescription($audioMap["description"]);
  3009.                     if (isset($audioMap["imgUrl"]))
  3010.                         $audio->setImgUrl($audioMap["imgUrl"]);
  3011.                     $entityManager $this->getDoctrine()->getManager();
  3012.                     foreach ($audioMap["diplome"] as $diplomeObject) {
  3013.                         $diplome $this->getDoctrine()
  3014.                             ->getRepository(Diplome::class)
  3015.                             ->findOneBy(['id' => $diplomeObject["id"]]);
  3016.                         if ($diplome == null) {
  3017.                             /*$audioDiplome = new AudioDiplome();
  3018.                         if(isset($diplomeObject["year"]))
  3019.                         {
  3020.                             if(!empty($diplomeObject["year"]))
  3021.                             {
  3022.                                 $audioDiplome->setYear($diplomeObject["year"]);
  3023.                             }
  3024.                         }
  3025.                         $audioDiplome->setUrl($diplomeObject["url"]);
  3026.                         $audioDiplome->setOther($data['otherdDiplom'][$key]);
  3027.                         $audioDiplome->setIdAudio($audio);
  3028.                         $entityManager->persist($audioDiplome);*/
  3029.                             return $this->json([
  3030.                                 'message' => 'Error, no diplome found at this id ' $diplomeObject["id"],
  3031.                                 'path' => 'src/Controller/AudioController.php',
  3032.                                 "status" => 401
  3033.                             ], 401);
  3034.                         } else {
  3035.                             $audioDiplome = new AudioDiplome();
  3036.                             if (isset($diplomeObject["year"])) {
  3037.                                 if (!empty($diplomeObject["year"])) {
  3038.                                     $audioDiplome->setYear($diplomeObject["year"]);
  3039.                                 }
  3040.                             }
  3041.                             $audioDiplome->setUrl($diplomeObject["url"]);
  3042.                             $audioDiplome->setIdDiplome($diplome);
  3043.                             $audioDiplome->setIdAudio($audio);
  3044.                             $entityManager->persist($audioDiplome);
  3045.                         }
  3046.                     }
  3047.                     // $entityManager->persist($audio);
  3048.                     $entityManager->persist($this->createPermanantMotif(60"#FF00FF"$audio,  11));
  3049.                     $entityManager->persist($this->createPermanantMotif(90"#00FFFF"$audio,  21));
  3050.                     $entityManager->persist($this->createPermanantMotif(30"#FFFF00"$audio,  31));
  3051.                     $entityManager->persist($this->createPermanantMotif(60"#FF0000"$audio,  41));
  3052.                     $entityManager->persist($this->createPermanantMotif(60"#FFCC59"$audio692));
  3053.                     $entityManager->persist($this->createPermanantMotif(30"#33B679"$audio1061));
  3054.                     $entityManager->persist($this->createPermanantMotif(30"#F6BF25"$audio1071));
  3055.                     $entityManager->persist($this->createPermanantMotif(30"#E67C73"$audio1081));
  3056.                     $entityManager->persist($this->createPermanantMotif(30"#7886CB"$audio1091));
  3057.                     //  $entityManager->persist($this->createPermanantMotif(60, "#FF0000", $audio,  5));
  3058.                     $entityManager->persist($audio);
  3059.                     if ($gerant == null$gerant $audio;
  3060.                     $audioCentre = new AudioCentre();
  3061.                     $audioCentre->setIdAudio($audio);
  3062.                     $audioCentre->setIdCentre($centre);
  3063.                     $audioCentre->setIsConfirmed(true);
  3064.                     $audioCentre->setHoraire($publicFunction->centreHoraire2);
  3065.                     $centerHoliday json_decode($publicFunction->centreHoraire4true);
  3066.                     $audioCentre->setHorairesHoliday($centerHoliday);
  3067.                     $entityManager->persist($audioCentre);
  3068.                     // SEN MAIL NOTIF JUST FOR AUDIOS ADDED NOT FOR GERANT
  3069.                     // $entityManager->flush();
  3070.                 }
  3071.                 $resultAudio->add([
  3072.                     "id" => $audio->getId(),
  3073.                     "civilite" => $audio->getCivilite(),
  3074.                     "name" => $audio->getName(),
  3075.                     "lastname" => $audio->getLastname(),
  3076.                     "birthdate" => $audio->getBirthdate(),
  3077.                     "mail" => $audio->getMail(),
  3078.                     "phone" => $audio->getPhone(),
  3079.                     "adeli" => $audio->getAdeli(),
  3080.                     "pin" => $audio->getPin(),
  3081.                     "description" => $audio->getDescription(),
  3082.                     "imgUrl" => $audio->getImgUrl(),
  3083.                 ]);
  3084.             }
  3085.         } else {
  3086.             return new Response(json_encode([
  3087.                 'message' => 'Error, no audio found',
  3088.                 'path' => 'src/Controller/CentreController.php',
  3089.             ]), 404);
  3090.         }
  3091.         // generate color code 
  3092.         $colors = array(
  3093.             "#FFC0CB"// Pink
  3094.             "#FFD700"// Gold
  3095.             "#90EE90"// Light Green
  3096.             "#87CEFA"// Light Sky Blue
  3097.             "#FFA07A"// Light Salmon
  3098.             "#F0E68C"// Khaki
  3099.             "#B0C4DE"// Light Steel Blue
  3100.             "#98FB98"// Pale Green
  3101.             "#FFB6C1"// Light Pink
  3102.             "#ADD8E6"// Light Blue
  3103.             "#FF69B4"// Hot Pink
  3104.             "#FFA500"// Orange
  3105.             "#00FF7F"// Spring Green
  3106.             "#AFEEEE"// Pale Turquoise
  3107.             "#FF8C00"// Dark Orange
  3108.             "#FFE4B5"// Moccasin
  3109.             "#00CED1"// Dark Turquoise
  3110.             "#7FFFD4"// Aquamarine
  3111.             "#FF4500"// Orange Red
  3112.             "#00FA9A"// Medium Spring Green
  3113.             "#FFF0F5"// Lavender Blush
  3114.             "#00BFFF"// Deep Sky Blue
  3115.             "#FF6347"// Tomato
  3116.             "#20B2AA"// Light Sea Green
  3117.             "#FFFF00"// Yellow
  3118.             "#32CD32"// Lime Green
  3119.             "#FFF5EE"// Seashell
  3120.             "#1E90FF"// Dodger Blue
  3121.             "#CD5C5C"// Indian Red
  3122.             "#8FBC8F"// Dark Sea Green
  3123.             "#F0FFFF"// Azure
  3124.             "#4169E1"// Royal Blue
  3125.             "#FF8B00"// Dark Orange
  3126.             "#66CDAA"// Medium Aquamarine
  3127.             "#FFFACD"// Lemon Chiffon
  3128.             "#6495ED"// Cornflower Blue
  3129.             "#FF7F50"// Coral
  3130.             "#00FF00"// Lime
  3131.             "#FAFAD2"// Light Goldenrod Yellow
  3132.             "#87CEEB"// Sky Blue
  3133.             "#DC143C"// Crimson
  3134.             "#2E8B57"// Sea Green
  3135.             "#F5DEB3"// Wheat
  3136.             "#4682B4"// Steel Blue
  3137.             "#CD853F"// Peru
  3138.             "#8A2BE2"// Blue Violet
  3139.             "#D2691E"// Chocolate
  3140.             "#6A5ACD"// Slate Blue
  3141.             "#F5F5DC"// Beige
  3142.             "#7B68EE"// Medium Slate Blue
  3143.         );
  3144.         // short initial 
  3145.         $name $data['name'];
  3146.         $words explode(' '$name);
  3147.         $initials '';
  3148.         foreach ($words as $word) {
  3149.             $initials .= strtoupper(substr($word01));
  3150.         }
  3151.         $initials strtoupper($initials);
  3152.         $shortName substr($initials02);
  3153.         $randomColor $colors[array_rand($colors)];
  3154.         // generate slug url 
  3155.         $slug $this->slugger->slug($data["name"])->lower();
  3156.         $centre->setName(strtoupper($data["name"]));
  3157.         $slugify $this->getDoctrine()
  3158.             ->getRepository(Centre::class)
  3159.             ->findOneBy(array('slug' => $slug));
  3160.         if ($slugify) {
  3161.             $centre->setSlug($slug "-1");
  3162.         } else {
  3163.             $centre->setSlug($slug);
  3164.         }
  3165.         if (isset($data["imgUrl"]))
  3166.             $centre->setImgUrl($data["imgUrl"]);
  3167.         if (isset($data["finessURL"]))
  3168.             $centre->setFinessUrl($data["finessURL"]);
  3169.         $centre->setIsRdvDomicile($data["isRdvDomicile"]);
  3170.         $centre->setIdGerant($gerant);
  3171.         $centre->setAddress($data["address"]);
  3172.         $centre->setPostale($data["postal"]);
  3173.         $centre->setCity(strtoupper($data["city"]));
  3174.         $centre->setFiness($data["finess"]);
  3175.         $centre->setSocialName($data["companyName"]);
  3176.         $centre->setSiret($data["siret"]);
  3177.         $centre->setInitial($shortName);
  3178.         $centre->setWebsite($data["website"]);
  3179.         $centre->setSignupDate(new \DateTime());
  3180.         $centre->setCalendarColor($randomColor);
  3181.         // set the galeries for images by default
  3182.         // Define an array of default image URLs
  3183.         $defaultImages = ["by-default-1.jpeg""by-default-2.jpeg""by-default-3.jpeg"];
  3184.         // Iterate through each default image
  3185.         foreach ($defaultImages as $imageUrl) {
  3186.             $centerImage = new CenterImage();
  3187.             $centerImage->setType("image");
  3188.             $centerImage->setUrl($imageUrl);
  3189.             // Associate the center image with the current center
  3190.             $centerImage->setCenter($centre);
  3191.             $entityManager->persist($centerImage);
  3192.         }
  3193.         /*$centrePhoneTest = $this->getDoctrine()
  3194.             ->getRepository(Centre::class)
  3195.             ->findOneBy(['phone' => $data["phone"]]);
  3196.         if ($centrePhoneTest)
  3197.             return $this->json([
  3198.                 'message' => 'Centre phone',
  3199.                 'path' => 'src/Controller/CentreController.php',
  3200.                 "status" => 401
  3201.             ], 401);*/
  3202.         $centre->setPhone($data["phone"]);
  3203.         $centre->setIsHandicap($data["isHandicap"]);
  3204.         $centre->setLongitude($data["longitude"]);
  3205.         $centre->setLatitude($data["latitude"]);
  3206.         $centre->setHoraire($publicFunction->centreHoraire2);
  3207.         $centerHoliday json_decode($publicFunction->centreHoraire4true);
  3208.         $centre->setHorairesHoliday($centerHoliday);
  3209.         $centre->setZoneKm(5);
  3210.        
  3211.        
  3212.        
  3213.         $entityManager $this->getDoctrine()->getManager();
  3214.         $entityManager->persist($centre);
  3215.         // for audio on multi centre creation
  3216.         
  3217.          
  3218.         $accessCentre = new AccessCentre();
  3219.         //  $accessData = $data["access"];
  3220.         $entityManager->flush();
  3221.         // save print setting 
  3222.         $setting = new Setting();
  3223.         $setting->setName($data["name"]);
  3224.         $setting->setAddress($data["address"]);
  3225.         $setting->setPhone($data["phone"]);
  3226.         $setting->setLogoUrl($centre->getImgUrl());
  3227.         $setting->setWebsite($data["website"]);
  3228.         $setting->setFirstname($audio->getName());
  3229.         $setting->setLastname($audio->getLastname());
  3230.         $setting->setEmail($gerant->getMail());
  3231.         $setting->setSeuilCaDroite(true);
  3232.         $setting->setSeuilCaGauche(true);
  3233.         $setting->setSeuilConfortDroite(true);
  3234.         $setting->setSeuilConfortGauche(true);
  3235.         $setting->setSeuilinconfortDroite(true);
  3236.         $setting->setSeuilInConfortGauche(true);
  3237.         $setting->setSeuilCoDroite(true);
  3238.         $setting->setSeuilCoGauche(true);
  3239.         $setting->setSeuilCaMaskingDroite(true);
  3240.         $setting->setSeuilCaMaskingGauche(true);
  3241.         $setting->setSeuilCoMaskingDroite(true);
  3242.         $setting->setSeuilCoMaskingGauche(true);
  3243.         /* $setting->setCasqueDroite(false);
  3244.         $setting->setCasqueGauche(false);
  3245.         $setting->setCasqueBinaural(false);
  3246.         $setting->setChampsLibreDroite(false);
  3247.         $setting->setChampsLibreGauche(false);
  3248.         $setting->setChampsLibreBinaural(false);
  3249.         $setting->setChampsLibreAppDroite(false);
  3250.         $setting->setChampsLibreAppGauche(false);
  3251.         $setting->setChampsLibreAppBinaural(false);*/
  3252.         $setting->setCasqueDroite(true);
  3253.         $setting->setCasqueGauche(true);
  3254.         $setting->setCasqueBinaural(true);
  3255.         $setting->setChampsLibreDroite(true);
  3256.         $setting->setChampsLibreGauche(true);
  3257.         $setting->setChampsLibreBinaural(true);
  3258.         $setting->setChampsLibreAppDroite(true);
  3259.         $setting->setChampsLibreAppGauche(true);
  3260.         $setting->setChampsLibreAppBinaural(true);
  3261.         $setting->setCentre($centre);
  3262.         $entityManager->persist($setting);
  3263.         $entityManager->flush();
  3264.         $tokenString $publicFunction->generateRandomString(30);
  3265.         $params = array(
  3266.             "lien" => "{$_ENV['BASE_client']}confirmation_email/{$data["audio"][0]["mail"]}?token={$tokenString}",
  3267.             "nom" => "",
  3268.             "texte" => "Veuillez cliquer sur le bouton ci-dessous pour confirmer votre adresse mail",
  3269.             "titre" => "Confirmer mon email",
  3270.             "bouton" => "Confirmer mon Email",
  3271.         );
  3272.         $publicFunction->sendEmail($params$data["audio"][0]["mail"], "myaudio""Confirmation d'inscription sur My Audio Pro"122);
  3273.         $token = new Token();
  3274.         $token->setCreationDate(new DateTime());
  3275.         $token->setToken($tokenString);
  3276.         $token->setMail($audio->getMail());
  3277.         $entityManager $this->getDoctrine()->getManager();
  3278.         $entityManager->persist($token);
  3279.         $entityManager->flush();
  3280.              // create the sheet of ads
  3281.              $postales $this->getPostalCodes($centre);
  3282.              $dataSheet = [
  3283.                  $centre->getId() ?? ''// id centre
  3284.                  $centre->getName() ?? '',  // Nom
  3285.                  $centre->getCity() ?? '',  // ville
  3286.                  $centre->getLongitude() ?? ''// longitude
  3287.                  $centre->getLatitude() ?? '',  // lattitude
  3288.                  $centre->getZoneKm() ?? '',  // zone km
  3289.                  ($centre->getIdGerant()->getLastName() ?? '') . ' ' . ($centre->getIdGerant()->getName() ?? ''),
  3290.                  $centre->getAddress() ?? '',
  3291.                  $centre->getPostale() ?? '',
  3292.                  $postales ?? '' // in case postales is missing
  3293.              ];
  3294.              
  3295.          
  3296.              $this->googleSheetsService->appendToSheetZoneKm($dataSheet'centersByZoneKm');
  3297.         
  3298.              // create the sheet of marketing
  3299.              $entityManager $this->getDoctrine()->getManager();
  3300.              $sheetName 'AIntegrer';
  3301.              
  3302.              // Get already existing postals from column D
  3303.              $existingValues $this->googleSheetsService->getColumnValues($sheetName4); // column D
  3304.              $existingPostales array_filter($existingValues); 
  3305.              $existingPostales array_map('strval'$existingPostales); 
  3306.              
  3307.              if (!$centre) {
  3308.                  throw new \Exception('Centre not found.');
  3309.              }
  3310.              
  3311.              $rowsToAppend = [];
  3312.              
  3313.              $postales $this->getPostalCodesMarket($centre);
  3314.              $postales array_unique($postales);
  3315.              
  3316.              $newPostales array_diff($postales$existingPostales);
  3317.              $newPostales array_values($newPostales); // reset keys
  3318.              
  3319.              if (count($newPostales) > 0) {
  3320.                  $now = (new \DateTime())->format('d/m/Y');
  3321.                  $centerPostal $centre->getPostale();
  3322.              
  3323.                  foreach ($newPostales as $index => $postal) {
  3324.                      if ($index === 0) {
  3325.                          $rowsToAppend[] = [false$now$centerPostal$postal];
  3326.                      } else {
  3327.                          $rowsToAppend[] = [''''''$postal];
  3328.                      }
  3329.                  }
  3330.              
  3331.                  $this->googleSheetsService->appendToSheetMarketing($rowsToAppend$sheetName);
  3332.              }
  3333.              
  3334.         /* $user = [
  3335.             "prenomAudioprothesiste" => $gerant->getName(),
  3336.             "urlDemo" => "https://calendar.google.com/calendar/u/0/appointments/schedules/AcZssZ0Ry72UDE9m8d2IylSycOMQVerlY0jHt1DLWFD6Pso4hg79sQ9nUAlxtZYOPH6wSubDX4vqVQWh",
  3337.         ];
  3338.         // we send parametre for the trait methid
  3339.         $params = $this->emailNotificationDemoService->prepareEmailParams($user);
  3340.         // send email notifcation
  3341.         $this->emailNotificationDemoService->sendEmail($params, $gerant->getMail(), 'Organisez votre Démo personnalisée de My Audio Pro', 143);
  3342.         */
  3343.         // set order datable patient 
  3344.         $this->orderPatient->createOrderPatient($audio);
  3345.         $plan $this->getDoctrine()->getRepository(Plan::class)
  3346.             ->findOneBy(["slug" => $data['plan']["planName"]]);
  3347.         $dataSubsc = [];
  3348.               $dataSubsc['created'] = $subscriptionData['created'];
  3349.         $dataSubsc['currentPeriodStart'] = $subscriptionData['current_period_start'];
  3350.         $dataSubsc['currentPeriodEnd'] = $subscriptionData['current_period_end'];
  3351.         $dataSubsc['centerId'] = $centre->getId();
  3352.         $dataSubsc['audioId'] = $audio->getId();
  3353.         $dataSubsc['id'] = $subscriptionData['subscriptionId'];
  3354.         $dataSubsc['invoiceId'] = $subscriptionData['invoiceId'];
  3355.         $dataSubsc['customer'] = $subscriptionData['customerId'];
  3356.         $dataSubsc['payment_method'] = $subscriptionData['default_payment_method'];
  3357.         $dataSubsc['amount'] = $data["price"]["finalPrice"] ?? $data["price"];
  3358.         $dataSubsc['quantity'] = $data["quantity"];
  3359.         $dataSubsc['recurring'] = ($data["price"]["recurring"] === "monthly") ? "month" 
  3360.         (($data["price"]["recurring"] === "yearly") ? "year" $data["price"]["recurring"]);
  3361.         $dataSubsc['planId'] = $plan->getId();
  3362.         $dataSubsc['status'] = "succeeded";
  3363.         //$this->logger->info("stripe end date",["endDate" => $currentPeriodEnd->format('Y-m-d H:i:s')]);
  3364.         $subscrition->createSubscription($dataSubsc);
  3365.         //$this->logger->info("databse end date",["endDate" => $sub]);
  3366.         // generate rdvurl
  3367.         $name $centre->getName();
  3368.         $city $centre->getCity();
  3369.         $postal $centre->getPostale();
  3370.         $nameSlug strtolower(preg_replace('/[^a-zA-Z0-9]+/''-'trim($name)));
  3371.         $citySlug strtolower(preg_replace('/[^a-zA-Z0-9]+/''-'trim($city)));
  3372.         $baseClient $_ENV['BASE_client'] ?? 'https://default-client-url.com';
  3373.         $urlRdv "{$baseClient}audioprothesiste/{$citySlug}/{$postal}/{$nameSlug}/prise-de-rdvaudioprothesiste-rapide/{$centre->getId()}";
  3374.         if (!$centre->getUrlRdv() || $centre->getUrlRdv() !== $urlRdv) {
  3375.             $centre->setUrlRdv($urlRdv);
  3376.             $entityManager->persist($centre);
  3377.             $entityManager->flush();
  3378.         }
  3379.         // post categorie de contrat cda
  3380.         $quantity $data["quantity"];
  3381.         $contractCategory $entityManager->getRepository(ContractCategory::class)->find(5);
  3382.         $plan $entityManager->getRepository(Plan::class)->find($plan->getId());
  3383.         if ($contractCategory && $plan && $quantity 0) {
  3384.             $specificSubscription = new SpecificSubscription();
  3385.             $specificSubscription->setContractCategory($contractCategory);
  3386.             $specificSubscription->setPlan($plan);
  3387.             $specificSubscription->setQuantity($quantity);
  3388.             $specificSubscription->setCenter($centre);
  3389.             $specificSubscription->setStatus(false);
  3390.             $specificSubscription->setAudio($audio);
  3391.             $entityManager->persist($specificSubscription);
  3392.             $entityManager->flush();
  3393.         }
  3394.         return $this->json([
  3395.             "audioId" => $audio->getId(),
  3396.             "centerId" => $centre->getId(),
  3397.             "name" => $centre->getName(),
  3398.             "imgUrl" => $centre->getImgUrl(),
  3399.             "isRdvDomicile" => $centre->getIsRdvDomicile(),
  3400.             "audio_id" => $centre->getIdGerant()->getId(),
  3401.             "address" => $centre->getAddress(),
  3402.             "postale" => $centre->getPostale(),
  3403.             "city" => $centre->getCity(),
  3404.             "finess" => $centre->getFiness(),
  3405.             "siret" => $centre->getSiret(),
  3406.             "website" => $centre->getWebsite(),
  3407.             "phone" => $centre->getPhone(),
  3408.             "isHandicap" => $centre->getIsHandicap(),
  3409.             //"audio" => $resultAudio->toArray(),
  3410.             "centerId" => $centre->getId(),
  3411.             "audioId" => $audio->getId(),
  3412.             "status" => 200,
  3413.         ]);
  3414.     }
  3415.     
  3416. /**
  3417.      * @Route("/centre/new-inscription-atol", name="postCentreNewInscriptionAtol", methods={"POST"})
  3418.      */
  3419.     public function postCentreNewInscriptionAtol(Request $requestPublicFunction $publicFunctionStripeService $stripeServiceSubscriptionService $subscritionBillingAtolService $invoiceAtol): Response
  3420.     {
  3421.         $data json_decode($request->getContent(), true);
  3422.       //  dd($data);
  3423.       /*  $requestData = [
  3424.             "name" => $data["audio"][0]["name"],
  3425.             "email" => $data["audio"][0]["mail"],
  3426.             "address" => $data["address"],
  3427.             "quantity" => $data["quantity"],
  3428.             "price" => $data["price"]["finalPrice"] ?? $data["price"],
  3429.             "recurring" => "atol",
  3430.             "paymentMethodId" => $data["paymentMethodId"],
  3431.             "offerName" => $data["plan"]["planName"],
  3432.         ];
  3433.         
  3434.        $createSubscription = $stripeService->createSubscriptionStripe($requestData);
  3435.       */
  3436.        // dd($createSubscription);
  3437.         $subscriptionData $data['subscription'];
  3438.         $centre = new Centre();
  3439.         $resultAudio = new ArrayCollection();
  3440.         $gerant null;
  3441.         if($data['gerant'] !== "")
  3442.                {
  3443.                 $gerant $this->getDoctrine()
  3444.                 ->getRepository(Audio::class)
  3445.                 ->find($data['gerant']);
  3446.                }
  3447.         if (isset($data["audio"])) {
  3448.             $entityManager $this->getDoctrine()->getManager();
  3449.             foreach ($data["audio"] as $key=>$audioMap) {
  3450.                // check if audio exist to collect on new center 
  3451.                if($audioMap['registredAudio'] !== "")
  3452.                {
  3453.                    $audio $this->getDoctrine()
  3454.                    ->getRepository(Audio::class)
  3455.                    ->find($audioMap['registredAudio']);
  3456.                    $audioCentre = new AudioCentre();
  3457.                    $audioCentre->setIdAudio($audio);
  3458.                    $audioCentre->setIdCentre($centre);
  3459.                    $audioCentre->setIsConfirmed(true);
  3460.                    $audioCentre->setHoraire($publicFunction->centreHoraire2);
  3461.                    $entityManager->persist($audioCentre);
  3462.                }
  3463.                
  3464.                else {
  3465.                $role $this->getDoctrine()
  3466.                ->getRepository(Role::class)
  3467.                ->find($audioMap["role"]);
  3468.                $audio = new Audio();
  3469.                
  3470.                $audio->setBirthdate(\DateTime::createFromFormat("d/m/Y"$audioMap["birthdate"]));
  3471.                $audio->setRole($role);
  3472.                $audio->setSignupDate(new \DateTime());
  3473.                $audio->setAdeli($data["audio"]["0"]["adeli"]);
  3474.                $audio->setCivilite($data["audio"]["0"]["civilite"]);
  3475.                $audio->setLastName($data["audio"]["0"]["lastname"]);
  3476.                $audio->setName($data["audio"]["0"]["name"]);
  3477.                // set notification by default selected
  3478.                $audio->setConfirmRdvMail(true);
  3479.                $audio->setConfirmRdvSms(true);
  3480.                $audio->setModifRdvMail(true);
  3481.                $audio->setModifRdvSms(true);
  3482.                $audio->setModifNote(true);
  3483.                $audioMailTest $this->getDoctrine()
  3484.                    ->getRepository(Audio::class)
  3485.                    ->findOneBy(['mail' => $audioMap["mail"]]);
  3486.                 /*if ($audioMailTest)
  3487.                 return $this->json([
  3488.                     'message' => "L'adresse e-mail est déjà enregistrée.",
  3489.                     'mail' => $audioMap["mail"],
  3490.                     'code' => "mail_exist",
  3491.                     'status' => 409 
  3492.                 ], 500); */
  3493.                 
  3494.                 $audio->setMail($audioMap["mail"]);
  3495.                 $audioPhoneTest $this->getDoctrine()
  3496.                     ->getRepository(Audio::class)
  3497.                     ->findOneBy(['phone' => $audioMap["phone"]]);
  3498.                 /*if ($audioPhoneTest)
  3499.                 return $this->json([
  3500.                     'message' => 'Le numéro de téléphone est déjà enregistré.',
  3501.                     'phone' => $audioMap["phone"],
  3502.                     'code' => "phone_exist",
  3503.                     'status' => 409 
  3504.                 ], 500); */
  3505.                 
  3506.                 $audio->setMailValid(true);
  3507.                 $audio->setPhone($audioMap["phone"]);
  3508.                 //$audio->setAdeli($audioMap["adeli"]);
  3509.                 if($data["isImported"] !== '')
  3510.                 $audio->setCodeParrainage($data["isImported"]);
  3511.                 $audio->setIsIndie(false);
  3512.                 // set default pass for audio inserted
  3513.                 $audioMap["password"] !== "" $audio->setPassword(password_hash($audioMap["password"], PASSWORD_DEFAULT)) : $audio->setPassword(password_hash("myaudio2023"PASSWORD_DEFAULT));
  3514.                 $audio->setPin($audioMap["pin"]);
  3515.                // $audio->setDescription($audioMap["description"]);
  3516.                 if (isset($audioMap["imgUrl"]))
  3517.                     $audio->setImgUrl($audioMap["imgUrl"]);
  3518.                 $entityManager $this->getDoctrine()->getManager();
  3519.                 foreach ($audioMap["diplome"] as $diplomeObject) {
  3520.                     $diplome $this->getDoctrine()
  3521.                         ->getRepository(Diplome::class)
  3522.                         ->findOneBy(['id' => $diplomeObject["id"]]);
  3523.                     if ($diplome == null) {
  3524.                         /*$audioDiplome = new AudioDiplome();
  3525.                         if(isset($diplomeObject["year"]))
  3526.                         {
  3527.                             if(!empty($diplomeObject["year"]))
  3528.                             {
  3529.                                 $audioDiplome->setYear($diplomeObject["year"]);
  3530.                             }
  3531.                         }
  3532.                         $audioDiplome->setUrl($diplomeObject["url"]);
  3533.                         $audioDiplome->setOther($data['otherdDiplom'][$key]);
  3534.                         $audioDiplome->setIdAudio($audio);
  3535.                         $entityManager->persist($audioDiplome);*/
  3536.                         return $this->json([
  3537.                             'message' => 'Error, no diplome found at this id ' $diplomeObject["id"],
  3538.                             'path' => 'src/Controller/AudioController.php',
  3539.                             "status" => 401
  3540.                         ], 401);
  3541.                     } else {
  3542.                         $audioDiplome = new AudioDiplome();
  3543.                         if(isset($diplomeObject["year"]))
  3544.                         {
  3545.                             if(!empty($diplomeObject["year"]))
  3546.                             {
  3547.                                 $audioDiplome->setYear($diplomeObject["year"]);
  3548.                             }
  3549.                         }
  3550.                         $audioDiplome->setUrl($diplomeObject["url"]);
  3551.                         $audioDiplome->setIdDiplome($diplome);
  3552.                         $audioDiplome->setIdAudio($audio);
  3553.                         $entityManager->persist($audioDiplome);
  3554.                     }
  3555.                 }
  3556.                
  3557.                 
  3558.       
  3559.                // $entityManager->persist($audio);
  3560.                $entityManager->persist($this->createPermanantMotif(60"#FF00FF"$audio,  11));
  3561.                 $entityManager->persist($this->createPermanantMotif(90"#00FFFF"$audio,  21));
  3562.                 $entityManager->persist($this->createPermanantMotif(30"#FFFF00"$audio,  31));
  3563.                 $entityManager->persist($this->createPermanantMotif(60"#FF0000"$audio,  41));
  3564.                 $entityManager->persist($this->createPermanantMotif(60"#FFCC59"$audio692));
  3565.                 $entityManager->persist($this->createPermanantMotif(30"#33B679"$audio1061));
  3566.                 $entityManager->persist($this->createPermanantMotif(30"#F6BF25"$audio1071));
  3567.                 $entityManager->persist($this->createPermanantMotif(30"#E67C73"$audio1081));
  3568.                 $entityManager->persist($this->createPermanantMotif(30"#7886CB"$audio1091));
  3569.               //  $entityManager->persist($this->createPermanantMotif(60, "#FF0000", $audio,  5));
  3570.                 $entityManager->persist($audio);
  3571.                 if ($gerant == null$gerant $audio;
  3572.                 $audioCentre = new AudioCentre();
  3573.                 $audioCentre->setIdAudio($audio);
  3574.                 $audioCentre->setIdCentre($centre);
  3575.                 $audioCentre->setIsConfirmed(true);
  3576.                 $audioCentre->setHoraire($publicFunction->centreHoraire2);
  3577.                 $centerHoliday json_decode($publicFunction->centreHoraire4true);
  3578.                 $audioCentre->setHorairesHoliday($centerHoliday);
  3579.                 $entityManager->persist($audioCentre);
  3580.                 // SEN MAIL NOTIF JUST FOR AUDIOS ADDED NOT FOR GERANT
  3581.                
  3582.                 
  3583.        // $entityManager->flush();
  3584.                
  3585.             }
  3586.                 $resultAudio->add([
  3587.                     "id" => $audio->getId(),
  3588.                     "civilite" => $audio->getCivilite(),
  3589.                     "name" => $audio->getName(),
  3590.                     "lastname" => $audio->getLastname(),
  3591.                     "birthdate" => $audio->getBirthdate(),
  3592.                     "mail" => $audio->getMail(),
  3593.                     "phone" => $audio->getPhone(),
  3594.                     "adeli" => $audio->getAdeli(),
  3595.                     "pin" => $audio->getPin(),
  3596.                     "description" => $audio->getDescription(),
  3597.                     "imgUrl" => $audio->getImgUrl(),
  3598.                 ]);
  3599.             }
  3600.         } else {
  3601.             return new Response(json_encode([
  3602.                 'message' => 'Error, no audio found',
  3603.                 'path' => 'src/Controller/CentreController.php',
  3604.             ]), 404);
  3605.         }
  3606.         // generate color code 
  3607.         $colors = array(
  3608.             "#FFC0CB"// Pink
  3609.             "#FFD700"// Gold
  3610.             "#90EE90"// Light Green
  3611.             "#87CEFA"// Light Sky Blue
  3612.             "#FFA07A"// Light Salmon
  3613.             "#F0E68C"// Khaki
  3614.             "#B0C4DE"// Light Steel Blue
  3615.             "#98FB98"// Pale Green
  3616.             "#FFB6C1"// Light Pink
  3617.             "#ADD8E6"// Light Blue
  3618.             "#FF69B4"// Hot Pink
  3619.             "#FFA500"// Orange
  3620.             "#00FF7F"// Spring Green
  3621.             "#AFEEEE"// Pale Turquoise
  3622.             "#FF8C00"// Dark Orange
  3623.             "#FFE4B5"// Moccasin
  3624.             "#00CED1"// Dark Turquoise
  3625.             "#7FFFD4"// Aquamarine
  3626.             "#FF4500"// Orange Red
  3627.             "#00FA9A"// Medium Spring Green
  3628.             "#FFF0F5"// Lavender Blush
  3629.             "#00BFFF"// Deep Sky Blue
  3630.             "#FF6347"// Tomato
  3631.             "#20B2AA"// Light Sea Green
  3632.             "#FFFF00"// Yellow
  3633.             "#32CD32"// Lime Green
  3634.             "#FFF5EE"// Seashell
  3635.             "#1E90FF"// Dodger Blue
  3636.             "#CD5C5C"// Indian Red
  3637.             "#8FBC8F"// Dark Sea Green
  3638.             "#F0FFFF"// Azure
  3639.             "#4169E1"// Royal Blue
  3640.             "#FF8B00"// Dark Orange
  3641.             "#66CDAA"// Medium Aquamarine
  3642.             "#FFFACD"// Lemon Chiffon
  3643.             "#6495ED"// Cornflower Blue
  3644.             "#FF7F50"// Coral
  3645.             "#00FF00"// Lime
  3646.             "#FAFAD2"// Light Goldenrod Yellow
  3647.             "#87CEEB"// Sky Blue
  3648.             "#DC143C"// Crimson
  3649.             "#2E8B57"// Sea Green
  3650.             "#F5DEB3"// Wheat
  3651.             "#4682B4"// Steel Blue
  3652.             "#CD853F"// Peru
  3653.             "#8A2BE2"// Blue Violet
  3654.             "#D2691E"// Chocolate
  3655.             "#6A5ACD"// Slate Blue
  3656.             "#F5F5DC"// Beige
  3657.             "#7B68EE"// Medium Slate Blue
  3658.         );
  3659.         // short initial 
  3660.         $name $data['name'];
  3661. $words explode(' '$name);
  3662. $initials '';
  3663. foreach ($words as $word) {
  3664.     $initials .= strtoupper(substr($word01));
  3665. }
  3666. $initials strtoupper($initials);
  3667. $shortName substr($initials02);
  3668.         $randomColor $colors[array_rand($colors)];
  3669.         // generate slug url 
  3670.         $slug $this->slugger->slug($data["name"])->lower();
  3671.         $centre->setName(strtoupper($data["name"]));
  3672.         $slugify $this->getDoctrine() 
  3673.         ->getRepository(Centre::class)
  3674.         ->findOneBy(array('slug' => $slug));
  3675.         
  3676.         if($slugify)
  3677.         {
  3678.             $centre->setSlug($slug."-1");
  3679.         }
  3680.         else 
  3681.         {
  3682.             $centre->setSlug($slug);
  3683.         }
  3684.         if (isset($data["imgUrl"]))
  3685.             $centre->setImgUrl($data["imgUrl"]);
  3686.         if (isset($data["finessURL"]))
  3687.         $centre->setFinessUrl($data["finessURL"]);
  3688.         $centre->setIsRdvDomicile($data["isRdvDomicile"]);
  3689.         $centre->setIdGerant($gerant);
  3690.         $centre->setAddress($data["address"]);
  3691.         $centre->setPostale($data["postal"]);
  3692.         $centre->setCity(strtoupper($data["city"]));
  3693.         $centre->setFiness($data["finess"]);
  3694.         $centre->setSocialName($data["companyName"]);
  3695.         $centre->setSiret($data["siret"]);
  3696.         $centre->setInitial($shortName);
  3697.         $centre->setWebsite($data["website"]);
  3698.         $centre->setSignupDate(new \DateTime());
  3699.         $centre->setCalendarColor($randomColor);
  3700.         $centre->setZoneKm(5);
  3701.         
  3702.         // set the galeries for images by default
  3703.         // Define an array of default image URLs
  3704.         $defaultImages = ["by-default-1.jpeg""by-default-2.jpeg""by-default-3.jpeg"];
  3705.         // Iterate through each default image
  3706.        foreach ($defaultImages as $imageUrl) {
  3707.         $centerImage = new CenterImage();
  3708.         $centerImage->setType("image");
  3709.         $centerImage->setUrl($imageUrl);
  3710.         // Associate the center image with the current center
  3711.         $centerImage->setCenter($centre);
  3712.         $entityManager->persist($centerImage);
  3713.          }
  3714.         /*$centrePhoneTest = $this->getDoctrine()
  3715.             ->getRepository(Centre::class)
  3716.             ->findOneBy(['phone' => $data["phone"]]);
  3717.         if ($centrePhoneTest)
  3718.             return $this->json([
  3719.                 'message' => 'Centre phone',
  3720.                 'path' => 'src/Controller/CentreController.php',
  3721.                 "status" => 401
  3722.             ], 401);*/
  3723.         $centre->setPhone($data["phone"]);
  3724.         $centre->setIsHandicap($data["isHandicap"]);
  3725.         $centre->setLongitude($data["longitude"]);
  3726.         $centre->setLatitude($data["latitude"]);
  3727.         $centre->setHoraire($publicFunction->centreHoraire2);
  3728.         $centerHoliday json_decode($publicFunction->centreHoraire4true);
  3729.         $centre->setHorairesHoliday($centerHoliday);
  3730.        
  3731.         $atolAudition $this->getDoctrine()
  3732.             ->getRepository(AtoLauditionPartner::class)->findOneBy(["codeMag" => $data["codeAdherant"]]);
  3733.         $centre->setAtoLauditionPartner($atolAudition);
  3734.         $entityManager $this->getDoctrine()->getManager();
  3735.         
  3736.             
  3737.         $entityManager->persist($centre);
  3738.         // for audio on multi centre creation
  3739.         $accessCentre = new AccessCentre();
  3740.         
  3741.         //  $accessData = $data["access"];
  3742.   
  3743.         $entityManager->flush();
  3744.         // save print setting 
  3745.  
  3746.         $setting = new Setting();
  3747.         $setting->setName($data["name"]);
  3748.         $setting->setAddress($data["address"]);
  3749.         $setting->setPhone($data["phone"]);
  3750.         $setting->setLogoUrl($centre->getImgUrl());
  3751.         $setting->setWebsite($data["website"]);
  3752.         $setting->setFirstname($audio->getName());
  3753.         $setting->setLastname($audio->getLastname());
  3754.         $setting->setEmail($gerant->getMail());
  3755.         $setting->setSeuilCaDroite(true);
  3756.         $setting->setSeuilCaGauche(true);
  3757.         $setting->setSeuilConfortDroite(true);
  3758.         $setting->setSeuilConfortGauche(true);
  3759.         $setting->setSeuilinconfortDroite(true);
  3760.         $setting->setSeuilInConfortGauche(true);
  3761.         $setting->setSeuilCoDroite(true);
  3762.         $setting->setSeuilCoGauche(true);
  3763.         $setting->setSeuilCaMaskingDroite(true);
  3764.         $setting->setSeuilCaMaskingGauche(true);
  3765.         $setting->setSeuilCoMaskingDroite(true);
  3766.         $setting->setSeuilCoMaskingGauche(true);
  3767.        /* $setting->setCasqueDroite(false);
  3768.         $setting->setCasqueGauche(false);
  3769.         $setting->setCasqueBinaural(false);
  3770.         $setting->setChampsLibreDroite(false);
  3771.         $setting->setChampsLibreGauche(false);
  3772.         $setting->setChampsLibreBinaural(false);
  3773.         $setting->setChampsLibreAppDroite(false);
  3774.         $setting->setChampsLibreAppGauche(false);
  3775.         $setting->setChampsLibreAppBinaural(false);*/
  3776.         $setting->setCasqueDroite(true);
  3777.         $setting->setCasqueGauche(true);
  3778.         $setting->setCasqueBinaural(true);
  3779.         $setting->setChampsLibreDroite(true);
  3780.         $setting->setChampsLibreGauche(true);
  3781.         $setting->setChampsLibreBinaural(true);
  3782.         $setting->setChampsLibreAppDroite(true);
  3783.         $setting->setChampsLibreAppGauche(true);
  3784.         $setting->setChampsLibreAppBinaural(true);
  3785.         $setting->setCentre($centre);
  3786.         $entityManager->persist($setting);
  3787.         $entityManager->flush();
  3788.  $tokenString $publicFunction->generateRandomString(30);
  3789.       /*  $params = array(  
  3790.             "lien" =>"{$_ENV['BASE_client']}confirmation_email/{$data["audio"][0]["mail"]}?token={$tokenString}",
  3791.             "nom" =>"",
  3792.             "texte" =>"Veuillez cliquer sur le bouton ci-dessous pour confirmer votre adresse mail",
  3793.             "titre"=> "Confirmer mon email",
  3794.             "bouton"=> "Confirmer mon Email",
  3795.         );
  3796.         $publicFunction->sendEmail($params, $data["audio"][0]["mail"],"myaudio", "Confirmation d'inscription sur My Audio Pro", 122 );
  3797. */
  3798.         $token = new Token();
  3799.         $token->setCreationDate(new DateTime());
  3800.         $token->setToken($tokenString);
  3801.         $token->setMail($audio->getMail());
  3802.         $entityManager $this->getDoctrine()->getManager();
  3803.         $entityManager->persist($token);
  3804.         
  3805.         $entityManager->flush();     
  3806.          // create the sheet of ads
  3807.          $postales $this->getPostalCodes($centre);
  3808.          $dataSheet = [
  3809.              $centre->getId() ?? ''// id centre
  3810.              $centre->getName() ?? '',  // Nom
  3811.              $centre->getCity() ?? '',  // ville
  3812.              $centre->getLongitude() ?? ''// longitude
  3813.              $centre->getLatitude() ?? '',  // lattitude
  3814.              $centre->getZoneKm() ?? '',  // zone km
  3815.              ($centre->getIdGerant()->getLastName() ?? '') . ' ' . ($centre->getIdGerant()->getName() ?? ''),
  3816.              $centre->getAddress() ?? '',
  3817.              $centre->getPostale() ?? '',
  3818.              $postales ?? '' // in case postales is missing
  3819.          ];
  3820.          
  3821.      
  3822.          $this->googleSheetsService->appendToSheetZoneKm($dataSheet'centersByZoneKm');
  3823.                       // create the sheet of marketing
  3824.                       $entityManager $this->getDoctrine()->getManager();
  3825.                       $sheetName 'AIntegrer';
  3826.                       
  3827.                       // Get already existing postals from column D
  3828.                       $existingValues $this->googleSheetsService->getColumnValues($sheetName4); // column D
  3829.                       $existingPostales array_filter($existingValues); 
  3830.                       $existingPostales array_map('strval'$existingPostales); 
  3831.                       
  3832.                       // Use a specific centre instance instead of findAll
  3833.                       
  3834.                       if (!$centre) {
  3835.                           throw new \Exception('Centre not found.');
  3836.                       }
  3837.                       
  3838.                       $rowsToAppend = [];
  3839.                       
  3840.                       $postales $this->getPostalCodesMarket($centre);
  3841.                       $postales array_unique($postales);
  3842.                       
  3843.                       $newPostales array_diff($postales$existingPostales);
  3844.                       $newPostales array_values($newPostales); // reset keys
  3845.                       
  3846.                       if (count($newPostales) > 0) {
  3847.                           $now = (new \DateTime())->format('d/m/Y');
  3848.                           $centerPostal $centre->getPostale();
  3849.                       
  3850.                           foreach ($newPostales as $index => $postal) {
  3851.                               if ($index === 0) {
  3852.                                   $rowsToAppend[] = [false$now$centerPostal$postal];
  3853.                               } else {
  3854.                                   $rowsToAppend[] = [''''''$postal];
  3855.                               }
  3856.                           }
  3857.                       
  3858.                           $this->googleSheetsService->appendToSheetMarketing($rowsToAppend$sheetName);
  3859.                       }
  3860.                       
  3861.          
  3862.        /* $user = [
  3863.             "prenomAudioprothesiste" => $gerant->getName(),
  3864.             "urlDemo" => "https://calendar.google.com/calendar/u/0/appointments/schedules/AcZssZ0Ry72UDE9m8d2IylSycOMQVerlY0jHt1DLWFD6Pso4hg79sQ9nUAlxtZYOPH6wSubDX4vqVQWh",
  3865.         ];
  3866.         // we send parametre for the trait methid
  3867.         $params = $this->emailNotificationDemoService->prepareEmailParams($user);
  3868.         // send email notifcation
  3869.         $this->emailNotificationDemoService->sendEmail($params, $gerant->getMail(), 'Organisez votre Démo personnalisée de My Audio Pro', 143);
  3870.         */
  3871.         // set order datable patient 
  3872.         $this->orderPatient->createOrderPatient($audio);
  3873.         $plan $this->getDoctrine()->getRepository(Plan::class)
  3874.         ->findOneBy(["slug" => $data['plan']["planName"]] );
  3875. //dd($plan);
  3876.         $dataSubsc = [];
  3877.       
  3878.         $dataSubsc['created'] = $subscriptionData['created'];
  3879.         $dataSubsc['currentPeriodStart'] = $subscriptionData['current_period_start'];
  3880.         $dataSubsc['currentPeriodEnd'] = $subscriptionData['current_period_end'];
  3881.         $dataSubsc['centerId'] = $centre->getId();
  3882.         $dataSubsc['audioId'] = $audio->getId();
  3883.         $dataSubsc['id'] = $subscriptionData['subscriptionId'];
  3884.         $dataSubsc['invoiceId'] = $subscriptionData['invoiceId'];
  3885.         $dataSubsc['customer'] = $subscriptionData['customerId'];
  3886.         $dataSubsc['payment_method'] = $subscriptionData['default_payment_method'];
  3887.         $dataSubsc['amount'] = $data["price"]["finalPrice"] ?? $data["price"];
  3888.         $dataSubsc['quantity'] = $data["quantity"];
  3889.         $dataSubsc['recurring'] = ($data["price"]["recurring"] === "monthly") ? "month" 
  3890.         (($data["price"]["recurring"] === "yearly") ? "year" $data["price"]["recurring"]);
  3891.         $dataSubsc['planId'] = $plan->getId();
  3892.         $dataSubsc['status'] = "succeeded";
  3893.                  
  3894.       
  3895.         //$this->logger->info("stripe end date",["endDate" => $currentPeriodEnd->format('Y-m-d H:i:s')]);
  3896.         $subscrition->createSubscription($dataSubsc);
  3897.         //$this->logger->info("databse end date",["endDate" => $sub]);
  3898.         // generate rdvurl
  3899.         $name $centre->getName();
  3900.         $city $centre->getCity();
  3901.         $postal $centre->getPostale();
  3902.         $nameSlug strtolower(preg_replace('/[^a-zA-Z0-9]+/''-'trim($name)));
  3903.         $citySlug strtolower(preg_replace('/[^a-zA-Z0-9]+/''-'trim($city)));
  3904.         $baseClient $_ENV['BASE_client'] ?? 'https://default-client-url.com';
  3905.         $urlRdv "{$baseClient}audioprothesiste/{$citySlug}/{$postal}/{$nameSlug}/prise-de-rdvaudioprothesiste-rapide/{$centre->getId()}";
  3906.         if (!$centre->getUrlRdv() || $centre->getUrlRdv() !== $urlRdv) {
  3907.             $centre->setUrlRdv($urlRdv);
  3908.             $entityManager->persist($centre);
  3909.             $entityManager->flush();
  3910.         }
  3911.          // post categorie de contrat cda
  3912.          $quantity $data["quantity"];
  3913.          $contractCategory $entityManager->getRepository(ContractCategory::class)->find(7);
  3914.          $plan $entityManager->getRepository(Plan::class)->find($plan->getId());
  3915.          if ($contractCategory && $plan && $quantity 0) {
  3916.             
  3917.              $specificSubscription = new SpecificSubscription();
  3918.              $specificSubscription->setContractCategory($contractCategory);
  3919.              $specificSubscription->setPlan($plan);
  3920.              $specificSubscription->setQuantity($quantity);
  3921.              $specificSubscription->setCenter($centre);
  3922.              $specificSubscription->setStatus(false);
  3923.              $specificSubscription->setStripeCustomer($subscriptionData['customerId']);
  3924.              $specificSubscription->setPaymentMethod($subscriptionData['default_payment_method']);
  3925.              $specificSubscription->setPaidAmount($data["price"]["finalPrice"] ?? $data["price"]);
  3926.              $specificSubscription->setAudio($audio);
  3927.              $entityManager->persist($specificSubscription);
  3928.              $entityManager->flush();     
  3929.          }
  3930.         // call docage and create it
  3931.         $this->callAtolDocage($centre);
  3932.         // create invoice we will switch later after signature not here
  3933.         $invoiceAtol->createClient($centre$data);
  3934.  
  3935.         return $this->json([
  3936.             "audioId" => $audio->getId(),
  3937.             "centerId" => $centre->getId(),
  3938.             "name" => $centre->getName(),
  3939.             "imgUrl" => $centre->getImgUrl(),
  3940.             "isRdvDomicile" => $centre->getIsRdvDomicile(),
  3941.             "audio_id" => $centre->getIdGerant()->getId(),
  3942.             "address" => $centre->getAddress(),
  3943.             "postale" => $centre->getPostale(),
  3944.             "city" => $centre->getCity(),
  3945.             "finess" => $centre->getFiness(),
  3946.             "siret" => $centre->getSiret(),
  3947.             "website" => $centre->getWebsite(),
  3948.             "phone" => $centre->getPhone(),
  3949.             "isHandicap" => $centre->getIsHandicap(),
  3950.             //"audio" => $resultAudio->toArray(),
  3951.             "centerId" => $centre->getId(),
  3952.             "audioId" => $audio->getId(),
  3953.             "status" => 200,
  3954.         ]);
  3955.     }
  3956.   /**
  3957.      * @Route("/relance/valide/mail/token", name="relancerValidationMail", methods={"POST"})
  3958.      */
  3959.     public function relancerValidationMail(Request $requestPublicFunction $publicFunction)
  3960.     {
  3961.         $entityManager $this->getDoctrine()->getManager();
  3962.         $data json_decode($request->getContent(), true);
  3963.         $tokenString $publicFunction->generateRandomString(30);
  3964.         $params = array(
  3965.             "lien" => "{$_ENV['BASE_client']}confirmation_email/{$data['mail']}?token={$tokenString}",
  3966.             "nom" => "",
  3967.             "texte" => "Veuillez cliquer sur le bouton ci-dessous pour confirmer votre adresse mail",
  3968.             "titre" => "Confirmer mon email",
  3969.             "bouton" => "Confirmer mon Email",
  3970.         );
  3971.         $publicFunction->sendEmail($params$data['mail'], $data['mail'], "Confirmation d'inscription sur My Audio Pro"122);
  3972.         $token = new Token();
  3973.         $token->setCreationDate(new DateTime());
  3974.         $token->setToken($tokenString);
  3975.         $token->setMail($data['mail']);
  3976.         $entityManager $this->getDoctrine()->getManager();
  3977.         $entityManager->persist($token);
  3978.         $entityManager->flush();
  3979.         return new Response(json_encode([
  3980.             "message" => "Un mail viens de vous etre envoyé",
  3981.             "status" => 200,
  3982.         ]));
  3983.     }
  3984.     /**
  3985.      * @Route("/valider/mail/token", name="validerMailGerant", methods={"POST"})
  3986.      */
  3987.     public function validerMailGerant(Request $request)
  3988.     {
  3989.         // get all data including the client that matches the mail stored in the token
  3990.         $entityManager $this->getDoctrine()->getManager();
  3991.         $data json_decode($request->getContent(), true);
  3992.         if (isset($data["token"])) {
  3993.             $token $this->getDoctrine()
  3994.                 ->getRepository(Token::class)
  3995.                 ->findOneBy(['token' => $data["token"]]);
  3996.             if (!$token) {
  3997.                 return new Response(json_encode([
  3998.                     'message' => 'Erreur',
  3999.                     'path' => 'src/Controller/CentreController.php',
  4000.                 ]), 200);
  4001.             }
  4002.         } else {
  4003.             return new Response(json_encode([
  4004.                 "message" => "Erreur",
  4005.                 "status" => 401,
  4006.             ]), 200);
  4007.         }
  4008.         $audio $this->getDoctrine()
  4009.             ->getRepository(Audio::class)
  4010.             ->findOneBy(['mail' => $token->getMail()]);
  4011.         if (!$audio) {
  4012.             return new Response(json_encode([
  4013.                 'message' => 'Erreur',
  4014.                 'path' => 'src/Controller/CentreController.php',
  4015.             ]), 200);
  4016.         }
  4017.         $start_date $token->getCreationDate();
  4018.         $since_start $start_date->diff(new DateTime());
  4019.         if ($since_start->10) {
  4020.             //success
  4021.             $audio->setMailValid(1);
  4022.             $audio->getAudioCentre()[0]->getIdCentre()->setIsValid(1);
  4023.             $entityManager->remove($token);
  4024.             $entityManager->flush();
  4025.             //TODO envoyer un mail avec lien pro
  4026.             return new Response(json_encode([
  4027.                 "message" => "ok",
  4028.                 "status" => 200,
  4029.             ]));
  4030.             // if it's more than 01 minutes
  4031.         } else {
  4032.             $entityManager->remove($token);
  4033.             $entityManager->flush();
  4034.             return new Response(json_encode([
  4035.                 "message" => "nok",
  4036.                 "status" => 401,
  4037.             ]), 200);
  4038.         }
  4039.     }
  4040.     /**
  4041.      * @Route("/centre/image", name="postCentreImage", methods={"POST"})
  4042.      */
  4043.     public function postCentreImage(Request $requestFileUploader $fileUploader): Response
  4044.     {
  4045.         $image $request->files->get('image');
  4046.         $fileUploader->upload($image"images/setting/");
  4047.         return new Response(json_encode([
  4048.             "imgUrl" => $fileUploader->upload($image"images/centre/"),
  4049.             "status" => 200,
  4050.         ]));
  4051.     }
  4052.     /**
  4053.      * @Route("/centre/image/fData-newinscription", name="postCentreImageByFormDataNewInscription", methods={"POST"})
  4054.      */
  4055.     public function postCentreImageByFormDataNewInscription(Request $requestFileUploader $fileUploader): Response
  4056.     {
  4057.         $newfilename "";
  4058.         $audioFile "";
  4059.         $diplomeFile "";
  4060.         $finessfilename "";
  4061.         $audioId $request->request->get('audioId');
  4062.         $centreId $request->request->get('centreId');
  4063.         $facadeFile $request->files->get('image_facade');
  4064.         $fitnessFile $request->files->get('image_interieur');
  4065.         $profilFile $request->files->get('image_profil');
  4066.         $diplomeFile $request->files->get('image_diplome');
  4067.         $audio =  $this->getDoctrine()
  4068.             ->getRepository(Audio::class)
  4069.             ->find($audioId);
  4070.         $center =  $this->getDoctrine()
  4071.             ->getRepository(Centre::class)
  4072.             ->find($centreId);
  4073.         $entityManager $this->getDoctrine()->getManager();
  4074.         // add image galerie
  4075.         // delete the default image united 
  4076.         if ($facadeFile || $fitnessFile || $diplomeFile) {
  4077.             $oldImages $this->getDoctrine()
  4078.                 ->getRepository(CenterImage::class)
  4079.                 ->findBy(["center" => $center]);
  4080.             if ($oldImages) {
  4081.                 foreach ($oldImages as $image) {
  4082.                     $entityManager->remove($image);
  4083.                 }
  4084.                 $entityManager->flush();
  4085.             }
  4086.         }
  4087.         // Post image centre
  4088.         $facadeFile $request->files->get('image_facade');
  4089.         if ($facadeFile) {
  4090.             $fileArray = [
  4091.                 'name' => $facadeFile->getClientOriginalName(),
  4092.                 'type' => $facadeFile->getMimeType(),
  4093.                 'tmp_name' => $facadeFile->getPathname(),
  4094.                 'error' => $facadeFile->getError(),
  4095.                 'size' => $facadeFile->getSize(),
  4096.             ];
  4097.             $newfilename $fileUploader->uploadFormData($fileArray"images/centre/""images/centres/");
  4098.             $center->setImgUrl($newfilename);
  4099.             $entityManager->persist($center);
  4100.             $image = new CenterImage();
  4101.             $image->setCenter($center);
  4102.             $image->setType('image');
  4103.             if ($newfilename) {
  4104.                 $image->setUrl($newfilename);
  4105.                 $entityManager->persist($image);
  4106.             }
  4107.             $entityManager->flush();
  4108.             $publicImagePath $this->getParameter('kernel.project_dir') . '/public/assets/images/centre/' $newfilename;
  4109.             $assetsImagePath $this->getParameter('kernel.project_dir') . '/assets/images/centre/' $newfilename;
  4110.             if (file_exists($assetsImagePath)) {
  4111.                 copy($assetsImagePath$publicImagePath);
  4112.             }
  4113.             $publicImagePathCtrs $this->getParameter('kernel.project_dir') . '/public/assets/images/centres/' $newfilename;
  4114.             $assetsImagePathCtrs $this->getParameter('kernel.project_dir') . '/assets/images/centres/' $newfilename;
  4115.             if (file_exists($assetsImagePathCtrs)) {
  4116.                 copy($assetsImagePathCtrs$publicImagePathCtrs);
  4117.             }
  4118.         }
  4119.         // Post FINESS centre
  4120.         $fitnessFile $request->files->get('image_interieur');
  4121.         if ($fitnessFile) {
  4122.             $fileArray = [
  4123.                 'name' => $fitnessFile->getClientOriginalName(),
  4124.                 'type' => $fitnessFile->getMimeType(),
  4125.                 'tmp_name' => $fitnessFile->getPathname(),
  4126.                 'error' => $fitnessFile->getError(),
  4127.                 'size' => $fitnessFile->getSize(),
  4128.             ];
  4129.             $finessfilename $fileUploader->uploadFormData($fileArray"images/centres/");
  4130.             $image = new CenterImage();
  4131.             $image->setCenter($center);
  4132.             $image->setType('image');
  4133.             if ($finessfilename) {
  4134.                 $image->setUrl($finessfilename);
  4135.                 $entityManager->persist($image);
  4136.             }
  4137.             $entityManager->flush();
  4138.             $publicImagePath $this->getParameter('kernel.project_dir') . '/public/assets/images/centres/' $finessfilename;
  4139.             $assetsImagePath $this->getParameter('kernel.project_dir') . '/assets/images/centres/' $finessfilename;
  4140.             if (file_exists($assetsImagePath)) {
  4141.                 copy($assetsImagePath$publicImagePath);
  4142.             }
  4143.         }
  4144.         // Post audio profile
  4145.         $profilFile $request->files->get('image_profil');
  4146.         if ($profilFile) {
  4147.             $fileArray = [
  4148.                 'name' => $profilFile->getClientOriginalName(),
  4149.                 'type' => $profilFile->getMimeType(),
  4150.                 'tmp_name' => $profilFile->getPathname(),
  4151.                 'error' => $profilFile->getError(),
  4152.                 'size' => $profilFile->getSize(),
  4153.             ];
  4154.             $audioFilename $fileUploader->uploadFormData($fileArray"images/audio/");
  4155.             $audio->setImgUrl($audioFilename);
  4156.             $entityManager->persist($audio);
  4157.             $publicImagePath $this->getParameter('kernel.project_dir') . '/public/assets/images/audio/' $audioFilename;
  4158.             $assetsImagePath $this->getParameter('kernel.project_dir') . '/assets/images/audio/' $audioFilename;
  4159.             if (file_exists($assetsImagePath)) {
  4160.                 copy($assetsImagePath$publicImagePath);
  4161.             }
  4162.         }
  4163.         // Post audio diplome
  4164.         $diplomeFile $request->files->get('image_diplome');
  4165.         if ($diplomeFile) {
  4166.             $fileArray = [
  4167.                 'name' => $diplomeFile->getClientOriginalName(),
  4168.                 'type' => $diplomeFile->getMimeType(),
  4169.                 'tmp_name' => $diplomeFile->getPathname(),
  4170.                 'error' => $diplomeFile->getError(),
  4171.                 'size' => $diplomeFile->getSize(),
  4172.             ];
  4173.             $d $fileUploader->uploadFormData($fileArray"document/audio/""images/centres/");
  4174.             $audioDiplome = new AudioDiplome();
  4175.             $image = new CenterImage();
  4176.             $image->setCenter($center);
  4177.             $image->setType('image');
  4178.             $newfilename $d;
  4179.             if ($newfilename) {
  4180.                 $image->setUrl($newfilename);
  4181.                 $entityManager->persist($image);
  4182.             }
  4183.             $entityManager->flush();
  4184.         }
  4185.         $entityManager->flush();
  4186.         return new Response(json_encode([
  4187.             "message" => "updated succesfully"
  4188.         ]));
  4189.     }
  4190.     /**
  4191.      * @Route("/centre/image/fData", name="postCentreImageByFormDataInscription", methods={"POST"})
  4192.      */
  4193.     public function postCentreImageByFormDataInscription(Request $requestFileUploader $fileUploader): Response
  4194.     {
  4195.         $newfilename "";
  4196.         $audioFile "";
  4197.         $diplomeFile "";
  4198.         $finessfilename "";
  4199.         $entityManager $this->getDoctrine()->getManager();
  4200.         //post image centre
  4201.         if (isset($_FILES["picCentre"]) && $_FILES["picCentre"]["size"] != 0) {
  4202.             $newfilename $fileUploader->uploadFormData($_FILES["picCentre"], "images/setting/""images/centre/");
  4203.             $publicImagePath $this->getParameter('kernel.project_dir') . '/public/assets/images/centre/' $newfilename;
  4204.             $assetsImagePath $this->getParameter('kernel.project_dir') . '/assets/images/centre/' $newfilename;
  4205.             if (file_exists($assetsImagePath)) {
  4206.                 copy($assetsImagePath$publicImagePath);
  4207.             }
  4208.         } else {
  4209.             $publicImagePath $this->getParameter('kernel.project_dir') . '/public/assets/images/centre/imgOreille.png';
  4210.             $assetsImagePath $this->getParameter('kernel.project_dir') . '/assets/images/centre/imgOreille.png';
  4211.             if (file_exists($assetsImagePath)) {
  4212.                 copy($assetsImagePath$publicImagePath);
  4213.             }
  4214.             $newfilename 'imgOreille.png';
  4215.         }
  4216.         //post FINESS centre
  4217.         if (isset($_FILES["fileFiness"]) && $_FILES["fileFiness"]["size"] != 0) {
  4218.             $finessfilename $fileUploader->uploadFormData($_FILES["fileFiness"], "document/centre/finess");
  4219.         }
  4220.         $audioFile = array();
  4221.         $diplomeFile = array();
  4222.         //post image audio
  4223.         if (isset($_POST['nombreAudio'])) {
  4224.             for ($i 1$i <= $_POST['nombreAudio']; $i++) {
  4225.                 if (isset($_FILES["picAudio" $i]) && $_FILES["picAudio" $i]["size"] != 0) {
  4226.                     $audioFilename $fileUploader->uploadFormData($_FILES["picAudio" $i], "images/audio/");
  4227.                     array_push($audioFile$audioFilename);
  4228.                 }
  4229.                 // post audio diplome
  4230.                 $dip = array();
  4231.                 for ($j 1$j <= 5$j++) {
  4232.                     if (isset($_FILES["fileDilpomeA" $i $j]) && $_FILES["fileDilpomeA" $i $j]["size"] != 0) {
  4233.                         $d $fileUploader->uploadFormData($_FILES["fileDilpomeA" $i $j], "document/audio/");
  4234.                         array_push($dip$d);
  4235.                     }
  4236.                 }
  4237.                 array_push($diplomeFile$dip);
  4238.             }
  4239.         }
  4240.         $entityManager->flush();
  4241.         return new Response(json_encode([
  4242.             "fileName" => $newfilename,
  4243.             "audioFile" => $audioFile,
  4244.             "diplomeFile" => $diplomeFile,
  4245.             "finessfilename" => $finessfilename
  4246.         ]));
  4247.     }
  4248.     /**
  4249.      * @Route("/centre/fData/{id}", name="postCentreImageByFormData", methods={"POST"})
  4250.      */
  4251.     public function postCentreImageByFormData(Centre $centreRequest $requestFileUploader $fileUploader): Response
  4252.     {
  4253.         if (!$request->query->get('token')) {
  4254.             return new Response(json_encode([
  4255.                 "message" => "Pas de token n'a été spécifié",
  4256.                 "status" => 401,
  4257.             ]), 401);
  4258.         }
  4259.         $entityManager $this->getDoctrine()->getManager();
  4260.         /** @var Token */
  4261.         $token $this->getDoctrine()
  4262.             ->getRepository(Token::class)
  4263.             ->findOneBy(['token' => $request->query->get('token'), 'id_audio' => $centre->getIdGerant()]);
  4264.         if (!$token) {
  4265.             return new Response(json_encode([
  4266.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4267.                 "status" => 404,
  4268.             ]), 404);
  4269.         }
  4270.         // get token age
  4271.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4272.         // if the token if older than 7 days
  4273.         if ($dateDiff->7) {
  4274.             $entityManager $this->getDoctrine()->getManager();
  4275.             $entityManager->remove($token);
  4276.             $entityManager->flush();
  4277.             return $this->json([
  4278.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4279.                 'path' => 'src/Controller/AudioController.php',
  4280.                 "status" => 401,
  4281.             ], 401);
  4282.         }
  4283.         if (isset($_FILES["pic"]) && $_FILES["pic"]["size"] != 0) {
  4284.             $newfilename $fileUploader->uploadFormData($_FILES["pic"], "images/centre/");
  4285.             $centre->setImgUrl($newfilename);
  4286.         }
  4287.         $entityManager->flush();
  4288.         return $this->json([
  4289.             "imgUrl" => $centre->getImgUrl(),
  4290.         ]);
  4291.     }
  4292.     /**
  4293.      * @Route("/centre/{id}/access", name="editAccessByCentreByID", methods={"PUT"})
  4294.      */
  4295.     public function editAccessCentreByCentreID(Centre $centreRequest $request)
  4296.     {
  4297.         $entityManager $this->getDoctrine()->getManager();
  4298.         $data json_decode($request->getContent(), true);
  4299.         if (!isset($data['token']))
  4300.             return new Response(json_encode([
  4301.                 "message" => "Pas de token n'a été spécifié",
  4302.                 "status" => 401,
  4303.             ]), 401);
  4304.         $entityManager $this->getDoctrine()->getManager();
  4305.         /** @var Token */
  4306.         $token $this->getDoctrine()
  4307.             ->getRepository(Token::class)
  4308.             ->findOneBy(['token' => $data['token'], 'id_audio' => $centre->getIdGerant()]);
  4309.         if (!$token)
  4310.             return new Response(json_encode([
  4311.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4312.                 "status" => 404,
  4313.             ]), 404);
  4314.         // get token age
  4315.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4316.         // if the token if older than 7 days
  4317.         if ($dateDiff->7) {
  4318.             $entityManager->remove($token);
  4319.             $entityManager->flush();
  4320.             return $this->json([
  4321.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4322.                 'path' => 'src/Controller/ClientController.php',
  4323.                 "status" => 401
  4324.             ], 401);
  4325.         }
  4326.         $centre $this->getDoctrine()
  4327.             ->getRepository(Centre::class)
  4328.             ->findOneBy(['id' => $centre->getId()]);
  4329.         if (!$centre) {
  4330.             return new Response(json_encode([
  4331.                 'message' => 'Error, no Centre found at this id',
  4332.                 'path' => 'src/Controller/CentreController.php',
  4333.             ]));
  4334.         } else {
  4335.             $accessCentre $this->getDoctrine()
  4336.                 ->getRepository(AccessCentre::class)
  4337.                 ->findOneBy(['id_centre' => $centre->getId()]);
  4338.             if (isset($data["Métro"]))
  4339.                 $accessCentre->setMetro($data["Métro"]);
  4340.             if (isset($data["Bus"]))
  4341.                 $accessCentre->setBus($data["Bus"]);
  4342.             if (isset($data["Tram"]))
  4343.                 $accessCentre->setTram($data["Tram"]);
  4344.             if (isset($data["RER"]))
  4345.                 $accessCentre->setRer($data["RER"]);
  4346.             if (isset($data["Parking Public"]))
  4347.                 $accessCentre->setParkingPublic($data["Parking Public"]);
  4348.             if (isset($data["Parking Privé"]))
  4349.                 $accessCentre->setParkingPrivate($data["Parking Privé"]);
  4350.             if (isset($data["Autre"]))
  4351.                 $accessCentre->setOther($data["Autre"]);
  4352.             $entityManager->persist($accessCentre);
  4353.             $entityManager->flush();
  4354.             return new Response(json_encode([
  4355.                 "idCentre" => $centre->getId(),
  4356.                 "metro" => $accessCentre->getMetro(),
  4357.                 "tram" => $accessCentre->getTram(),
  4358.                 "bus" => $accessCentre->getBus(),
  4359.                 "rer" => $accessCentre->getRer(),
  4360.                 "Parking Public" => $accessCentre->getParkingPublic(),
  4361.                 "Parking Privé" => $accessCentre->getParkingPrivate(),
  4362.                 "autre" => $accessCentre->getOther(),
  4363.             ]));
  4364.         }
  4365.     }
  4366.     /**
  4367.      * @Route("/centre/{id}", name="editCentreByID", methods={"PUT"})
  4368.      */
  4369.     public function editCentreByID(Centre $centreRequest $request)
  4370.     {
  4371.         $entityManager $this->getDoctrine()->getManager();
  4372.         $data json_decode($request->getContent(), true);
  4373.         if (!isset($data['token']))
  4374.             return new Response(json_encode([
  4375.                 "message" => "Pas de token n'a été spécifié",
  4376.                 "status" => 401,
  4377.             ]), 401);
  4378.         $entityManager $this->getDoctrine()->getManager();
  4379.         /** @var Token */
  4380.         $token $this->getDoctrine()
  4381.             ->getRepository(Token::class)
  4382.             ->findOneBy(['token' => $data['token'], 'id_audio' => $centre->getIdGerant()]);
  4383.         if (!$token)
  4384.             return new Response(json_encode([
  4385.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4386.                 "status" => 404,
  4387.             ]), 404);
  4388.         // get token age
  4389.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4390.         // if the token if older than 7 days
  4391.         if ($dateDiff->7) {
  4392.             $entityManager->remove($token);
  4393.             $entityManager->flush();
  4394.             return $this->json([
  4395.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4396.                 'path' => 'src/Controller/ClientController.php',
  4397.                 "status" => 401
  4398.             ], 401);
  4399.         }
  4400.         if (isset($data["audio_id"])) {
  4401.             $audio $this->getDoctrine()
  4402.                 ->getRepository(Audio::class)
  4403.                 ->findOneBy(['id' => $data["audio_id"]]);
  4404.             if (!$audio)
  4405.                 return new Response(json_encode([
  4406.                     'message' => 'Error, no Audio found at this id',
  4407.                     'path' => 'src/Controller/AudioController.php',
  4408.                 ]));
  4409.             $centre->setIdGerant($audio);
  4410.         }
  4411.         if (isset($data["name"]))
  4412.             $centre->setName($data["name"]);
  4413.         if (isset($data["imgUrl"]))
  4414.             $centre->setImgUrl($data["imgUrl"]);
  4415.         if (isset($data["isRdvDomicile"]))
  4416.             $centre->setIsRdvDomicile($data["isRdvDomicile"]);
  4417.         if (isset($data["address"]))
  4418.             $centre->setAddress($data["address"]);
  4419.         if (isset($data["numero"]))
  4420.             $centre->setNumero($data["numero"]);
  4421.         if (isset($data["voie"]))
  4422.             $centre->setVoie($data["voie"]);
  4423.         if (isset($data["rue"]))
  4424.             $centre->setRue($data["rue"]);
  4425.         if (isset($data["description"]))
  4426.             $centre->setDescription($data["description"]);
  4427.         if (isset($data["longitude"]))
  4428.             $centre->setLongitude($data["longitude"]);
  4429.         if (isset($data["latitude"]))
  4430.             $centre->setLatitude($data["latitude"]);
  4431.         if (isset($data["postale"]))
  4432.             $centre->setPostale($data["postale"]);
  4433.         if (isset($data["city"]))
  4434.             $centre->setCity($data["city"]);
  4435.         if (isset($data["finess"]))
  4436.             $centre->setFiness($data["finess"]);
  4437.         if (isset($data["siret"]))
  4438.             $centre->setSiret($data["siret"]);
  4439.         if (isset($data["website"]))
  4440.             $centre->setWebsite($data["website"]);
  4441.         if (isset($data["phone"])) {
  4442.             $centrePhoneTest $this->getDoctrine()
  4443.                 ->getRepository(Centre::class)
  4444.                 ->findOneBy(['phone' => $data["phone"]]);
  4445.             if ($centrePhoneTest)
  4446.                 return $this->json([
  4447.                     'message' => 'Ce numéro de téléphone est déjà attribué.',
  4448.                     'path' => 'src/Controller/CentreController.php',
  4449.                     "status" => 401
  4450.                 ], 401);
  4451.             $centre->setPhone($data["phone"]);
  4452.         }
  4453.         if (isset($data["isHandicap"]))
  4454.             $centre->setIsHandicap($data["isHandicap"]);
  4455.         $entityManager->flush();
  4456.         return new Response(json_encode([
  4457.             "id" => $centre->getId(),
  4458.             "audio_id" => $centre->getIdGerant()->getId(),
  4459.             "name" => $centre->getName(),
  4460.             "imgUrl" => $centre->getImgUrl(),
  4461.             "isRdvDomicile" => $centre->getIsRdvDomicile(),
  4462.             "address" => $centre->getAddress(),
  4463.             "numero" => $centre->getNumero(),
  4464.             "voie" => $centre->getVoie(),
  4465.             "rue" => $centre->getRue(),
  4466.             "postale" => $centre->getPostale(),
  4467.             "city" => $centre->getCity(),
  4468.             "finess" => $centre->getFiness(),
  4469.             "siret" => $centre->getSiret(),
  4470.             "website" => $centre->getWebsite(),
  4471.             "phone" => $centre->getPhone(),
  4472.             "isHandicap" => $centre->getIsHandicap(),
  4473.         ]));
  4474.     }
  4475.     public function createPermanantMotif(int $durationString $colorAudio $audioint $id_motifint $type): AudioMotif
  4476.     {
  4477.         $audioMotif = new AudioMotif();
  4478.         $audioMotif->setDuration($duration);
  4479.         $audioMotif->setColor($color);
  4480.         $audioMotif->setIsRDVonline(true);
  4481.         $audioMotif->setIsDeleted(false);
  4482.         $audioMotif->setType($type);
  4483.         // change when that feature will be implemented.
  4484.         $audioMotif->setIdAudio($audio);
  4485.         $motif $this->getDoctrine()
  4486.             ->getRepository(Motif::class)
  4487.             ->findOneBy(['id' => $id_motif]);
  4488.         $audioMotif->setIdMotif($motif);
  4489.         return $audioMotif;
  4490.     }
  4491.     /**
  4492.      * @Route("centre/{id}/dockage/", name="callDocages", methods={"GET"})
  4493.      */
  4494.     public function callDocage(Centre $centre)
  4495.     {
  4496.         $entityManager $this->getDoctrine()->getManager();
  4497.         /** @var Token */
  4498.         $centre $this->getDoctrine()
  4499.             ->getRepository(Centre::class)
  4500.             ->findOneBy(['id' => $centre->getId()]);
  4501.         if ($centre->getIdDockage() != null) {
  4502.             $transaction $this->lancementSignatureDocument($centre$centre->getIdDockage());
  4503.         } else {
  4504.             $idDocage $this->createContactDockage($centre);
  4505.             $transaction $this->lancementSignatureDocument($centre$idDocage);
  4506.         }
  4507.         return new Response(json_encode([
  4508.             "response" => $transaction,
  4509.             "transactionId" => $centre->getTransactionId(),
  4510.             "documentId" => $centre->getDocumentId(),
  4511.             "isSign" => $centre->getIsSign(),
  4512.             "gerant" => $centre->getIdGerant()->getMail()
  4513.         ]));
  4514.     }
  4515.     /**
  4516.      * @Route("centre/{id}/dockage-ATOL/", name="callAtolDocages", methods={"GET"})
  4517.      */
  4518.     public function callAtolDocage(Centre $centre)
  4519.     {
  4520.         $entityManager $this->getDoctrine()->getManager();
  4521.         /** @var Token */
  4522.         $centre $this->getDoctrine()
  4523.             ->getRepository(Centre::class)
  4524.             ->findOneBy(['id' => $centre->getId()]);
  4525.         
  4526.         if($centre->getIdDockage() != null)
  4527.         {
  4528.             $transaction $this->lancementSignatureAtolDocument($centre$centre->getIdDockage());
  4529.            
  4530.         } else {
  4531.             $idDocage $this->createContactAtolDockage($centre);
  4532.             $transaction $this->lancementSignatureAtolDocument($centre$idDocage);
  4533.         }
  4534.     
  4535.         
  4536.         return new Response(json_encode([
  4537.             "response" => $transaction,
  4538.             "transactionId" => $centre->getTransactionId(),
  4539.             "documentId" => $centre->getDocumentId(),
  4540.             "isSign" => $centre->getIsSign(),
  4541.             "gerant" => $centre->getIdGerant()->getMail()
  4542.         ]));
  4543.     }
  4544.     public function createContactDockage($centre){
  4545.             $entityManager $this->getDoctrine()->getManager();
  4546.         $emailGerant $centre->getIdGerant()->getMail();
  4547.         $firstName $centre->getIdGerant()->getName();
  4548.         $lastName $centre->getIdGerant()->getLastName();
  4549.         $address $centre->getAddress();
  4550.         $phone $centre->getIdGerant()->getPhone();
  4551.         $city $centre->getCity();
  4552.         $imgUrl $centre->getImgUrl();
  4553.         $centreName $centre->getName();
  4554.         $postal $centre->getPostale();
  4555.         $codeAdherant "";
  4556.         $civilite $centre->getIdGerant()->getCivilite();
  4557.         if ($civilite == "Monsieur") {
  4558.             $genre 1;
  4559.         } elseif ($civilite "Madame") {
  4560.             $genre 2;
  4561.         } else {
  4562.             $genre 3;
  4563.         }
  4564.         $curl curl_init();
  4565.         curl_setopt_array($curl, array(
  4566.             CURLOPT_URL => 'https://api.docage.com/Contacts',
  4567.             CURLOPT_RETURNTRANSFER => true,
  4568.             CURLOPT_ENCODING => '',
  4569.             CURLOPT_MAXREDIRS => 10,
  4570.             CURLOPT_TIMEOUT => 0,
  4571.             CURLOPT_FOLLOWLOCATION => true,
  4572.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  4573.             CURLOPT_CUSTOMREQUEST => 'POST',
  4574.             CURLOPT_USERPWD => 'contact@myaudio.fr' ":" 'f32c08a2-7f91-4aa4-a88d-1acc5bdd97f3',
  4575.             CURLOPT_POSTFIELDS => '{
  4576.                 "Email": "' $emailGerant '",
  4577.                 "FirstName": "' $firstName '",
  4578.                 "LastName": "' $lastName '",
  4579.                 "Address1": "' $address '",
  4580.                 "Address2": "' $codeAdherant '",
  4581.                 "City": "' $city '",
  4582.                 "State": "",
  4583.                 "ZipCode": "' $postal '",
  4584.                 "Country": "France",
  4585.                 "Notes": "",
  4586.                 "Phone": "' $phone '",
  4587.                 "Mobile": "",
  4588.                 "Company": "' $centreName '",
  4589.                 "Gender": "' $genre '",
  4590.                 "Civility": "",
  4591.                 "ProfilePictureSmall": "' $imgUrl '",
  4592.                 "ProfilePictureMedium": "JVBERi0xLjQNCiXi48 [...] VPRgo=",
  4593.                 "ProfilePictureLarge": "JVBERi0xLjQNCiXi48 [...] VPRgo="
  4594.             }',
  4595.             CURLOPT_HTTPHEADER => array(
  4596.                 'Content-Type: application/json'
  4597.             ),
  4598.         ));
  4599.         $response1 curl_exec($curl);
  4600.         curl_close($curl);
  4601.         $idDocage json_decode($response1);
  4602.         $centre->setIdDockage($idDocage);
  4603.         $entityManager->flush();
  4604.         return $idDocage;
  4605.     }
  4606.     public function createContactAtolDockage($centre){
  4607.             $entityManager $this->getDoctrine()->getManager();
  4608.         $emailGerant $centre->getIdGerant()->getMail();
  4609.         $firstName $centre->getIdGerant()->getName();
  4610.         $lastName $centre->getIdGerant()->getLastName();
  4611.         $address $centre->getAddress();
  4612.         $phone $centre->getIdGerant()->getPhone();
  4613.         $city $centre->getCity();
  4614.         $imgUrl $centre->getImgUrl();
  4615.         $centreName $centre->getName();
  4616.         $postal $centre->getPostale();
  4617.         $codeAdherant $centre->getAtoLauditionPartner()->getCodeMag();
  4618.         $civilite $centre->getIdGerant()->getCivilite();
  4619.         if ($civilite == "Monsieur") {
  4620.             $genre 1;
  4621.         } elseif ($civilite "Madame") {
  4622.             $genre 2;
  4623.         } else {
  4624.             $genre 3;
  4625.         }
  4626.         $curl curl_init();
  4627.         curl_setopt_array($curl, array(
  4628.             CURLOPT_URL => 'https://api.docage.com/Contacts',
  4629.             CURLOPT_RETURNTRANSFER => true,
  4630.             CURLOPT_ENCODING => '',
  4631.             CURLOPT_MAXREDIRS => 10,
  4632.             CURLOPT_TIMEOUT => 0,
  4633.             CURLOPT_FOLLOWLOCATION => true,
  4634.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  4635.             CURLOPT_CUSTOMREQUEST => 'POST',
  4636.             CURLOPT_USERPWD => 'contact@myaudio.fr' ":" 'f32c08a2-7f91-4aa4-a88d-1acc5bdd97f3',
  4637.             CURLOPT_POSTFIELDS => '{
  4638.                 "Email": "' $emailGerant '",
  4639.                 "FirstName": "' $firstName '",
  4640.                 "LastName": "' $lastName '",
  4641.                 "Address1": "' $address '",
  4642.                 "Address2": "' $codeAdherant '",
  4643.                 "City": "' $city '",
  4644.                 "State": "",
  4645.                 "ZipCode": "' $postal '",
  4646.                 "Country": "France",
  4647.                 "Notes": "",
  4648.                 "Phone": "' $phone '",
  4649.                 "Mobile": "",
  4650.                 "Company": "' $centreName '",
  4651.                 "Gender": "' $genre '",
  4652.                 "Civility": "",
  4653.                 "ProfilePictureSmall": "' $imgUrl '",
  4654.                 "ProfilePictureMedium": "JVBERi0xLjQNCiXi48 [...] VPRgo=",
  4655.                 "ProfilePictureLarge": "JVBERi0xLjQNCiXi48 [...] VPRgo="
  4656.             }',
  4657.             CURLOPT_HTTPHEADER => array(
  4658.                 'Content-Type: application/json'
  4659.             ),
  4660.         ));
  4661.         $response1 curl_exec($curl);
  4662.         curl_close($curl);
  4663.         $idDocage json_decode($response1);
  4664.         $centre->setIdDockage($idDocage);
  4665.         $entityManager->flush();
  4666.         return $idDocage;
  4667.     }
  4668.     public function lancementSignatureDocument($centre$idDockage)
  4669.     {
  4670.         $entityManager $this->getDoctrine()->getManager();
  4671.         // $idDockage = $centre->getIdDockage();
  4672.         $curl curl_init();
  4673.         curl_setopt_array($curl, array(
  4674.             CURLOPT_URL => 'https://api.docage.com/Transactions/CreateFullTransaction',
  4675.             CURLOPT_RETURNTRANSFER => true,
  4676.             CURLOPT_ENCODING => '',
  4677.             CURLOPT_MAXREDIRS => 10,
  4678.             CURLOPT_TIMEOUT => 0,
  4679.             CURLOPT_FOLLOWLOCATION => true,
  4680.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  4681.             CURLOPT_CUSTOMREQUEST => 'POST',
  4682.             CURLOPT_USERPWD => 'contact@myaudio.fr' ":" 'f32c08a2-7f91-4aa4-a88d-1acc5bdd97f3',
  4683.             CURLOPT_POSTFIELDS => array('TemplateId' => 'd6fa147a-2bda-437f-8e1f-ce470b59aa06''Client' => $idDockage),
  4684.         ));
  4685.         $response1 curl_exec($curl);
  4686.         $transaction json_decode($response1);
  4687.         $centre->setDocumentId($transaction->TransactionFiles[0]->Id);
  4688.         $centre->setTransactionId($transaction->TransactionFiles[0]->TransactionId);
  4689.         $centre->setIsSign(0);
  4690.         $entityManager->flush();
  4691.         curl_close($curl);
  4692.         return json_decode($response1);
  4693.     }
  4694.     public function lancementSignatureAtolDocument($centre$idDockage)
  4695.     {
  4696.         $entityManager $this->getDoctrine()->getManager();
  4697.        // $idDockage = $centre->getIdDockage();
  4698.         $curl curl_init();
  4699.         curl_setopt_array($curl, array(
  4700.         CURLOPT_URL => 'https://api.docage.com/Transactions/CreateFullTransaction',
  4701.         CURLOPT_RETURNTRANSFER => true,
  4702.         CURLOPT_ENCODING => '',
  4703.         CURLOPT_MAXREDIRS => 10,
  4704.         CURLOPT_TIMEOUT => 0,
  4705.         CURLOPT_FOLLOWLOCATION => true,
  4706.         CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  4707.         CURLOPT_CUSTOMREQUEST => 'POST',
  4708.         CURLOPT_USERPWD => 'contact@myaudio.fr' ":" 'f32c08a2-7f91-4aa4-a88d-1acc5bdd97f3',
  4709.         CURLOPT_POSTFIELDS => array('TemplateId' => 'aac5b1ca-fa3d-438d-9e1d-e45d7032281f''Client' => $idDockage),
  4710.         ));
  4711.         $response1 curl_exec($curl);
  4712.         $transaction json_decode($response1);
  4713.         $centre->setDocumentId($transaction->TransactionFiles[0]->Id);
  4714.         $centre->setTransactionId($transaction->TransactionFiles[0]->TransactionId);
  4715.         $centre->setIsSign(0);
  4716.         $entityManager->flush();
  4717.         curl_close($curl);
  4718.         return json_decode($response1);
  4719.     }
  4720.     
  4721.     /**
  4722.      * @Route("centre/{id}/relance/dockage", name="relanceDocage", methods={"GET"})
  4723.      */
  4724.     public function relanceDocage(Centre $centre)
  4725.     {
  4726.         $output null;
  4727.         $retval null;
  4728.         //exec("curl --location --request GET 'https://api.docage.com/SendReminders/".$centre->getTransactionId()."'", $output, $retval);
  4729.         $curl curl_init();
  4730.         curl_setopt_array($curl, array(
  4731.             CURLOPT_URL => 'https://api.docage.com/SendReminders/' $centre->getTransactionId(),
  4732.             CURLOPT_RETURNTRANSFER => true,
  4733.             CURLOPT_ENCODING => '',
  4734.             CURLOPT_MAXREDIRS => 10,
  4735.             CURLOPT_TIMEOUT => 0,
  4736.             CURLOPT_FOLLOWLOCATION => true,
  4737.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  4738.             CURLOPT_CUSTOMREQUEST => 'GET',
  4739.             CURLOPT_USERPWD => 'contact@myaudio.fr' ":" 'f32c08a2-7f91-4aa4-a88d-1acc5bdd97f3',
  4740.         ));
  4741.         $response1 curl_exec($curl);
  4742.         curl_close($curl);
  4743.         return new Response(json_encode([
  4744.             "response" => $response1,
  4745.             "transactionId" => $centre->getTransactionId(),
  4746.             "documentId" => $centre->getDocumentId(),
  4747.             "isSign" => $centre->getIsSign(),
  4748.         ]));
  4749.     }
  4750.     /**
  4751.      * @Route("centre/{id}/get/document", name="getDocumentDocage", methods={"GET"})
  4752.      */
  4753.     public function getDocumentDocage(Centre $centre)
  4754.     {
  4755.         $output null;
  4756.         $retval null;
  4757.         $curl curl_init();
  4758.         curl_setopt_array($curl, array(
  4759.             CURLOPT_URL => 'https://api.docage.com/TransactionFiles/Download/' $centre->getDocumentId(),
  4760.             CURLOPT_RETURNTRANSFER => true,
  4761.             CURLOPT_ENCODING => '',
  4762.             CURLOPT_MAXREDIRS => 10,
  4763.             CURLOPT_TIMEOUT => 0,
  4764.             CURLOPT_FOLLOWLOCATION => true,
  4765.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  4766.             CURLOPT_CUSTOMREQUEST => 'GET',
  4767.             CURLOPT_USERPWD => 'contact@myaudio.fr' ":" 'f32c08a2-7f91-4aa4-a88d-1acc5bdd97f3',
  4768.         ));
  4769.         $response1 curl_exec($curl);
  4770.         curl_close($curl);
  4771.         $r str_replace('"'''$response1);
  4772.         $pdf_decoded base64_decode($r);
  4773.         //Write data back to pdf file
  4774.         $projectDir $this->getParameter('kernel.project_dir');
  4775.         //$pdfFilePath = $projectDir . '/assets/partner/facture' . $invoice->getToken() . '.pdf';
  4776.         $pdf fopen($projectDir '/assets/pdf/cga_' $centre->getId() . '.pdf''w');
  4777.         fwrite($pdf$pdf_decoded);
  4778.         //close output file
  4779.         fclose($pdf);
  4780.         return new Response($response1);
  4781.     }
  4782.     /**
  4783.      * @Route("centre/{id}/checkisSign", name="checkValid", methods={"GET"})
  4784.      */
  4785.     public function checkisSign(Centre $centre)
  4786.     {
  4787.         $entityManager $this->getDoctrine()->getManager();
  4788.         $curl curl_init();
  4789.         curl_setopt_array($curl, array(
  4790.             CURLOPT_URL => 'https://api.docage.com/Transactions/Status/' $centre->getTransactionId(),
  4791.             CURLOPT_RETURNTRANSFER => true,
  4792.             CURLOPT_ENCODING => '',
  4793.             CURLOPT_MAXREDIRS => 10,
  4794.             CURLOPT_TIMEOUT => 0,
  4795.             CURLOPT_FOLLOWLOCATION => true,
  4796.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  4797.             CURLOPT_CUSTOMREQUEST => 'GET',
  4798.             CURLOPT_USERPWD => 'contact@myaudio.fr' ":" 'f32c08a2-7f91-4aa4-a88d-1acc5bdd97f3',
  4799.         ));
  4800.         $response1 curl_exec($curl);
  4801.         curl_close($curl);
  4802.         if ($response1 == "Done") {
  4803.             $centre->setIsSign(1);
  4804.             $entityManager->flush();
  4805.         }
  4806.         return new Response($centre->getIsSign());
  4807.     }
  4808.     /**
  4809.      * @Route("/mandat/create", name="mandatCreate", methods={"GET"})
  4810.      */
  4811.     public function sendToCreateMandat(Request $request)
  4812.     {
  4813.         //live : live_jk-8FCTbZ0ydYSvXNeT4P8MCGO__VM9Vb2c1-teG
  4814.         $token $request->query->get('token');
  4815.         $centreId $request->query->get('centre');
  4816.         $access_token "{$_ENV['goCardless_api']}";
  4817.         $client = new \GoCardlessPro\Client([
  4818.             'access_token' => $access_token,
  4819.             'environment'  => \GoCardlessPro\Environment::LIVE,
  4820.         ]);
  4821.         $centre $this->getDoctrine()
  4822.             ->getRepository(Centre::class)
  4823.             ->findOneBy(['id' => $centreId]);
  4824.         $gerant $centre->getIdGerant();
  4825.         $redirectFlow $client->redirectFlows()->create([
  4826.             "params" => [
  4827.                 // This will be shown on the payment pages
  4828.                 "description" => "Abonnement My Audio",
  4829.                 // Not the access token
  4830.                 "session_token" => $token,
  4831.                 "success_redirect_url" => "{$_ENV['BASE_logiciel']}mandat/loading",
  4832.                 // Optionally, prefill customer details on the payment page
  4833.                 "prefilled_customer" => [
  4834.                     "given_name" => $gerant->getName(),
  4835.                     "family_name" => $gerant->getLastname(),
  4836.                     "email" => $gerant->getMail(),
  4837.                     "address_line1" => $centre->getAddress(),
  4838.                     "city" => $centre->getCity(),
  4839.                     "postal_code" => strval($centre->getPostale()),
  4840.                 ],
  4841.             ]
  4842.         ]);
  4843.         return $this->json([
  4844.             'idflow' => $redirectFlow->id,
  4845.             'url' => $redirectFlow->redirect_url,
  4846.             'redirect' => $redirectFlow
  4847.         ]);
  4848.     }
  4849.     /**
  4850.      * @Route("/mandat/validate", name="mandatValidate", methods={"GET"})
  4851.      */
  4852.     public function validateMandat(Request $request)
  4853.     {
  4854.         $entityManager $this->getDoctrine()->getManager();
  4855.         $token $request->query->get('token');
  4856.         $url $request->query->get('url');
  4857.         $centreId $request->query->get('centre');
  4858.         $access_token "{$_ENV['goCardless_api']}";
  4859.         $client = new \GoCardlessPro\Client([
  4860.             'access_token' => $access_token,
  4861.             'environment'  => \GoCardlessPro\Environment::LIVE,
  4862.         ]);
  4863.         $redirectFlow $client->redirectFlows()->complete(
  4864.             $url//The redirect flow ID from above.
  4865.             ["params" => ["session_token" => $token]]
  4866.         );
  4867.         $customers $client->customers()->list()->records;
  4868.         $mandats $client->mandates()->list();
  4869.         $confirmation $redirectFlow->confirmation_url;
  4870.         $client $this->getDoctrine()
  4871.             ->getRepository(Centre::class)
  4872.             ->findOneBy(['id' => $centreId]);
  4873.         $client->setMandat($redirectFlow->links->mandate);
  4874.         $entityManager->flush();
  4875.         return $this->json([
  4876.             'confirmation' => $confirmation,
  4877.             'clients' => $customers,
  4878.             'mandats' => $mandats,
  4879.             'mandatId' => $redirectFlow->links->mandate
  4880.         ]);
  4881.     }
  4882.     /**
  4883.      * @Route("/centre/{id}/mandat/", name="getCentreMandatById", methods={"GET"})
  4884.      */
  4885.     public function getCentreMandatGyId(Centre $centreRequest $request)
  4886.     {
  4887.         $mandat $centre->getMandat();
  4888.         if ($mandat != null) {
  4889.             $client = new \GoCardlessPro\Client(array(
  4890.                 'access_token' => "{$_ENV['goCardless_api']}",
  4891.                 'environment'  => \GoCardlessPro\Environment::LIVE,
  4892.             ));
  4893.             $infoMandat =  $client->mandates()->get($mandat);
  4894.         } else {
  4895.             $infoMandat "";
  4896.         }
  4897.         return $this->json([
  4898.             'mandat' => $infoMandat,
  4899.         ]);
  4900.     }
  4901.     /**
  4902.      * @Route("/checkFacturation/centres", name="checkFacturation", methods={"GET"})
  4903.      */
  4904.     public function checkFacturation()
  4905.     {
  4906.         $centres $this->getDoctrine()
  4907.             ->getRepository(Centre::class)
  4908.             ->findAll();
  4909.         foreach ($centres as $centre) {
  4910.             $inscription $centre->getSignupDate();
  4911.             $origin = new DateTime(date_format($inscription'Y-m-d'));
  4912.             $target = new DateTime('now');
  4913.             $interval $origin->diff($target);
  4914.             $month $interval->format('%m');
  4915.             if ($month 0) {
  4916.                 $dayNow $target->format("d");
  4917.                 $day $origin->format("d");
  4918.                 if ($day == $dayNow) {
  4919.                     $this->getFacturationByCentre($centre);
  4920.                 }
  4921.             }
  4922.         }
  4923.         return $this->json([
  4924.             'mandat' => $month,
  4925.         ]);
  4926.     }
  4927.     /**
  4928.      * @Route("/facturation/centre/{id}", name="getFacturationByCentre", methods={"GET"})
  4929.      */
  4930.     public function getFacturationByCentre(Centre $centre)
  4931.     {
  4932.         $entityManager $this->getDoctrine()->getManager();
  4933.         /**** ABONNEMENT ****/
  4934.         $dateInscription $centre->getSignupDate();
  4935.         $origin = new DateTime(date_format($dateInscription'Y-m-d'));
  4936.         $target = new DateTime('now');
  4937.         $interval $origin->diff($target);
  4938.         $month $interval->format('%m');
  4939.         if (intval($month) > 12) {
  4940.             $abonnement 49.90;
  4941.             $reduction 0.00;
  4942.         } elseif (intval($month) == 1) {
  4943.             $abonnement 49.90;
  4944.             $reduction 59.88;
  4945.         } else {
  4946.             $abonnement 39.90;
  4947.             $reduction 12.00;
  4948.         }
  4949.         /**** NOMBRE D'AUDIOS ****/
  4950.         $audios $this->getDoctrine()
  4951.             ->getRepository(AudioCentre::class)
  4952.             ->findBy(['id_centre' => $centre]);
  4953.         $audioSupplementaire count($audios) - 1;
  4954.         $audioAbonnement 19.90 $audioSupplementaire;
  4955.         $jour date("Y-m-d");
  4956.         $dateFin = new DateTime($jour);
  4957.         $dateDebut  strtotime($jour "- 1 months");
  4958.         $dateDebut date("Y-m-d"$dateDebut);
  4959.         $dateDebut = new DateTime($dateDebut);
  4960.         /**** MY RDV ****/
  4961.         $myrdv 0;
  4962.         $rdvs $this->getDoctrine()
  4963.             ->getRepository(Rdv::class)
  4964.             ->findRDVCentreBetweenDateWithoutTest($dateDebut$dateFin$centre->getID());
  4965.         $myrdv $myrdv + (50 count($rdvs));
  4966.         /**** MY RDV ADVANCED ****/
  4967.         $myRdvAdvanced 0;
  4968.         $rdvsA $this->getDoctrine()
  4969.             ->getRepository(Rdv::class)
  4970.             ->findRDVCentreBetweenDateWithTestId($dateDebut$dateFin$centre->getID());
  4971.         $myRdvAdvanced $myRdvAdvanced + (100 count($rdvsA));
  4972.         /**** MY LEAD ****/
  4973.         $mylead 0;
  4974.         $nbMyLead 0;
  4975.         $rdvsCanceled $this->getDoctrine()
  4976.             ->getRepository(Rdv::class)
  4977.             ->findCanceledRdvCentreBetweenDateWithoutTest($dateDebut$dateFin$centre->getID());
  4978.         foreach ($rdvsCanceled as $rdvc) {
  4979.             if (!is_null($rdvc->getIdClient())) {
  4980.                 $rdvClient $this->getDoctrine()
  4981.                     ->getRepository(Rdv::class)
  4982.                     ->findRDVLeadByClient($dateDebut$centre->getID(), $rdvc->getIdClient()->getID());
  4983.                 if (count($rdvClient) == 0) {
  4984.                     $mylead $mylead 35;
  4985.                     $nbMyLead $nbMyLead 1;
  4986.                 }
  4987.             }
  4988.         }
  4989.         /**** MY LEAD ADVANCED****/
  4990.         $myleadAdvanced 0;
  4991.         $nbMyLeadAdvanced 0;
  4992.         $rdvsCanceledA $this->getDoctrine()
  4993.             ->getRepository(Rdv::class)
  4994.             ->findCanceledRdvCentreBetweenDateWithTest($dateDebut$dateFin$centre->getID());
  4995.         foreach ($rdvsCanceledA as $rdvc) {
  4996.             if (!is_null($rdvc->getIdClient())) {
  4997.                 $rdvClient $this->getDoctrine()
  4998.                     ->getRepository(Rdv::class)
  4999.                     ->findRDVLeadByClient($dateDebut$centre->getID(), $rdvc->getIdClient()->getID());
  5000.                 if (count($rdvClient) == 0) {
  5001.                     $myleadAdvanced $myleadAdvanced 35;
  5002.                     $nbMyLeadAdvanced $nbMyLeadAdvanced 1;
  5003.                 }
  5004.             }
  5005.         }
  5006.         // Recuperation de l'ID vos facture ou creation 
  5007.         if (!is_null($centre->getFactureId())) {
  5008.             $factureId $centre->getFactureId();
  5009.         } else {
  5010.             $curl curl_init();
  5011.             curl_setopt_array($curl, array(
  5012.                 CURLOPT_URL => 'https://myaudio.vosfactures.fr/clients.json',
  5013.                 CURLOPT_RETURNTRANSFER => true,
  5014.                 CURLOPT_ENCODING => '',
  5015.                 CURLOPT_MAXREDIRS => 10,
  5016.                 CURLOPT_TIMEOUT => 0,
  5017.                 CURLOPT_FOLLOWLOCATION => true,
  5018.                 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  5019.                 CURLOPT_CUSTOMREQUEST => 'POST',
  5020.                 CURLOPT_POSTFIELDS => '{ 
  5021.                 "api_token": "pRHakmigmSJuVSYbcBS",
  5022.                 "client": { 
  5023.                     "name":"' $centre->getName() . '", 
  5024.                     "city": "' $centre->getCity() . '", 
  5025.                     "country": "France", 
  5026.                     "email": "' $centre->getIdGerant()->getMail() . '", 
  5027.                     "post_code": "' $centre->getPostale() . '", 
  5028.                     "street":"' $centre->getAddress() . '",
  5029.                     "phone": "' $centre->getPhone() . '"
  5030.                 }
  5031.             }',
  5032.                 CURLOPT_HTTPHEADER => array(
  5033.                     'Accept: application/json',
  5034.                     'Content-Type: application/json'
  5035.                 ),
  5036.             ));
  5037.             $response1 curl_exec($curl);
  5038.             $rep =  json_decode($response1);
  5039.             $factureId $rep->{'id'};
  5040.             $centre->setFactureId($rep->{'id'});
  5041.             $entityManager->flush();
  5042.         }
  5043.         // Création de la nouvelle facture 
  5044.         $curl curl_init();
  5045.         curl_setopt_array($curl, array(
  5046.             CURLOPT_URL => 'https://myaudio.vosfactures.fr/invoices.json',
  5047.             CURLOPT_RETURNTRANSFER => true,
  5048.             CURLOPT_ENCODING => '',
  5049.             CURLOPT_MAXREDIRS => 10,
  5050.             CURLOPT_TIMEOUT => 0,
  5051.             CURLOPT_FOLLOWLOCATION => true,
  5052.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  5053.             CURLOPT_CUSTOMREQUEST => 'POST',
  5054.             CURLOPT_POSTFIELDS => '{ 
  5055.               "api_token": "pRHakmigmSJuVSYbcBS",
  5056.               "invoice": {
  5057.                 "department_id": 937362, 
  5058.                 "client_id": ' intval($centre->getFactureId()) . ',
  5059.                 "test": true,
  5060.                 "discount_kind":"amount",
  5061.                 "show_discount":true,
  5062.                 "positions":[
  5063.                     {"product_id": 102520343, "quantity":1, "discount": "' $reduction '"}, 
  5064.                     {"product_id": 103129798, "quantity": ' $audioSupplementaire '},
  5065.                     {"product_id": 102520426, "quantity": ' $nbMyLead '},
  5066.                     {"product_id": 102520439, "quantity": ' $nbMyLeadAdvanced '},
  5067.                     {"product_id": 102520392, "quantity": ' count($rdvs) . '},
  5068.                     {"product_id": 102520413, "quantity": ' count($rdvsA) . '}
  5069.                 ]
  5070.             }
  5071.           }',
  5072.             CURLOPT_HTTPHEADER => array(
  5073.                 'Accept: application/json',
  5074.                 'Content-Type: application/json'
  5075.             ),
  5076.         ));
  5077.         $fact curl_exec($curl);
  5078.         $fact =  json_decode($fact);
  5079.         $factId $fact->{'id'};
  5080.         $tokenId $fact->{'token'};
  5081.         $numeroFact $fact->{'number'};
  5082.         $montantHT $fact->{'price_net'};
  5083.         $montantTTC $fact->{'price_gross'};
  5084.         $dateFact $target;
  5085.         //POST FACTURE 
  5086.         $facture = new Factures();
  5087.         $facture->setId(intval($factId));
  5088.         $facture->setToken($tokenId);
  5089.         $facture->setDate($dateFact);
  5090.         $facture->setCentre($centre);
  5091.         $facture->setNumero($numeroFact);
  5092.         $facture->setPrixHT($montantHT);
  5093.         $facture->setPrixTTC($montantTTC);
  5094.         $entityManager->persist($facture);
  5095.         $entityManager->flush();
  5096.         $centimes floatval($montantTTC) * 100;
  5097.         //Envoi a Gocardless
  5098.         if (!is_null($centre->getMandat())) {
  5099.             $access_token "{$_ENV['goCardless_api']}";
  5100.             $client = new \GoCardlessPro\Client([
  5101.                 'access_token' => $access_token,
  5102.                 'environment'  => \GoCardlessPro\Environment::LIVE,
  5103.             ]);
  5104.             $redirectFlow $client->payments()->create([
  5105.                 "params" => [
  5106.                     "amount" => $centimes,
  5107.                     "currency" => "EUR",
  5108.                     "metadata" => [
  5109.                         "order_dispatch_date" => date("Y-m-d")
  5110.                     ],
  5111.                     "links" => [
  5112.                         "mandate" => $centre->getMandat()
  5113.                     ]
  5114.                 ]
  5115.             ]);
  5116.             $paiementId $redirectFlow->{'api_response'}->{'body'}->{'payments'}->{'id'};
  5117.             $facture->setPaiement($paiementId);
  5118.             $entityManager->persist($facture);
  5119.             $entityManager->flush();
  5120.         } else {
  5121.             $paiementId 0;
  5122.             $redirectFlow "";
  5123.         }
  5124.         return $this->json([
  5125.             'centre' => $centre->getID(),
  5126.             'reduction' => $reduction,
  5127.             'mandat' =>  $interval->format('%m mois'),
  5128.             'audio' => count($audios),
  5129.             'date_debut' => $dateDebut,
  5130.             'date_fin' => $dateFin,
  5131.             'MyRDV' => $myrdv,
  5132.             'MyRDVAdvanced' => $myRdvAdvanced,
  5133.             'MyLead' => $mylead,
  5134.             'MyLeadAdvanced' => $myleadAdvanced,
  5135.             'idFact' => $factureId,
  5136.             'factureId' => $factId,
  5137.             'tokenFact' => $tokenId,
  5138.             'dateFacture' => $dateFact,
  5139.             'numeroFact' => $numeroFact,
  5140.             'paiementId' => $paiementId,
  5141.             'redirect' => $redirectFlow
  5142.         ]);
  5143.     }
  5144.     /**
  5145.      * @Route("/getPaiement/", name="getPaiement", methods={"GET"})
  5146.      */
  5147.     public function getPaiement()
  5148.     {
  5149.         //Envoi a Gocardless
  5150.         $access_token "{$_ENV['goCardless_api']}";
  5151.         $client = new \GoCardlessPro\Client([
  5152.             'access_token' => $access_token,
  5153.             'environment'  => \GoCardlessPro\Environment::LIVE,
  5154.         ]);
  5155.         $redirectFlow $client->payments()->get("PM004RNN4TTSXJ");
  5156.         return $this->json([
  5157.             'redirect' => $redirectFlow
  5158.         ]);
  5159.     }
  5160.     /**
  5161.      * @Route("/gerantCenter/{id}/", name="getGerantCentre", methods={"GET","HEAD"})
  5162.      */
  5163.     public function getGerantCentres(Request $requestAudio $audio)
  5164.     {
  5165.         if (!$request->query->get('token')) {
  5166.             return new Response(json_encode([
  5167.                 "message" => "Pas de token n'a été spécifié",
  5168.                 "status" => 401,
  5169.             ]), 401);
  5170.         }
  5171.         $entityManager $this->getDoctrine()->getManager();
  5172.         $audioCentre $this->getDoctrine()
  5173.             ->getRepository(Centre::class)->findBy(['id_gerant' => $audio->getId()]);
  5174.         //dd($audioCentre);
  5175.         /** @var Token */
  5176.         $token $this->getDoctrine()
  5177.             ->getRepository(Token::class)
  5178.             ->findOneBy(['token' => $request->query->get('token'), 'id_audio' => $audio]);
  5179.         if (!$token) {
  5180.             return new Response(json_encode([
  5181.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5182.                 "status" => 404,
  5183.             ]), 404);
  5184.         }
  5185.         // get token age
  5186.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5187.         // if the token if older than 7 days
  5188.         if ($dateDiff->7) {
  5189.             $entityManager->remove($token);
  5190.             $entityManager->flush();
  5191.             return $this->json([
  5192.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5193.                 'path' => 'src/Controller/ClientController.php',
  5194.                 "status" => 401,
  5195.             ], 401);
  5196.         }
  5197.         // get plan 
  5198.         $planAudio $this->getDoctrine()
  5199.             ->getRepository(Subscription::class)
  5200.             ->findOneBy(['audio' => $audio->getId()]);
  5201.         if ($planAudio) {
  5202.             $planQuanity $planAudio->getPlan()->getId();
  5203.         } else {
  5204.             $planAudio $this->getDoctrine()
  5205.                 ->getRepository(SpecificSubscription::class)
  5206.                 ->findOneBy(['audio' => $audio->getId()]);
  5207.             if ($planAudio) {
  5208.                 $planQuanity $planAudio->getPlan()->getId();
  5209.             } else {
  5210.                 $planAudio $this->getDoctrine()
  5211.                     ->getRepository(PartnerSubscription::class)
  5212.                     ->findOneBy(['audio' => $audio->getId()]);
  5213.                 $planQuanity $planAudio->getPlan()->getId();
  5214.             }
  5215.         }
  5216.         if ($audio->getIsPartner()) {
  5217.             // get plan 
  5218.             $planAudio $this->getDoctrine()
  5219.                 ->getRepository(PartnerSubscription::class)
  5220.                 ->findOneBy(['audio' => $audio->getId()]);
  5221.         } else {
  5222.             // get plan 
  5223.             $planAudio $this->getDoctrine()
  5224.                 ->getRepository(Subscription::class)
  5225.                 ->findOneBy(['audio' => $audio->getId()]);
  5226.             if (!$planAudio) {
  5227.                 $planAudio $this->getDoctrine()
  5228.                     ->getRepository(SpecificSubscription::class)
  5229.                     ->findOneBy(['audio' => $audio->getId()]);
  5230.             }
  5231.         }
  5232.         if (!$planAudio)
  5233.             return $this->json([
  5234.                 "message" => "Plan nexiste pas",
  5235.                 "status" => 404,
  5236.             ]);
  5237.         if ($planAudio) {
  5238.             $planQuanity $planAudio->getQuantity();
  5239.             $planAmount $planAudio->getPaidAmount();
  5240.             $planName $planAudio->getPlan()->getName();
  5241.             $planInterval $planAudio->getPlanInterval();
  5242.             $planId $planAudio->getPlan()->getId();
  5243.         }
  5244.         $centers array_map(function ($centre) {
  5245.             return [
  5246.                 "id" => $centre->getId(),
  5247.                 "address" => $centre->getAddress(),
  5248.                 "city" => $centre->getCity(),
  5249.                 "name" => $centre->getName(),
  5250.                 "website" => $centre->getWebsite(),
  5251.                 "isSign" => $centre->getIsSign(),
  5252.                 'urlRdv' => $centre->getUrlRdv()
  5253.             ];
  5254.         }, $audioCentre);
  5255.         return $this->json([
  5256.             "centers" => $centers,
  5257.             "planId" => $planId,
  5258.             "planQuantity" => $planQuanity,
  5259.             "planAmount" => $planAmount,
  5260.             "planName" => $planName,
  5261.             "planInterval" => $planInterval,
  5262.             "status" => 200
  5263.         ]);
  5264.     }
  5265.     /**
  5266.      * @Route("/center/add", name="postCenterAudio", methods={"POST"})
  5267.      */
  5268.     public function postCenterPro(Request $requestPublicFunction $publicFunctionStripeService $stripeService): Response
  5269.     {
  5270.         $data json_decode($request->getContent(), true);
  5271.         $audioCheckTel $this->getDoctrine()
  5272.             ->getRepository(Centre::class)
  5273.             ->findOneBy(["phone" => $data['phone']]);
  5274.         if ($audioCheckTel && !$data['isSamePhone']) {
  5275.             return $this->json([
  5276.                 "message" => "Le numéro de téléphone existe déjà",
  5277.                 "status" => 404,
  5278.             ]);
  5279.         }
  5280.         if (!isset($data["token"])) {
  5281.             return new Response(json_encode([
  5282.                 "message" => "Pas de token n'a été spécifié",
  5283.                 "status" => 401,
  5284.             ]), 401);
  5285.         }
  5286.         $entityManager $this->getDoctrine()->getManager();
  5287.         /** @var Token */
  5288.         $token $this->getDoctrine()
  5289.             ->getRepository(Token::class)
  5290.             ->findOneBy(['token' => $data["token"], 'id_audio' => $data["gerant"]]);
  5291.         if (!$token) {
  5292.             return new Response(json_encode([
  5293.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5294.                 "status" => 404,
  5295.             ]), 404);
  5296.         }
  5297.         // get token age
  5298.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5299.         // if the token if older than 7 days
  5300.         if ($dateDiff->7) {
  5301.             $entityManager->remove($token);
  5302.             $entityManager->flush();
  5303.             return $this->json([
  5304.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5305.                 'path' => 'src/Controller/ClientController.php',
  5306.                 "status" => 401,
  5307.             ], 401);
  5308.         }
  5309.         $entityManager $this->getDoctrine()->getManager();
  5310.         // update subscription 
  5311.         if (isset($data["subscriptionId"])) {
  5312.             $planAudio $this->getDoctrine()
  5313.                 ->getRepository(Subscription::class)
  5314.                 ->find($data["subscriptionId"]);
  5315.             $quantity $planAudio->getQuantity() + 1;
  5316.             if ($planAudio->getPlanInterval() == "year") {
  5317.                 $discountPercentage 15.8;
  5318.                 $pricePerMonth $planAudio->getPlan()->getPrice();
  5319.                 $discountAnnual = ($pricePerMonth 12) * (- ($discountPercentage 100));
  5320.                 $amount $planAudio->getPaidAmount() + number_format($discountAnnual1);
  5321.             } else {
  5322.                 $amount $planAudio->getPaidAmount() + $planAudio->getPlan()->getPrice();
  5323.             }
  5324.             $planAudio->setQuantity($quantity);
  5325.             $planAudio->setPaidAmount($amount);
  5326.             $entityManager->persist($planAudio);
  5327.             if ($_ENV['APP_ENV']  === 'dev') {
  5328.                 $privateKey $_ENV['STRIPE_SECRET_KEY_TEST'];
  5329.             } else {
  5330.                 $privateKey $_ENV['STRIPE_SECRET_KEY_LIVE'];
  5331.             }
  5332.             $stripeProduct $stripeService->getPriceIdMap();
  5333.             \Stripe\Stripe::setApiKey($privateKey);
  5334.             $cusId $planAudio->getStripeCustomerId();
  5335.             // Retrieve the existing subscription
  5336.             $subscriptions \Stripe\Subscription::all(['customer' => $cusId]);
  5337.             $subscription $subscriptions->data[0];
  5338.             // Determine the price ID for the new product
  5339.             $newPriceId = ($planAudio->getPlanInterval() == "year") ? $stripeProduct['additionnalCenterYearly'] : $stripeProduct['additionnalCenter'];
  5340.             // Find if the price ID already exists in the subscription items
  5341.             $existingItem null;
  5342.             foreach ($subscription->items->data as $item) {
  5343.                 if ($item->price->id == $newPriceId) {
  5344.                     $existingItem $item;
  5345.                     break;
  5346.                 }
  5347.             }
  5348.             // Update quantity if the item exists, otherwise create a new item
  5349.             if ($planAudio->getQuantity() > 2) {
  5350.                 // Update the quantity of the existing item
  5351.                 $newQuantity $existingItem->quantity 1;
  5352.                 \Stripe\SubscriptionItem::update($existingItem->id, [
  5353.                     'quantity' => $newQuantity,
  5354.                 ]);
  5355.             } else {
  5356.                 // Create a new subscription item
  5357.                 \Stripe\SubscriptionItem::create([
  5358.                     'subscription' => $subscription->id,
  5359.                     'price' => $newPriceId,
  5360.                     'quantity' => 1,
  5361.                 ]);
  5362.             }
  5363.         }
  5364.         // generate color code 
  5365.         $colors = array(
  5366.             "#FFC0CB"// Pink
  5367.             "#FFD700"// Gold
  5368.             "#90EE90"// Light Green
  5369.             "#87CEFA"// Light Sky Blue
  5370.             "#FFA07A"// Light Salmon
  5371.             "#F0E68C"// Khaki
  5372.             "#B0C4DE"// Light Steel Blue
  5373.             "#98FB98"// Pale Green
  5374.             "#FFB6C1"// Light Pink
  5375.             "#ADD8E6"// Light Blue
  5376.             "#FF69B4"// Hot Pink
  5377.             "#FFA500"// Orange
  5378.             "#00FF7F"// Spring Green
  5379.             "#AFEEEE"// Pale Turquoise
  5380.             "#FF8C00"// Dark Orange
  5381.             "#FFE4B5"// Moccasin
  5382.             "#00CED1"// Dark Turquoise
  5383.             "#7FFFD4"// Aquamarine
  5384.             "#FF4500"// Orange Red
  5385.             "#00FA9A"// Medium Spring Green
  5386.             "#FFF0F5"// Lavender Blush
  5387.             "#00BFFF"// Deep Sky Blue
  5388.             "#FF6347"// Tomato
  5389.             "#20B2AA"// Light Sea Green
  5390.             "#FFFF00"// Yellow
  5391.             "#32CD32"// Lime Green
  5392.             "#FFF5EE"// Seashell
  5393.             "#1E90FF"// Dodger Blue
  5394.             "#CD5C5C"// Indian Red
  5395.             "#8FBC8F"// Dark Sea Green
  5396.             "#F0FFFF"// Azure
  5397.             "#4169E1"// Royal Blue
  5398.             "#FF8B00"// Dark Orange
  5399.             "#66CDAA"// Medium Aquamarine
  5400.             "#FFFACD"// Lemon Chiffon
  5401.             "#6495ED"// Cornflower Blue
  5402.             "#FF7F50"// Coral
  5403.             "#00FF00"// Lime
  5404.             "#FAFAD2"// Light Goldenrod Yellow
  5405.             "#87CEEB"// Sky Blue
  5406.             "#DC143C"// Crimson
  5407.             "#2E8B57"// Sea Green
  5408.             "#F5DEB3"// Wheat
  5409.             "#4682B4"// Steel Blue
  5410.             "#CD853F"// Peru
  5411.             "#8A2BE2"// Blue Violet
  5412.             "#D2691E"// Chocolate
  5413.             "#6A5ACD"// Slate Blue
  5414.             "#F5F5DC"// Beige
  5415.             "#7B68EE"// Medium Slate Blue
  5416.         );
  5417.         // short initial 
  5418.         $name $data['name'];
  5419.         $words explode(' '$name);
  5420.         $initials '';
  5421.         foreach ($words as $word) {
  5422.             $initials .= strtoupper(substr($word01));
  5423.         }
  5424.         $initials strtoupper($initials);
  5425.         $shortName substr($initials02);
  5426.         $randomColor $colors[array_rand($colors)];
  5427.         // get gerant
  5428.         $gerant $this->getDoctrine()
  5429.             ->getRepository(Audio::class)
  5430.             ->find($data['gerant']);
  5431.         // set center
  5432.         $centre = new Centre();
  5433.         // generate slug url 
  5434.         $slug $this->slugger->slug($data["name"])->lower();
  5435.         $slugify $this->getDoctrine()
  5436.             ->getRepository(Centre::class)
  5437.             ->findOneBy(array('slug' => $slug));
  5438.         if ($slugify) {
  5439.             $centre->setSlug($slug "-1");
  5440.         } else {
  5441.             $centre->setSlug($slug);
  5442.         }
  5443.         $centre->setName($data["name"]);
  5444.         if (isset($data["imgUrl"]))
  5445.             $centre->setImgUrl($data["imgUrl"]);
  5446.         if (isset($data["finessURL"]))
  5447.             $centre->setFinessUrl($data["finessURL"]);
  5448.         $centre->setIsRdvDomicile($data["isRdvDomicile"]);
  5449.         $centre->setIdGerant($gerant);
  5450.         $centre->setAddress($data["address"]);
  5451.         $centre->setPostale($data["postal"]);
  5452.         $centre->setCity($data["city"]);
  5453.         $centre->setFiness($data["finess"]);
  5454.         $centre->setIsValid(true);
  5455.         $centre->setSiret($data["siret"]);
  5456.         $centre->setIsSign(1);
  5457.         $centre->setWebsite($data["website"]);
  5458.         $centre->setSignupDate(new \DateTime());
  5459.         if ($data['isSamePhone']) {
  5460.             $principalCenter $this->getDoctrine()
  5461.                 ->getRepository(AudioCentre::class)
  5462.                 ->findOneBy(['id_audio' => $gerant]);
  5463.             $phone $principalCenter $principalCenter->getIdCentre()->getPhone() : "";
  5464.             $centre->setPhone($phone);
  5465.         } else {
  5466.             $centre->setPhone($data['phone']);
  5467.         }
  5468.         $centre->setIsHandicap($data["isHandicap"]);
  5469.         $centre->setInitial($shortName);
  5470.         $centre->setLongitude($data["longitude"]);
  5471.         $centre->setLatitude($data["latitude"]);
  5472.         $centre->setCalendarColor($randomColor);
  5473.         $centre->setHoraire($publicFunction->centreHoraire2);
  5474.         $centerHoliday json_decode($publicFunction->centreHoraire4true);
  5475.         $centre->setHorairesHoliday($centerHoliday);
  5476.         $entityManager->persist($centre);
  5477.         // set audio center
  5478.         $audioCentre = new AudioCentre();
  5479.         $audioCentre->setIdAudio($gerant);
  5480.         $audioCentre->setIdCentre($centre);
  5481.         $audioCentre->setIsConfirmed(true);
  5482.         $audioCentre->setHoraire($publicFunction->centreHoraire2);
  5483.         $centerHoliday json_decode($publicFunction->centreHoraire4true);
  5484.         $audioCentre->setHorairesHoliday($centerHoliday);
  5485.         $entityManager->persist($audioCentre);
  5486.         // set access to center
  5487.         $accessCentre = new AccessCentre();
  5488.         foreach ($data["access"] as $accessData) {
  5489.             if (isset($accessData["metro"]))
  5490.                 $accessCentre->setMetro(json_encode($accessData["metro"], JSON_FORCE_OBJECT));
  5491.             if (isset($accessData["bus"]))
  5492.                 $accessCentre->setBus(json_encode($accessData["bus"], JSON_FORCE_OBJECT));
  5493.             if (isset($accessData["tram"]))
  5494.                 $accessCentre->setTram(json_encode($accessData["tram"], JSON_FORCE_OBJECT));
  5495.             if (isset($accessData["rer"]))
  5496.                 $accessCentre->setRer(json_encode($accessData["rer"], JSON_FORCE_OBJECT));
  5497.             if (isset($accessData["parkingPublic"]))
  5498.                 $accessCentre->setParkingPublic(json_encode($accessData["parkingPublic"], JSON_FORCE_OBJECT));
  5499.             if (isset($accessData["parkingPrivate"]))
  5500.                 $accessCentre->setParkingPrivate(json_encode($accessData["parkingPrivate"], JSON_FORCE_OBJECT));
  5501.             if (isset($accessData["other"]))
  5502.                 $accessCentre->setOther(json_encode($accessData["other"], JSON_FORCE_OBJECT));
  5503.         }
  5504.         $accessCentre->setIdCentre($centre);
  5505.         $entityManager->persist($accessCentre);
  5506.         // save print setting 
  5507.         $setting = new Setting();
  5508.         $setting->setName($data["name"]);
  5509.         $setting->setAddress($data["address"]);
  5510.         $setting->setPhone($data["phone"]);
  5511.         $setting->setLogoUrl($centre->getImgUrl());
  5512.         $setting->setWebsite($data["website"]);
  5513.         $setting->setFirstname($gerant->getName());
  5514.         $setting->setLastname($gerant->getLastname());
  5515.         $setting->setEmail($gerant->getMail());
  5516.         $setting->setSeuilCaDroite(true);
  5517.         $setting->setSeuilCaGauche(true);
  5518.         $setting->setSeuilConfortDroite(true);
  5519.         $setting->setSeuilinconfortDroite(true);
  5520.         $setting->setSeuilInConfortGauche(true);
  5521.         $setting->setSeuilConfortGauche(true);
  5522.         $setting->setSeuilCoDroite(true);
  5523.         $setting->setSeuilCoGauche(true);
  5524.         $setting->setSeuilCaMaskingDroite(true);
  5525.         $setting->setSeuilCaMaskingGauche(true);
  5526.         $setting->setSeuilCoMaskingDroite(true);
  5527.         $setting->setSeuilCoMaskingGauche(true);
  5528.         /*
  5529.          $setting->setCasqueDroite(false);
  5530.          $setting->setCasqueGauche(false);
  5531.          $setting->setCasqueBinaural(false);
  5532.          $setting->setChampsLibreDroite(false);
  5533.          $setting->setChampsLibreGauche(false);
  5534.          $setting->setChampsLibreBinaural(false);
  5535.          $setting->setChampsLibreAppDroite(false);
  5536.          $setting->setChampsLibreAppGauche(false);
  5537.          $setting->setChampsLibreAppBinaural(false);*/
  5538.         $setting->setCasqueDroite(true);
  5539.         $setting->setCasqueGauche(true);
  5540.         $setting->setCasqueBinaural(true);
  5541.         $setting->setChampsLibreDroite(true);
  5542.         $setting->setChampsLibreGauche(true);
  5543.         $setting->setChampsLibreBinaural(true);
  5544.         $setting->setChampsLibreAppDroite(true);
  5545.         $setting->setChampsLibreAppGauche(true);
  5546.         $setting->setChampsLibreAppBinaural(true);
  5547.         $setting->setCentre($centre);
  5548.         $entityManager->persist($setting);
  5549.         //add the centre access
  5550.         if (isset($data["mutuelle"]))
  5551.             foreach ($data["mutuelle"] as $mutuelleObject) {
  5552.                 $mutuelle $this->getDoctrine()
  5553.                     ->getRepository(Mutuelle::class)
  5554.                     ->findOneBy(['id' => $mutuelleObject]);
  5555.                 if ($mutuelle == null) {
  5556.                     return new Response(json_encode([
  5557.                         'message' => 'Error, no mutuelle found at this id ' $mutuelleObject,
  5558.                         'path' => 'src/Controller/CentreController.php',
  5559.                     ]));
  5560.                 } else {
  5561.                     $centreMutuelle = new CentreMutuelle();
  5562.                     $centreMutuelle->setIdMutuelle($mutuelle);
  5563.                     $centreMutuelle->setIdCentre($centre);
  5564.                     if (isset($data["otherMutuelle"]) && $mutuelle->getLibelle() == "Autres")
  5565.                         $centreMutuelle->setOther(json_encode($data["otherMutuelle"], JSON_FORCE_OBJECT));
  5566.                     $entityManager->persist($centreMutuelle);
  5567.                 }
  5568.             }
  5569.         //other spetiality 
  5570.         if (isset($data["otherSpetiality"])) {
  5571.             $audioSpecialite = new AudioSpecialite();
  5572.             // $audioSpecialite->setIdSpecialite($specialite);
  5573.             $audioSpecialite->setIdAudio($audio);
  5574.             $audioSpecialite->setOther(json_encode($data["otherSpetiality"], JSON_FORCE_OBJECT));
  5575.             $entityManager->persist($audioSpecialite);
  5576.         }
  5577.         if (isset($data["prestation"]))
  5578.             foreach ($data["prestation"] as $prestationId) {
  5579.                 $prestation $this->getDoctrine()
  5580.                     ->getRepository(Prestation::class)
  5581.                     ->findOneBy(['id' => $prestationId]);
  5582.                 if ($prestation == null) {
  5583.                     return new Response(json_encode([
  5584.                         'message' => 'Error, no prestation found at this id ' $prestationId,
  5585.                         'path' => 'src/Controller/CentreController.php',
  5586.                     ]));
  5587.                 } else {
  5588.                     $centrePrestation = new CentrePrestation();
  5589.                     $centrePrestation->setIdPrestation($prestation);
  5590.                     $centrePrestation->setIdCentre($centre);
  5591.                     $entityManager->persist($centrePrestation);
  5592.                 }
  5593.             }
  5594.         // set the galeries for images by default
  5595.         // Define an array of default image URLs
  5596.         $defaultImages = ["by-default-1.jpeg""by-default-2.jpeg""by-default-3.jpeg"];
  5597.         // Iterate through each default image
  5598.         foreach ($defaultImages as $imageUrl) {
  5599.             $centerImage = new CenterImage();
  5600.             $centerImage->setType("image");
  5601.             $centerImage->setUrl($imageUrl);
  5602.             // Associate the center image with the current center
  5603.             $centerImage->setCenter($centre);
  5604.             $entityManager->persist($centerImage);
  5605.         }
  5606.         /* if (isset($data["tier"]))
  5607.         foreach ($data["tier"] as $tierObject) {
  5608.             $tier = $this->getDoctrine()
  5609.                 ->getRepository(Tier::class)
  5610.                 ->findOneBy(['id' => $tierObject]);
  5611.             if ($tier == null) {
  5612.                 return new Response(json_encode([
  5613.                     'message' => 'Error, no tier found at this id ' . $tierObject,
  5614.                     'path' => 'src/Controller/CentreController.php',
  5615.                 ]));
  5616.             } else {
  5617.                 $centreTier = new CentreTier();
  5618.                 $centreTier->setIdTier($tier);
  5619.                 $centreTier->setIdCentre($centre);
  5620.                 $entityManager->persist($centreTier);
  5621.             }
  5622.         }*/
  5623.         $entityManager->flush();
  5624.         $name $centre->getName();
  5625.         $city $centre->getCity();
  5626.         $postal $centre->getPostale();
  5627.         $nameSlug strtolower(preg_replace('/[^a-zA-Z0-9]+/''-'trim($name)));
  5628.         $citySlug strtolower(preg_replace('/[^a-zA-Z0-9]+/''-'trim($city)));
  5629.         $baseClient $_ENV['BASE_client'] ?? 'https://default-client-url.com';
  5630.         $urlRdv "{$baseClient}audioprothesiste/{$citySlug}/{$postal}/{$nameSlug}/prise-de-rdvaudioprothesiste-rapide/{$centre->getId()}";
  5631.         if (!$centre->getUrlRdv() || $centre->getUrlRdv() !== $urlRdv) {
  5632.             $centre->setUrlRdv($urlRdv);
  5633.             $entityManager->persist($centre);
  5634.             $entityManager->flush();
  5635.         }
  5636.         return $this->json([
  5637.             'message' => 'centre a été ajouté',
  5638.             "status" => 200
  5639.         ]);
  5640.     }
  5641.     /**
  5642.      * @Route("/getcentre/{id}", name="getCentreId", methods={"GET","HEAD"})
  5643.      */
  5644.     public function getCentreId(Centre $centrePublicFunction $publicFunction): Response
  5645.     {
  5646.         $accessCentre $this->getDoctrine()->getRepository(AccessCentre::class)
  5647.             ->findOneBy(array('id_centre' => $centre->getId()));
  5648.         /*if (!$accessCentre)
  5649.             return new Response(json_encode([
  5650.                 'message' => 'Error, no accessCentre found at this id',
  5651.                 'path' => 'src/Controller/CentreController.php',
  5652.             ]), 404);
  5653.        */
  5654.         /** @var CentrePrestation[]*/
  5655.         $prestations $this->getDoctrine()->getRepository(CentrePrestation::class)
  5656.             ->findBy(array('id_centre' => $centre->getId()));
  5657.         $resultPrestation = new ArrayCollection();
  5658.         foreach ($prestations as $prestation) {
  5659.             $resultPrestation->add([
  5660.                 "id" => $prestation->getIdPrestation()->getId(),
  5661.                 "titre" => $prestation->getIdPrestation()->getLibelle(),
  5662.             ]);
  5663.         }
  5664.         /** @var CentreMutuelle[]*/
  5665.         $mutuelles $this->getDoctrine()->getRepository(CentreMutuelle::class)
  5666.             ->findBy(array('id_centre' => $centre->getId()));
  5667.         $resultMutuelle = new ArrayCollection();
  5668.         foreach ($mutuelles as $mutuelle) {
  5669.             $resultMutuelle->add([
  5670.                 "id" => $mutuelle->getIdMutuelle()->getId(),
  5671.                 "titre" => $mutuelle->getIdMutuelle()->getLibelle(),
  5672.             ]);
  5673.         }
  5674.         if ($accessCentre) {
  5675.             $metroIDs json_decode($accessCentre->getMetro(), true);
  5676.             $metroNames = [];
  5677.             if (is_array($metroIDs)) {
  5678.                 $stations $this->getDoctrine()->getRepository(Station::class)->findBy(['id' => $metroIDs]);
  5679.                 foreach ($stations as $station) {
  5680.                     $metroNames[] = [
  5681.                         "name" => $station->getName(),
  5682.                         "value" => $station->getId(),
  5683.                     ];
  5684.                 }
  5685.             }
  5686.             return $this->json([
  5687.                 "tram" => json_decode($accessCentre->getTram(), true),
  5688.                 "rer" => json_decode($accessCentre->getRer(), true),
  5689.                 "metro" => $metroNames,
  5690.                 "bus" => json_decode($accessCentre->getBus(), true),
  5691.                 "parking" => json_decode($accessCentre->getParkingPublic(), true),
  5692.                 "parkingPrivate" => json_decode($accessCentre->getParkingPrivate(), true),
  5693.                 "other" => json_decode($accessCentre->getOther(), true),
  5694.                 "id" => $centre->getId(),
  5695.                 "audio_id" => $centre->getIdGerant()->getId(),
  5696.                 "name" => $centre->getName(),
  5697.                 "imgUrl" => $centre->getImgUrl(),
  5698.                 "isRdvDomicile" => $centre->getIsRdvDomicile(),
  5699.                 "address" => $centre->getAddress(),
  5700.                 "numero" => $centre->getNumero(),
  5701.                 "voie" => $centre->getVoie(),
  5702.                 "rue" => $centre->getRue(),
  5703.                 "description" => $centre->getDescription(),
  5704.                 "postale" => $centre->getPostale(),
  5705.                 "city" => $centre->getCity(),
  5706.                 "finess" => $centre->getFiness(),
  5707.                 "siret" => $centre->getSiret(),
  5708.                 "website" => $centre->getWebsite(),
  5709.                 "phone" => $centre->getPhone(),
  5710.                 "imgUrl" => $centre->getImgUrl(),
  5711.                 "aditionnelInfo" => $centre->getAditionnelInfo(),
  5712.                 "initial" => $centre->getInitial(),
  5713.                 "calendarColor" => $centre->getCalendarColor(),
  5714.                 "isHandicap" => $centre->getIsHandicap(),
  5715.                 "longitude" => $centre->getLongitude(),
  5716.                 "latitude" => $centre->getLatitude(),
  5717.                 "isSign" => $centre->getIsSign(),
  5718.                 //"comments" => $comments,
  5719.                 "mutuelles" => $resultMutuelle->toArray(),
  5720.                 "prestations" => $resultPrestation->toArray(),
  5721.                 //"tiers" => $resultTier->toArray(),
  5722.                 //"audio" => $resultAudio->toArray(),
  5723.                 "schedule" => $centre->getHoraire(),
  5724.                 "status" => 200,
  5725.             ]);
  5726.         } else {
  5727.             return $this->json([
  5728.                 "id" => $centre->getId(),
  5729.                 "audio_id" => $centre->getIdGerant()->getId(),
  5730.                 "name" => $centre->getName(),
  5731.                 "imgUrl" => $centre->getImgUrl(),
  5732.                 "isRdvDomicile" => $centre->getIsRdvDomicile(),
  5733.                 "address" => $centre->getAddress(),
  5734.                 "numero" => $centre->getNumero(),
  5735.                 "voie" => $centre->getVoie(),
  5736.                 "rue" => $centre->getRue(),
  5737.                 "description" => $centre->getDescription(),
  5738.                 "postale" => $centre->getPostale(),
  5739.                 "city" => $centre->getCity(),
  5740.                 "finess" => $centre->getFiness(),
  5741.                 "siret" => $centre->getSiret(),
  5742.                 "website" => $centre->getWebsite(),
  5743.                 "phone" => $centre->getPhone(),
  5744.                 "imgUrl" => $centre->getImgUrl(),
  5745.                 "aditionnelInfo" => $centre->getAditionnelInfo(),
  5746.                 "initial" => $centre->getInitial(),
  5747.                 "calendarColor" => $centre->getCalendarColor(),
  5748.                 "isHandicap" => $centre->getIsHandicap(),
  5749.                 "longitude" => $centre->getLongitude(),
  5750.                 "latitude" => $centre->getLatitude(),
  5751.                 // "averageRating" => $publicFunction->calculateRating($centreRdvs),
  5752.                 //"nbrReview" => count($centreRdvs),
  5753.                 "tram" => null,
  5754.                 "rer" => null,
  5755.                 "metro" => null,
  5756.                 "bus" => null,
  5757.                 "parking" => null,
  5758.                 "parkingPrivate" => null,
  5759.                 "other" => null,
  5760.                 "isSign" => $centre->getIsSign(),
  5761.                 //"comments" => $comments,
  5762.                 "mutuelles" => $resultMutuelle->toArray(),
  5763.                 "prestations" => $resultPrestation->toArray(),
  5764.                 //"tiers" => $resultTier->toArray(),
  5765.                 //"audio" => $resultAudio->toArray(),
  5766.                 "schedule" => $centre->getHoraire(),
  5767.                 "status" => 200,
  5768.             ]);
  5769.         }
  5770.     }
  5771.     /**
  5772.      * @Route("/center/update/{id}", name="updateCenterAudio", methods={"POST"})
  5773.      */
  5774.     public function EditCentreBy(Request $requestCentre $centrePublicFunction $publicFunction): Response
  5775.     {
  5776.         $data json_decode($request->getContent(), true);
  5777.         if (!isset($data["token"])) {
  5778.             return new Response(json_encode([
  5779.                 "message" => "Pas de token n'a été spécifié",
  5780.                 "status" => 401,
  5781.             ]), 401);
  5782.         }
  5783.         $audioCheckTel $this->getDoctrine()
  5784.             ->getRepository(Centre::class)
  5785.             ->findOneBy(["phone" => $data['phone']]);
  5786.         /* if ($audioCheckTel)
  5787.         return $this->json([
  5788.             "message" => "Le numéro de téléphone existe déjà",
  5789.             "status" => 404,
  5790.         ]);
  5791.         */
  5792.         $entityManager $this->getDoctrine()->getManager();
  5793.         /** @var Token */
  5794.         $token $this->getDoctrine()
  5795.             ->getRepository(Token::class)
  5796.             ->findOneBy(['token' => $data["token"], 'id_audio' => $data["gerant"]]);
  5797.         if (!$token) {
  5798.             return new Response(json_encode([
  5799.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5800.                 "status" => 404,
  5801.             ]), 404);
  5802.         }
  5803.         // get token age
  5804.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5805.         // if the token if older than 7 days
  5806.         if ($dateDiff->7) {
  5807.             $entityManager->remove($token);
  5808.             $entityManager->flush();
  5809.             return $this->json([
  5810.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5811.                 'path' => 'src/Controller/ClientController.php',
  5812.                 "status" => 401,
  5813.             ], 401);
  5814.         }
  5815.         $entityManager $this->getDoctrine()->getManager();
  5816.         if (isset($data["name"]))
  5817.             $centre->setName($data["name"]);
  5818.         if (isset($data["imgUrl"]))
  5819.             $centre->setImgUrl($data["imgUrl"]);
  5820.         if (isset($data["finessURL"]))
  5821.             $centre->setFinessUrl($data["finessURL"]);
  5822.         if (isset($data["isRdvDomicile"]))
  5823.             $centre->setIsRdvDomicile($data["isRdvDomicile"]);
  5824.         if (isset($data["address"]))
  5825.             $centre->setAddress($data["address"]);
  5826.         if (isset($data["postal"]))
  5827.             $centre->setPostale($data["postal"]);
  5828.         if (isset($data["city"]))
  5829.             $centre->setCity($data["city"]);
  5830.         if (isset($data["finess"]))
  5831.             $centre->setFiness($data["finess"]);
  5832.         if (isset($data["siret"]))
  5833.             $centre->setSiret($data["siret"]);
  5834.         if (isset($data["description"]))
  5835.             $centre->setDescription($data["description"]);
  5836.         if (isset($data["initial"]))
  5837.             $centre->setInitial($data["initial"]);
  5838.         if (isset($data["calendarColor"]))
  5839.             $centre->setCalendarColor($data["calendarColor"]);
  5840.         if (isset($data["website"]))
  5841.             $centre->setWebsite($data["website"]);
  5842.         if (isset($data["aditionnelInfo"]))
  5843.             $centre->setAditionnelInfo($data["aditionnelInfo"]);
  5844.         // Toujours défini à la date actuelle
  5845.         $centre->setSignupDate(new \DateTime());
  5846.         if (isset($data["phone"]))
  5847.             $centre->setPhone($data["phone"]);
  5848.         if (isset($data["isHandicap"]))
  5849.             $centre->setIsHandicap($data["isHandicap"]);
  5850.         if (isset($data["longitude"]))
  5851.             $centre->setLongitude($data["longitude"]);
  5852.         if (isset($data["latitude"]))
  5853.             $centre->setLatitude($data["latitude"]);
  5854.         //  $centre->setHoraire($publicFunction->centreHoraire2);
  5855.         $entityManager->persist($centre);
  5856.         // Fetch access centre data
  5857.         // Fetch access centre data
  5858.         $accessCentre $entityManager->getRepository(AccessCentre::class)->findOneBy(['id_centre' => $centre->getId()]);
  5859.         if ($accessCentre) {
  5860.             // Set the values from the form inputs
  5861.             foreach ($data["access"] as $accessData) {
  5862.                 if (isset($accessData["metro"]))
  5863.                     $accessCentre->setMetro(json_encode($accessData["metro"], JSON_FORCE_OBJECT));
  5864.                 if (isset($accessData["bus"]))
  5865.                     $accessCentre->setBus(json_encode($accessData["bus"], JSON_FORCE_OBJECT));
  5866.                 if (isset($accessData["tram"]))
  5867.                     $accessCentre->setTram(json_encode($accessData["tram"], JSON_FORCE_OBJECT));
  5868.                 if (isset($accessData["rer"]))
  5869.                     $accessCentre->setRer(json_encode($accessData["rer"], JSON_FORCE_OBJECT));
  5870.                 if (isset($accessData["parkingPublic"]))
  5871.                     $accessCentre->setParkingPublic(json_encode($accessData["parkingPublic"], JSON_FORCE_OBJECT));
  5872.                 if (isset($accessData["parkingPrivate"]))
  5873.                     $accessCentre->setParkingPrivate(json_encode($accessData["parkingPrivate"], JSON_FORCE_OBJECT));
  5874.                 if (isset($accessData["other"]))
  5875.                     $accessCentre->setOther(json_encode($accessData["other"], JSON_FORCE_OBJECT));
  5876.             }
  5877.             //$accessCentre->setIdCentre($centre);
  5878.             /*if (isset($data['metro'])) {
  5879.     $metroValues = explode(',', $data['metro']);
  5880.     $accessCentre->setMetro(json_encode($metroValues, JSON_FORCE_OBJECT));
  5881. }
  5882. if (isset($data['bus'])) {
  5883.     $busValues = explode(',', $data['bus']);
  5884.     $accessCentre->setBus(json_encode($busValues, JSON_FORCE_OBJECT));
  5885. }
  5886. if (isset($data['tram'])) {
  5887.     $tramValues = explode(',', $data['tram']);
  5888.     $accessCentre->setTram(json_encode($tramValues, JSON_FORCE_OBJECT));
  5889. }
  5890. if (isset($data['rer'])) {
  5891.     $rerValues = explode(',', $data['rer']);
  5892.     $accessCentre->setRer(json_encode($rerValues, JSON_FORCE_OBJECT));
  5893. }
  5894. if (isset($data['parking'])) {
  5895.     $parkingValues = explode(',', $data['parking']);
  5896.     $accessCentre->setParkingPublic(json_encode($parkingValues, JSON_FORCE_OBJECT));
  5897. }
  5898. if (isset($data['parkingPrivate'])) {
  5899.     $parkingPrivateValues = explode(',', $data['parkingPrivate']);
  5900.     $accessCentre->setParkingPrivate(json_encode($parkingPrivateValues, JSON_FORCE_OBJECT));
  5901. }
  5902. if (isset($data['other'])) {
  5903.     $otherValues = explode(',', $data['other']);
  5904.     $accessCentre->setOther(json_encode($otherValues, JSON_FORCE_OBJECT));
  5905. }*/
  5906.         } else {
  5907.             // Create an instance of AccessCentre
  5908.             $accessCentre = new AccessCentre();
  5909.             // Set the values from the form inputs
  5910.             if (isset($accessData["metro"]))
  5911.                 $accessCentre->setMetro(json_encode($accessData["metro"], JSON_FORCE_OBJECT));
  5912.             if (isset($accessData["bus"]))
  5913.                 $accessCentre->setBus(json_encode($accessData["bus"], JSON_FORCE_OBJECT));
  5914.             if (isset($accessData["tram"]))
  5915.                 $accessCentre->setTram(json_encode($accessData["tram"], JSON_FORCE_OBJECT));
  5916.             if (isset($accessData["rer"]))
  5917.                 $accessCentre->setRer(json_encode($accessData["rer"], JSON_FORCE_OBJECT));
  5918.             if (isset($accessData["parkingPublic"]))
  5919.                 $accessCentre->setParkingPublic(json_encode($accessData["parkingPublic"], JSON_FORCE_OBJECT));
  5920.             if (isset($accessData["parkingPrivate"]))
  5921.                 $accessCentre->setParkingPrivate(json_encode($accessData["parkingPrivate"], JSON_FORCE_OBJECT));
  5922.             if (isset($accessData["other"]))
  5923.                 $accessCentre->setOther(json_encode($accessData["other"], JSON_FORCE_OBJECT));
  5924.             if (isset($data['other'])) {
  5925.                 $otherValues explode(','$data['other']);
  5926.                 $accessCentre->setOther(json_encode($otherValuesJSON_FORCE_OBJECT));
  5927.             }
  5928.         }
  5929.         $mutuels $this->getDoctrine()
  5930.             ->getRepository(CentreMutuelle::class)
  5931.             ->findBy(['id_centre' => $centre->getId()]);
  5932.         $prestations $this->getDoctrine()
  5933.             ->getRepository(CentrePrestation::class)
  5934.             ->findBy(['id_centre' => $centre->getId()]);
  5935.         $entityManager $this->getDoctrine()->getManager();
  5936.         foreach ($mutuels as $mutuel) {
  5937.             $entityManager->remove($mutuel);
  5938.         }
  5939.         foreach ($prestations as $prestation) {
  5940.             $entityManager->remove($prestation);
  5941.         }
  5942.         if (isset($data["mutuelle"]))
  5943.             foreach ($data["mutuelle"] as $mutuelleObject) {
  5944.                 $mutuelle $this->getDoctrine()
  5945.                     ->getRepository(Mutuelle::class)
  5946.                     ->findOneBy(['id' => $mutuelleObject]);
  5947.                 if ($mutuelle == null) {
  5948.                     return new Response(json_encode([
  5949.                         'message' => 'Error, no mutuelle found at this id ' $mutuelleObject,
  5950.                         'path' => 'src/Controller/CentreController.php',
  5951.                     ]));
  5952.                 } else {
  5953.                     $centreMutuelle = new CentreMutuelle();
  5954.                     $centreMutuelle->setIdMutuelle($mutuelle);
  5955.                     $centreMutuelle->setIdCentre($centre);
  5956.                     if (isset($data["otherMutuelle"]) && $mutuelle->getLibelle() == "Autres")
  5957.                         $centreMutuelle->setOther(json_encode($data["otherMutuelle"], JSON_FORCE_OBJECT));
  5958.                     $entityManager->persist($centreMutuelle);
  5959.                 }
  5960.             }
  5961.         //other spetiality 
  5962.         if (isset($data["otherSpetiality"])) {
  5963.             $audioSpecialite = new AudioSpecialite();
  5964.             // $audioSpecialite->setIdSpecialite($specialite);
  5965.             $audioSpecialite->setIdAudio($audio);
  5966.             $audioSpecialite->setOther(json_encode($data["otherSpetiality"], JSON_FORCE_OBJECT));
  5967.             $entityManager->persist($audioSpecialite);
  5968.         }
  5969.         if (isset($data["prestation"]))
  5970.             foreach ($data["prestation"] as $prestationId) {
  5971.                 $prestation $this->getDoctrine()
  5972.                     ->getRepository(Prestation::class)
  5973.                     ->findOneBy(['id' => $prestationId]);
  5974.                 if ($prestation == null) {
  5975.                     return new Response(json_encode([
  5976.                         'message' => 'Error, no prestation found at this id ' $prestationId,
  5977.                         'path' => 'src/Controller/CentreController.php',
  5978.                     ]));
  5979.                 } else {
  5980.                     $centrePrestation = new CentrePrestation();
  5981.                     $centrePrestation->setIdPrestation($prestation);
  5982.                     $centrePrestation->setIdCentre($centre);
  5983.                     $entityManager->persist($centrePrestation);
  5984.                 }
  5985.             }
  5986.         // Set the centre ID
  5987.         $accessCentre->setIdCentre($centre);
  5988.         // Persist the access centre entity
  5989.         $entityManager->persist($accessCentre);
  5990.         $entityManager->flush();
  5991.         return $this->json([
  5992.             'message' => 'centre a été modifié avec succée',
  5993.             "status" => 200
  5994.         ]);
  5995.     }
  5996.     /**
  5997.      * @Route("/centresingle/horaire/{id}", name="setCentreHoraireSingle", methods={"PUT"})
  5998.      */
  5999.     public function setCentreSingleHoraire(Centre $centrePublicFunction $publicFunctionRequest $request)
  6000.     {
  6001.         if (!$request->query->get('token')) {
  6002.             return new Response(json_encode([
  6003.                 "message" => "Pas de token n'a été spécifié",
  6004.                 "status" => 401,
  6005.             ]), 401);
  6006.         }
  6007.         $entityManager $this->getDoctrine()->getManager();
  6008.         /** @var Token */
  6009.         $token $this->getDoctrine()
  6010.             ->getRepository(Token::class)
  6011.             ->findOneBy(['token' => $request->query->get('token'), 'id_audio' => $request->query->get('audio')]);
  6012.         if (!$token) {
  6013.             return new Response(json_encode([
  6014.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6015.                 "status" => 404,
  6016.             ]), 404);
  6017.         }
  6018.         // get token age
  6019.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6020.         // if the token if older than 7 days
  6021.         if ($dateDiff->7) {
  6022.             $entityManager->remove($token);
  6023.             $entityManager->flush();
  6024.             return $this->json([
  6025.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6026.                 'path' => 'src/Controller/AudioController.php',
  6027.                 "status" => 401,
  6028.             ], 401);
  6029.         }
  6030.         $entityManager $this->getDoctrine()->getManager();
  6031.         $data json_decode($request->getContent(), true);
  6032.         $centre->setHoraire($data["horaires"]);
  6033.         $entityManager->flush();
  6034.         return $this->json([
  6035.             "id" => $centre->getId(),
  6036.             "horaires" => $data["horaires"]
  6037.         ]);
  6038.     }
  6039.     /**
  6040.      * @Route("/centresingle/horaire-holiday/{id}", name="setCentreHoraireHolidaySingle", methods={"PUT"})
  6041.      */
  6042.     public function setCentreHoraireHolidaySingle(Centre $centrePublicFunction $publicFunctionRequest $request)
  6043.     {
  6044.         if (!$request->query->get('token')) {
  6045.             return new Response(json_encode([
  6046.                 "message" => "Pas de token n'a été spécifié",
  6047.                 "status" => 401,
  6048.             ]), 401);
  6049.         }
  6050.         $entityManager $this->getDoctrine()->getManager();
  6051.         /** @var Token */
  6052.         $token $this->getDoctrine()
  6053.             ->getRepository(Token::class)
  6054.             ->findOneBy(['token' => $request->query->get('token'), 'id_audio' => $request->query->get('audio')]);
  6055.         if (!$token) {
  6056.             return new Response(json_encode([
  6057.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6058.                 "status" => 404,
  6059.             ]), 404);
  6060.         }
  6061.         // get token age
  6062.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6063.         // if the token if older than 7 days
  6064.         if ($dateDiff->7) {
  6065.             $entityManager->remove($token);
  6066.             $entityManager->flush();
  6067.             return $this->json([
  6068.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6069.                 'path' => 'src/Controller/AudioController.php',
  6070.                 "status" => 401,
  6071.             ], 401);
  6072.         }
  6073.         $entityManager $this->getDoctrine()->getManager();
  6074.         $data json_decode($request->getContent(), true);
  6075.         $centre->setHorairesHoliday($data["horaires"]);
  6076.         $entityManager->flush();
  6077.         return $this->json([
  6078.             "id" => $centre->getId(),
  6079.             "horaires" => $data["horaires"]
  6080.         ]);
  6081.     }
  6082.     /**
  6083.      * @Route("/centres/fData/{id}", name="postCentresImageByFormData", methods={"POST"})
  6084.      */
  6085.     public function postCentresImageByFormData(Centre $centreRequest $requestFileUploader $fileUploader): Response
  6086.     {
  6087.         if (!$request->query->get('token')) {
  6088.             return new Response(json_encode([
  6089.                 "message" => "Pas de token n'a été spécifié",
  6090.                 "status" => 401,
  6091.             ]), 401);
  6092.         }
  6093.         $entityManager $this->getDoctrine()->getManager();
  6094.         /** @var Token */
  6095.         $token $this->getDoctrine()
  6096.             ->getRepository(Token::class)
  6097.             ->findOneBy(['token' => $request->query->get('token'), 'id_audio' => $centre->getIdGerant()]);
  6098.         if (!$token) {
  6099.             return new Response(json_encode([
  6100.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6101.                 "status" => 404,
  6102.             ]), 404);
  6103.         }
  6104.         // get token age
  6105.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6106.         // if the token if older than 7 days
  6107.         if ($dateDiff->7) {
  6108.             $entityManager $this->getDoctrine()->getManager();
  6109.             $entityManager->remove($token);
  6110.             $entityManager->flush();
  6111.             return $this->json([
  6112.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6113.                 'path' => 'src/Controller/AudioController.php',
  6114.                 "status" => 401,
  6115.             ], 401);
  6116.         }
  6117.         // Handle updates to existing images
  6118.         if (isset($_FILES["file"])) {
  6119.             foreach ($_FILES["file"]["error"] as $key => $error) {
  6120.                 if ($error == UPLOAD_ERR_OK) {
  6121.                     $file = [
  6122.                         "name" => $_FILES["file"]["name"][$key],
  6123.                         "type" => $_FILES["file"]["type"][$key],
  6124.                         "tmp_name" => $_FILES["file"]["tmp_name"][$key],
  6125.                         "error" => $_FILES["file"]["error"][$key],
  6126.                         "size" => $_FILES["file"]["size"][$key],
  6127.                     ];
  6128.                     // Extract the image ID from the key
  6129.                     $imageId $key// Ensure this matches how you're identifying images
  6130.                     $image $entityManager->getRepository(CenterImage::class)->find($imageId);
  6131.                     if ($image) {
  6132.                         // Delete old file from the filesystem
  6133.                         $oldFilePath "images/centres/" $image->getUrl();
  6134.                         if (file_exists($oldFilePath)) {
  6135.                             unlink($oldFilePath);
  6136.                         }
  6137.                     } else {
  6138.                         // If no existing image, create a new entity
  6139.                         $image = new CenterImage();
  6140.                         $image->setCenter($centre);
  6141.                     }
  6142.                     // Determine file type (image or video) based on MIME type
  6143.                     $fileType mime_content_type($file['tmp_name']);
  6144.                     if (strpos($fileType'image') !== false) {
  6145.                         // File is an image
  6146.                         $image->setType('image');
  6147.                     } elseif (strpos($fileType'video') !== false) {
  6148.                         // File is a video
  6149.                         $image->setType('video');
  6150.                     }
  6151.                     $newfilename $fileUploader->uploadFormData($file"images/centres/");
  6152.                     if ($newfilename) {
  6153.                         $image->setUrl($newfilename);
  6154.                         $entityManager->persist($image);
  6155.                     }
  6156.                 }
  6157.             }
  6158.         }
  6159.         // Handle new image uploads
  6160.         if (isset($_FILES['newFile'])) {
  6161.             foreach ($_FILES['newFile']['error'] as $key => $error) {
  6162.                 if ($error == UPLOAD_ERR_OK) {
  6163.                     $file = [
  6164.                         'name' => $_FILES['newFile']['name'][$key],
  6165.                         'type' => $_FILES['newFile']['type'][$key],
  6166.                         'tmp_name' => $_FILES['newFile']['tmp_name'][$key],
  6167.                         'error' => $_FILES['newFile']['error'][$key],
  6168.                         'size' => $_FILES['newFile']['size'][$key],
  6169.                     ];
  6170.                     $image = new CenterImage();
  6171.                     $image->setCenter($centre);
  6172.                     $fileType mime_content_type($file['tmp_name']);
  6173.                     if (strpos($fileType'image') !== false) {
  6174.                         $image->setType('image');
  6175.                     } elseif (strpos($fileType'video') !== false) {
  6176.                         $image->setType('video');
  6177.                     }
  6178.                     $newfilename $fileUploader->uploadFormData($file"images/centres/");
  6179.                     if ($newfilename) {
  6180.                         $image->setUrl($newfilename);
  6181.                         $entityManager->persist($image);
  6182.                     }
  6183.                 }
  6184.             }
  6185.         }
  6186.         $entityManager->flush(); // Apply changes to the database
  6187.         return $this->json([
  6188.             "imgUrl" => $centre->getImgUrl(),
  6189.         ]);
  6190.     }
  6191.     /**
  6192.      * @Route("/centre/images/{id}", name="getCentresImage", methods={"GET"})
  6193.      */
  6194.     public function getCentresImage(Centre $centerPublicFunction $publicFunction): Response
  6195.     {
  6196.         $images $this->getDoctrine()
  6197.             ->getRepository(CenterImage::class)
  6198.             ->findBy(['center' => $center]);
  6199.         $imageCenter array_map(function ($image) {
  6200.             return [
  6201.                 "id" => $image->getId(),
  6202.                 "url" => $image->getUrl(),
  6203.                 "type" => $image->getType(),
  6204.             ];
  6205.         }, $images);
  6206.         return $this->json([
  6207.             "images" => $imageCenter,
  6208.         ]);
  6209.     }
  6210.     /**
  6211.      * @Route("/center/images/{url}", name="getCentresByImages", methods={"GET"})
  6212.      */
  6213.     public function getCentresByImages(string $urlPublicFunction $publicFunction): Response
  6214.     {
  6215.         return $publicFunction->replyWithFile('images/centres/'$url);
  6216.     }
  6217.     /**
  6218.      * @Route("centre/images/delete/", name="deleteCentresImage", methods={"POST"})
  6219.      */
  6220.     public function deleteCentresImage(Request $request): Response
  6221.     {
  6222.         $imageId $request->request->get("imageId");
  6223.         $imageGalerie $this->getDoctrine()->getRepository(CenterImage::class)
  6224.             ->find($imageId);
  6225.         $defaultImageUrls = ["by-default-1.jpeg""by-default-2.jpeg""by-default-3.jpeg"];
  6226.         if (!in_array($imageGalerie->getUrl(), $defaultImageUrls)) {
  6227.             $filePath $this->getParameter('kernel.project_dir') . "/assets/images/centres/" $imageGalerie->getUrl();
  6228.             if (file_exists($filePath)) {
  6229.                 unlink($filePath);
  6230.             }
  6231.         }
  6232.         $entityManager $this->getDoctrine()->getManager();
  6233.         $entityManager->remove($imageGalerie);
  6234.         $entityManager->flush();
  6235.         return $this->json(["status" => 200]);
  6236.     }
  6237.     /**
  6238.      * @Route("/center-update-description/{id}", name="setCentreDescription", methods={"PUT"})
  6239.      */
  6240.     public function setCentreDescription(Centre $centrePublicFunction $publicFunctionRequest $request)
  6241.     {
  6242.         $data json_decode($request->getContent(), true);
  6243.         if (!$data['token']) {
  6244.             return new Response(json_encode([
  6245.                 "message" => "Pas de token n'a été spécifié",
  6246.                 "status" => 401,
  6247.             ]), 401);
  6248.         }
  6249.         $entityManager $this->getDoctrine()->getManager();
  6250.         /** @var Token */
  6251.         $token $this->getDoctrine()
  6252.             ->getRepository(Token::class)
  6253.             ->findOneBy(['token' => $data['token'], 'id_audio' => $data['audio']]);
  6254.         if (!$token) {
  6255.             return new Response(json_encode([
  6256.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6257.                 "status" => 404,
  6258.             ]), 404);
  6259.         }
  6260.         // get token age
  6261.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6262.         // if the token if older than 7 days
  6263.         if ($dateDiff->7) {
  6264.             $entityManager->remove($token);
  6265.             $entityManager->flush();
  6266.             return $this->json([
  6267.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6268.                 'path' => 'src/Controller/AudioController.php',
  6269.                 "status" => 401,
  6270.             ], 401);
  6271.         }
  6272.         $date1 = new DateTime();
  6273.         $date2 = new DateTime();
  6274.         $entityManager $this->getDoctrine()->getManager();
  6275.         $centre->setDescription($data["description"]);
  6276.         $entityManager->flush();
  6277.         return $this->json([
  6278.             "id" => $centre->getId(),
  6279.             "status" => "200"
  6280.         ]);
  6281.     }
  6282.     /**
  6283.      * @Route("/audioschedule/centre", name="getScheduleCentre", methods={"GET","HEAD"})
  6284.      */
  6285.     public function getScheduleCentre(Request $requestPublicFunction $publicFunction)
  6286.     {
  6287.         $data $request->query->all();
  6288.         //dd($data);
  6289.         if (!$data['token']) {
  6290.             return new Response(json_encode([
  6291.                 "message" => "Pas de token n'a été spécifié",
  6292.                 "status" => 401,
  6293.             ]), 401);
  6294.         }
  6295.         $entityManager $this->getDoctrine()->getManager();
  6296.         /** @var Token */
  6297.         $token $this->getDoctrine()
  6298.             ->getRepository(Token::class)
  6299.             ->findOneBy(['token' => $data['token'], 'id_audio' => $data['audio']]);
  6300.         if (!$token) {
  6301.             return new Response(json_encode([
  6302.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6303.                 "status" => 404,
  6304.             ]), 404);
  6305.         }
  6306.         // get token age
  6307.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6308.         // if the token if older than 7 days
  6309.         if ($dateDiff->7) {
  6310.             $entityManager->remove($token);
  6311.             $entityManager->flush();
  6312.             return $this->json([
  6313.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6314.                 'path' => 'src/Controller/AudioController.php',
  6315.                 "status" => 401,
  6316.             ], 401);
  6317.         }
  6318.         $audio $this->getDoctrine()
  6319.             ->getRepository(Audio::class)
  6320.             ->find($data['audio']);
  6321.         $centre $this->getDoctrine()
  6322.             ->getRepository(Centre::class)
  6323.             ->find($data['center']);
  6324.         $date1 = new DateTime();
  6325.         $date2 = new DateTime();
  6326.         return $this->json([
  6327.             "schedule" => [
  6328.                 $publicFunction->calculSchedule($audio, new \DateTime(), $centre),
  6329.                 $publicFunction->calculSchedule($audio$date1->add(new DateInterval('P7D')), $centre),
  6330.                 $publicFunction->calculSchedule($audio$date2->add(new DateInterval('P14D')), $centre)
  6331.             ],
  6332.             "status" => "200"
  6333.         ]);
  6334.     }
  6335.     /**
  6336.      * @Route("/villes", name="getVilleCentre", methods={"GET","HEAD"})
  6337.      */
  6338.     public function getVilleCentre(Request $requestPublicFunction $publicFunction)
  6339.     {
  6340.         $data $request->query->all();
  6341.         //dd($data);
  6342.         $villes $this->getDoctrine()
  6343.             ->getRepository(Ville::class)
  6344.             ->findAll();
  6345.         $getVilles array_map(function ($ville) {
  6346.             return [
  6347.                 "id" => $ville->getId(),
  6348.                 "nom" => $ville->getNom(),
  6349.                 "slug" => $ville->getSlug(),
  6350.             ];
  6351.         }, $villes);
  6352.         return $this->json([
  6353.             "villes" => $getVilles,
  6354.             "status" => "200"
  6355.         ]);
  6356.     }
  6357.     /**
  6358.      * @Route("/assets/pdf/{filename}", name="download_pdf", methods={"GET"})
  6359.      */
  6360.     public function downloadPdf(string $filename): Response
  6361.     {
  6362.         $filePath '../assets/pdf/' $filename;
  6363.         if (!file_exists($filePath)) {
  6364.             return new Response('File not found.'Response::HTTP_NOT_FOUND);
  6365.         }
  6366.         return new BinaryFileResponse($filePath);
  6367.     }
  6368.     /**
  6369.      * @Route("/checkphoneclient", name="checkPhoneClient", methods={"GET","HEAD"})
  6370.      */
  6371.     public function checkPhoneClient(Request $requestPublicFunction $publicFunction)
  6372.     {
  6373.         $clientPhoneTest $this->getDoctrine()
  6374.             ->getRepository(Client::class)
  6375.             ->findOneBy(['phone' => $request->query->get('phone')]);
  6376.         if ($clientPhoneTest) {
  6377.             return $this->json([
  6378.                 'message' => 'Ce numéro de téléphone est déjà attribué.',
  6379.                 'path' => 'src/Controller/ClientController.php',
  6380.                 "status" => 401,
  6381.             ], 200);
  6382.         }
  6383.         return $this->json([
  6384.             'message' => 'Le numéro n\'est pas utilisé.',
  6385.             "status" => 200,
  6386.         ]);
  6387.     }
  6388.     /**
  6389.      * @Route("/checkemailclient", name="checkEmailClient", methods={"GET","HEAD"})
  6390.      */
  6391.     public function checkEmailClient(Request $requestPublicFunction $publicFunction)
  6392.     {
  6393.         $clientMailTest $this->getDoctrine()
  6394.             ->getRepository(Client::class)
  6395.             ->findOneBy(['mail' => $request->query->get('mail')]);
  6396.         if ($clientMailTest) {
  6397.             return $this->json([
  6398.                 'message' => 'Ce mail est déjà attribué.',
  6399.                 'path' => 'src/Controller/ClientController.php',
  6400.                 "status" => 401,
  6401.             ], 200);
  6402.         }
  6403.         return $this->json([
  6404.             'message' => 'Le mail n\'est pas utilisé.',
  6405.             "status" => 200,
  6406.         ]);
  6407.     }
  6408.     /**
  6409.      * @Route("/audioprothesiste/{ville}/{codePostal}/{nomDuCentre}/prise-de-rdv/{id}", name="getCentreByDetails", methods={"GET","HEAD"})
  6410.      */
  6411.     public function getCentreByDetails(string $villestring $codePostalstring $nomDuCentreint $idPublicFunction $publicFunctionRequest $request): Response
  6412.     {
  6413.         // Récupération du centre par ville, code postal et nom
  6414.         $centre $this->getDoctrine()->getRepository(Centre::class)->find($id);
  6415.         if (!$centre) {
  6416.             return new Response(json_encode([
  6417.                 'message' => 'Error, no centre found for these details.',
  6418.                 'path' => 'src/Controller/CentreController.php',
  6419.             ]), 404);
  6420.         }
  6421.         /** @var CentrePrestation[]*/
  6422.         $prestations $this->getDoctrine()->getRepository(CentrePrestation::class)
  6423.             ->findBy(array('id_centre' => $centre->getId()));
  6424.         $resultPrestation = new ArrayCollection();
  6425.         foreach ($prestations as $prestation) {
  6426.             $resultPrestation->add([
  6427.                 "id" => $prestation->getIdPrestation()->getId(),
  6428.                 "titre" => $prestation->getIdPrestation()->getLibelle(),
  6429.             ]);
  6430.         }
  6431.         /** @var CentreMutuelle[]*/
  6432.         $mutuelles $this->getDoctrine()->getRepository(CentreMutuelle::class)
  6433.             ->findBy(array('id_centre' => $centre->getId()));
  6434.         $resultMutuelle = new ArrayCollection();
  6435.         foreach ($mutuelles as $mutuelle) {
  6436.             $resultMutuelle->add([
  6437.                 "id" => $mutuelle->getIdMutuelle()->getId(),
  6438.                 "titre" => $mutuelle->getIdMutuelle()->getLibelle(),
  6439.             ]);
  6440.         }
  6441.         /** @var CentreTier[]*/
  6442.         $tiers $this->getDoctrine()->getRepository(CentreTier::class)
  6443.             ->findBy(array('id_centre' => $centre->getId()));
  6444.         $resultTier = new ArrayCollection();
  6445.         foreach ($tiers as $tier) {
  6446.             $resultTier->add([
  6447.                 "id" => $tier->getIdTier()->getId(),
  6448.                 "titre" => $tier->getIdTier()->getLibelle(),
  6449.             ]);
  6450.         }
  6451.         /** @var AudioCentre[] */
  6452.         $liaisons $this->getDoctrine()->getRepository(AudioCentre::class)
  6453.             ->findBy(array('id_centre' => $centre'isConfirmed' => true));
  6454.         $resultAudio = new ArrayCollection();
  6455.         foreach ($liaisons as $liaison) {
  6456.             /** @var Audio */
  6457.             $audio $this->getDoctrine()->getRepository(Audio::class)
  6458.                 ->findOneBy(array('id' => $liaison->getIdAudio()));
  6459.             // Motifs
  6460.             /** @var AudioMotif[] */
  6461.             $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  6462.                 ->findBy(array('id_audio' => $liaison->getIdAudio()));
  6463.             // will test whether or not the audio has the necessery motif to be added
  6464.             $resultMotif = new ArrayCollection();
  6465.             foreach ($motifs as $motif) {
  6466.                 // ignore deleted motif
  6467.                 if (!$motif->getIsDeleted() && $motif->getType() !== 2)
  6468.                     $resultMotif->add([
  6469.                         "id" => $motif->getIdMotif()->getId(),
  6470.                         "titre" => $motif->getIdMotif()->getTitre(),
  6471.                         "consigne" => $motif->getConsigne(),
  6472.                         "duration" => $motif->getDuration(),
  6473.                     ]);
  6474.             }
  6475.             // Specialities
  6476.             /** @var AudioSpecialite[] */
  6477.             $specialities $this->getDoctrine()->getRepository(AudioSpecialite::class)
  6478.                 ->findBy(array('id_audio' => $liaison->getIdAudio()));
  6479.             //speciality filter
  6480.             $resultSpeciality = new ArrayCollection();
  6481.             foreach ($specialities as $speciality) {
  6482.                 if ($speciality->getIdSpecialite() !== null) {
  6483.                     $resultSpeciality->add([
  6484.                         "id" => $speciality->getIdSpecialite()->getId(),
  6485.                         "titre" => $speciality->getIdSpecialite()->getLibelle(),
  6486.                     ]);
  6487.                 }
  6488.             }
  6489.             //schedule
  6490.             $date = new DateTime();
  6491.             //add audio in the result 
  6492.             if ($centre->getHoraire() == null || $centre->getHoraire() == []) continue;
  6493.             /** @var Rdv[] */
  6494.             $audioRdvs $this->getDoctrine()->getRepository(Rdv::class)
  6495.                 ->findAllReviewsAudio($audio->getId());
  6496.             $resultAudio->add([
  6497.                 "id" => $audio->getId(),
  6498.                 "civilite" => $audio->getCivilite(),
  6499.                 "name" => $audio->getName(),
  6500.                 "lastname" => $audio->getLastname(),
  6501.                 "birthdate" => $audio->getBirthdate(),
  6502.                 "mail" => $audio->getMail(),
  6503.                 "phone" => $audio->getPhone(),
  6504.                 "adeli" => $audio->getAdeli(),
  6505.                 "pin" => $audio->getPin(),
  6506.                 "description" => $audio->getDescription(),
  6507.                 "imgUrl" => $audio->getImgUrl(),
  6508.                 "averageRating" => $publicFunction->calculateRating($audioRdvs),
  6509.                 "nbrReview" => count($audioRdvs),
  6510.                 "motifs" => $resultMotif->toArray(),
  6511.                 "specialities" => $resultSpeciality->toArray(),
  6512.                 "schedule" => [
  6513.                     $publicFunction->calculSchedule($audio, new \DateTime(), $centre),
  6514.                     $publicFunction->calculSchedule($audio$date->add(new DateInterval('P7D')), $centre),
  6515.                     $publicFunction->calculSchedule($audio$date->add(new DateInterval('P14D')), $centre)
  6516.                 ],
  6517.             ]);
  6518.         }
  6519.         /** @var AccessCentre*/
  6520.         $accessCentre $this->getDoctrine()->getRepository(AccessCentre::class)
  6521.             ->findOneBy(array('id_centre' => $centre->getId()));
  6522.         if (!$accessCentre) {
  6523.             $tram = [];
  6524.             $rer = [];
  6525.             $metro = [];
  6526.             $bus = [];
  6527.             $parking = [];
  6528.             $pp = [];
  6529.             $other = [];
  6530.         } else {
  6531.             $metroIDs json_decode($accessCentre->getMetro(), true);
  6532.             $metroNames = array();
  6533.             if ($metroIDs) {
  6534.                 foreach ($metroIDs as $key => $stationID) {
  6535.                     $station $this->getDoctrine()->getRepository(Station::class)->find($stationID);
  6536.                     if ($station) {
  6537.                         $metroNames[$key] = $station->getName();
  6538.                     } else {
  6539.                         $metroNames[$key] = "Station Not Found";
  6540.                     }
  6541.                 }
  6542.             }
  6543.             $tram $accessCentre->getTram();
  6544.             $rer $accessCentre->getRer();
  6545.             $metro $metroNames;
  6546.             $bus $accessCentre->getBus();
  6547.             $parking $accessCentre->getParkingPublic();
  6548.             $pp $accessCentre->getParkingPrivate();
  6549.             $other $accessCentre->getOther();
  6550.         }
  6551.         /** @var Rdv[] */
  6552.         $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  6553.             ->findAllReviewsCentre($centre->getId());
  6554.         // Comment
  6555.         /** @var Rdv[] */
  6556.         $rdvs $this->getDoctrine()->getRepository(Rdv::class)
  6557.             ->findBy(array('id_centre' => $centre));
  6558.         $comments = [];
  6559.         foreach ($rdvs as $rdv)
  6560.             if ($rdv->getComment() && $rdv->getReview() && $rdv->getIdClient())
  6561.                 array_push($comments, [
  6562.                     "id" => $rdv->getIdClient()->getId(),
  6563.                     "name" => $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname()[0] . ".",
  6564.                     "comment" => $rdv->getComment(),
  6565.                     "isMale" => $rdv->getIdClient()->getCivilite() == "Monsieur",
  6566.                     "review" => $rdv->getReview(),
  6567.                 ]);
  6568.         $audioCentre $this->getDoctrine()->getRepository(AudioCentre::class)
  6569.             ->findOneBy(['id_centre' => $centre->getId()]);
  6570.         $audio $this->getDoctrine()->getRepository(Audio::class)
  6571.             ->findOneBy(['id' => $audioCentre->getIdAudio()]);
  6572.         //$doctor = $audio->serialize();
  6573.         return new Response(json_encode([
  6574.             "id" => $centre->getId(),
  6575.             "audio_id" => $centre->getIdGerant()->getId(),
  6576.             "name" => $centre->getName(),
  6577.             "imgUrl" => $centre->getImgUrl(),
  6578.             "isRdvDomicile" => $centre->getIsRdvDomicile(),
  6579.             "address" => $centre->getAddress(),
  6580.             "numero" => $centre->getNumero(),
  6581.             "voie" => $centre->getVoie(),
  6582.             "rue" => $centre->getRue(),
  6583.             "description" => $centre->getDescription(),
  6584.             "postale" => $centre->getPostale(),
  6585.             "city" => $centre->getCity(),
  6586.             "finess" => $centre->getFiness(),
  6587.             "siret" => $centre->getSiret(),
  6588.             "website" => $centre->getWebsite(),
  6589.             "phone" => $centre->getPhone(),
  6590.             "isHandicap" => $centre->getIsHandicap(),
  6591.             "longitude" => $centre->getLongitude(),
  6592.             "latitude" => $centre->getLatitude(),
  6593.             "averageRating" => $publicFunction->calculateRating($centreRdvs),
  6594.             "nbrReview" => count($centreRdvs),
  6595.             "tram" => $tram,
  6596.             "rer" => $rer,
  6597.             "metro" => $metro,
  6598.             "bus" => $bus,
  6599.             "parking" => $parking,
  6600.             "parkingPrivate" => $pp,
  6601.             "other" => $other,
  6602.             "comments" => $comments,
  6603.             "mutuelles" => $resultMutuelle->toArray(),
  6604.             "prestations" => $resultPrestation->toArray(),
  6605.             "tiers" => $resultTier->toArray(),
  6606.             "audio" => $resultAudio->toArray(),
  6607.             "schedule" => $centre->getHoraire(),
  6608.             //"doctor" => $doctor,
  6609.             "status" => 200,
  6610.         ]));
  6611.     }
  6612.     /**
  6613.      * @Route("/centres/generate-url-rdv", name="generateUrlRdvForAllCentres", methods={"POST"})
  6614.      */
  6615.     public function generateUrlRdvForAllCentres(): Response
  6616.     {
  6617.         $entityManager $this->getDoctrine()->getManager();
  6618.         $repository $this->getDoctrine()->getRepository(Centre::class);
  6619.         // Récupération de tous les centres
  6620.         $centres $repository->findAll();
  6621.         if (empty($centres)) {
  6622.             return new Response(json_encode([
  6623.                 'message' => 'No centres found in the database.',
  6624.             ]), 404, ['Content-Type' => 'application/json']);
  6625.         }
  6626.         $baseClient $_ENV['BASE_client'] ?? 'https://default-client-url.com';
  6627.         $updatedCentres = [];
  6628.         foreach ($centres as $centre) {
  6629.             // Récupération des informations nécessaires
  6630.             $id $centre->getId();
  6631.             $name $centre->getName();
  6632.             $city $centre->getCity();
  6633.             $postal $centre->getPostale();
  6634.             // Transformation en URL-friendly
  6635.             $nameSlug strtolower(preg_replace('/[^a-zA-Z0-9]+/''-'trim($name)));
  6636.             $citySlug strtolower(preg_replace('/[^a-zA-Z0-9]+/''-'trim($city)));
  6637.             // Construction de l'URL
  6638.             $urlRdv "{$baseClient}audioprothesiste/{$citySlug}/{$postal}/{$nameSlug}/prise-de-rdvaudioprothesiste-rapide/{$id}";
  6639.             // Mise à jour si l'URL est différente ou inexistante
  6640.             if (!$centre->getUrlRdv() || $centre->getUrlRdv() !== $urlRdv) {
  6641.                 $centre->setUrlRdv($urlRdv);
  6642.                 $entityManager->persist($centre);
  6643.                 $updatedCentres[] = $centre->getId(); // Ajoute l'ID des centres mis à jour
  6644.             }
  6645.         }
  6646.         // Sauvegarde des changements
  6647.         $entityManager->flush();
  6648.         // Retourne une réponse avec les centres mis à jour
  6649.         return new Response(json_encode([
  6650.             'message' => count($updatedCentres) . ' centres updated.',
  6651.             'updatedCentres' => $updatedCentres,
  6652.         ]), 200, ['Content-Type' => 'application/json']);
  6653.     }
  6654.     /**
  6655.      * @Route("/getlogin", name="getAssetsImage", methods={"GET"})
  6656.      */
  6657.     public function getAssetsImage(PublicFunction $publicFunction): Response
  6658.     {
  6659.         return $publicFunction->replyWithFile('images/'"login.png");
  6660.     }
  6661.     /**
  6662.      * @Route("/getloginImg", name="getAssetsImages", methods={"GET"})
  6663.      */
  6664.     public function getAssetsImages(PublicFunction $publicFunction): Response
  6665.     {
  6666.         return $publicFunction->replyWithFile('images/'"Logoblanc.png");
  6667.     }
  6668.     /**
  6669.      * @Route("/getloginImgpdf", name="getAssetsImagespdf", methods={"GET"})
  6670.      */
  6671.     public function getAssetsImagespdf(PublicFunction $publicFunction): Response
  6672.     {
  6673.         return $publicFunction->replyWithFile('images/'"pdflog.png");
  6674.     }
  6675.     /**
  6676.      * @Route("/send-password-email/{audio}", name="send-password-email-audio")
  6677.      */
  6678.     public function sendPassworEmail(Request $requestAudio $audioPublicFunction $publicFunction)
  6679.     {
  6680.         $randomPassword substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 08);
  6681.         $encodedPassword password_hash($randomPasswordPASSWORD_BCRYPT);
  6682.         $audio->setPassword($encodedPassword);
  6683.         $entityManager $this->getDoctrine()->getManager();
  6684.         $entityManager->persist($audio);
  6685.         $entityManager->flush();
  6686.         // send email notif to audio
  6687.         $params = [
  6688.             "nom" => $audio->getName(),
  6689.             "url" => $_ENV['BASE_logiciel'],
  6690.             "password" => $randomPassword,
  6691.             "email" => $audio->getMail(),
  6692.         ];
  6693.         $publicFunction->sendEmail($params$audio->getMail(), "Audioprothésiste""Bienvenue chez MyAudio, complétez vos informations"201);
  6694.         $referer $request->headers->get('referer');
  6695.         if (!$referer) {
  6696.             return $this->redirectToRoute('easyadmin', [
  6697.                 'controller' => 'CentreCrudController',
  6698.                 'action' => 'index',
  6699.             ]);
  6700.         }
  6701.         $this->addFlash('success'"L'audioprothésiste a bien reçu les mails d'activation et de génération de son compte MyAudio Pro.");
  6702.         return $this->redirect($referer);
  6703.     }
  6704.     private function getPostalCodes($entity): string
  6705. {
  6706.     $latitude $entity->getLatitude();
  6707.     $longitude $entity->getLongitude();
  6708.     $radius $entity->getZoneKm();
  6709.     if (empty($radius)) {
  6710.         return "zone de km est pas fournie ou manquante";
  6711.     }
  6712.     $postals $this->regionDepartmentRepository->findPostalsWithinRadius($latitude$longitude$radius);
  6713.     $postalCodes array_values(array_unique(array_column($postals'code_postal')));
  6714.     return implode(', '$postalCodes); 
  6715. }
  6716. private function getPostalCodesMarket($entity): array
  6717. {
  6718.     $latitude $entity->getLatitude();
  6719.     $longitude $entity->getLongitude();
  6720.     $radius $entity->getZoneKm();
  6721.     if (empty($radius)) {
  6722.         return []; 
  6723.     }
  6724.     $postals $this->regionDepartmentRepository->findPostalsWithinRadius($latitude$longitude$radius);
  6725.     $postalCodes array_values(array_unique(array_column($postals'code_postal')));
  6726.     return $postalCodes;  
  6727. }
  6728.   /**
  6729.  * @Route("/admin/cancel-subscription", name="admin_cancel_subscription", methods={"POST"})
  6730.  */
  6731. public function cancelSubscription(Request $request,PublicFunction $publicFunction)
  6732. {
  6733.     $data json_decode($request->getContent(), true);
  6734.     $id $data['id'] ?? null;
  6735.     $motif $data['motif'] ?? null;
  6736.     $status $data['status'] ?? null;
  6737.     $commentaire $data['commentaire'] ?? null;
  6738.     $entityManager $this->getDoctrine()->getManager();
  6739.     $center $entityManager->getRepository(Centre::class)->find($id);
  6740.     if (!$center) {
  6741.         return $this->json(['message' => 'Centre introuvable.'], 404);
  6742.     }
  6743.     if ($status === "blocked") {
  6744.         $existingRecord $entityManager->getRepository(CancellationRecord::class)
  6745.             ->findOneBy(['centre' => $center'status' => 'blocked']);
  6746.         if ($existingRecord) {
  6747.             $existingRecord->setMotif($motif);
  6748.             $existingRecord->setComment($commentaire);
  6749.             $existingRecord->setCreatedAt(new \DateTimeImmutable());
  6750.             $entityManager->flush();
  6751.             return $this->json([
  6752.                 'message' => 'Le centre était déjà bloqué. Les informations ont été mises à jour.',
  6753.                 'status' => 'updated'
  6754.             ]);
  6755.         }
  6756.         $cancellationRecord = new CancellationRecord();
  6757.         $cancellationRecord->setMotif($motif);
  6758.         $cancellationRecord->setComment($commentaire);
  6759.         $cancellationRecord->setCentre($center);
  6760.         $cancellationRecord->setStatus($status);
  6761.         $cancellationRecord->setCreatedAt(new \DateTimeImmutable());
  6762.         $center->setIsBlocked(true);
  6763.         $center->setIsValid(false);
  6764.         $entityManager->persist($cancellationRecord);
  6765.         $entityManager->persist($center);
  6766.         $entityManager->flush();
  6767.         return $this->json(['message' => 'Centre bloqué avec succès.''status' => 'success']);
  6768.     }
  6769. try {
  6770.      $privateKey $_ENV['APP_ENV'] === 'dev'
  6771.             $_ENV['STRIPE_SECRET_KEY_TEST']
  6772.             : $_ENV['STRIPE_SECRET_KEY_LIVE'];
  6773.         \Stripe\Stripe::setApiKey($privateKey);
  6774.         $subscription $entityManager->getRepository(Subscription::class)
  6775.             ->findOneBy(['audio' => $center->getIdGerant()]);
  6776.     
  6777.     if ($subscription) {
  6778.         \Stripe\Subscription::update($subscription->getStripeSubscriptionId(), [
  6779.             'metadata' => [
  6780.                 'cancellation_reason' => $motif,
  6781.                 'comment' => $commentaire,
  6782.             ]
  6783.         ]);
  6784.         \Stripe\Subscription::retrieve($subscription->getStripeSubscriptionId())->cancel();
  6785.     }
  6786. } catch (\Exception $e) {
  6787.     
  6788.     $this->addFlash('warning''Stripe non annulé : ' $e->getMessage());
  6789. }
  6790. $center->setIsResilied(true);
  6791. $center->setIsValid(false);
  6792. $entityManager->persist($center);
  6793. $entityManager->flush();
  6794. $params = [
  6795.     "fullName" => $center->getIdGerant()->getName() . " " $center->getIdGerant()->getLastname(),
  6796.     "date" => (new \DateTime())->format('d/m/Y'),
  6797. ];
  6798. $publicFunction->sendEmail(
  6799.     $params,
  6800.     $center->getIdGerant()->getMail(),
  6801.     "Audioprothésiste",
  6802.     "Confirmation de la résiliation de votre abonnement",
  6803.     227
  6804. );
  6805. return $this->json([
  6806.     'message' => 'L’abonnement a été résilié avec succès',
  6807.     'status' => 'partial_success'
  6808. ]);
  6809. }
  6810. }