src/Controller/CentreController.php line 774

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