src/Controller/CentreController.php line 876

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.        /* $requestData = [
  3543.             "name" => $data["audio"][0]["name"],
  3544.             "email" => $data["audio"][0]["mail"],
  3545.             "address" => $data["address"],
  3546.             "quantity" => $data["quantity"],
  3547.             "price" => $data["price"]["finalPrice"] ?? $data["price"],
  3548.             "recurring" => ($data["price"]["recurring"] === "monthly") ? "month" : (($data["price"]["recurring"] === "yearly") ? "year" : $data["price"]["recurring"]),
  3549.             "paymentMethodId" => $data["paymentMethodId"],
  3550.             "offerName" => $data["plan"]["planName"],
  3551.         ];
  3552.         $createSubscription = $stripeService->createSubscriptionStripe($requestData);*/
  3553.         // dd($createSubscription);
  3554.         $subscriptionData $data['subscription'];
  3555.         $centre = new Centre();
  3556.         $resultAudio = new ArrayCollection();
  3557.         $gerant null;
  3558.         if ($data['gerant'] !== "") {
  3559.             $gerant $this->getDoctrine()
  3560.                 ->getRepository(Audio::class)
  3561.                 ->find($data['gerant']);
  3562.         }
  3563.         if (isset($data["audio"])) {
  3564.             $entityManager $this->getDoctrine()->getManager();
  3565.             foreach ($data["audio"] as $key => $audioMap) {
  3566.                 // check if audio exist to collect on new center 
  3567.                 if ($audioMap['registredAudio'] !== "") {
  3568.                     $audio $this->getDoctrine()
  3569.                         ->getRepository(Audio::class)
  3570.                         ->find($audioMap['registredAudio']);
  3571.                     $audioCentre = new AudioCentre();
  3572.                     $audioCentre->setIdAudio($audio);
  3573.                     $audioCentre->setIdCentre($centre);
  3574.                     $audioCentre->setIsConfirmed(true);
  3575.                     $audioCentre->setHoraire($publicFunction->centreHoraire2);
  3576.                     $entityManager->persist($audioCentre);
  3577.                 } else {
  3578.                     $role $this->getDoctrine()
  3579.                         ->getRepository(Role::class)
  3580.                         ->find($audioMap["role"]);
  3581.                     $audio = new Audio();
  3582.                     $audio->setBirthdate(\DateTime::createFromFormat("d/m/Y"$audioMap["birthdate"]));
  3583.                     $audio->setRole($role);
  3584.                     $audio->setSignupDate(new \DateTime());
  3585.                     $audio->setAdeli($data["audio"]["0"]["adeli"]);
  3586.                     $audio->setCivilite($data["audio"]["0"]["civilite"]);
  3587.                     $audio->setLastName($data["audio"]["0"]["lastname"]);
  3588.                     $audio->setName($data["audio"]["0"]["name"]);
  3589.                     // set notification by default selected
  3590.                     $audio->setConfirmRdvMail(true);
  3591.                     $audio->setConfirmRdvSms(true);
  3592.                     $audio->setModifRdvMail(true);
  3593.                     $audio->setModifRdvSms(true);
  3594.                     $audio->setModifNote(true);
  3595.                     $audioMailTest $this->getDoctrine()
  3596.                         ->getRepository(Audio::class)
  3597.                         ->findOneBy(['mail' => $audioMap["mail"]]);
  3598.                     /*if ($audioMailTest)
  3599.                 return $this->json([
  3600.                     'message' => "L'adresse e-mail est déjà enregistrée.",
  3601.                     'mail' => $audioMap["mail"],
  3602.                     'code' => "mail_exist",
  3603.                     'status' => 409 
  3604.                 ], 500); */
  3605.                     $audio->setMail($audioMap["mail"]);
  3606.                     $audioPhoneTest $this->getDoctrine()
  3607.                         ->getRepository(Audio::class)
  3608.                         ->findOneBy(['phone' => $audioMap["phone"]]);
  3609.                     /*if ($audioPhoneTest)
  3610.                 return $this->json([
  3611.                     'message' => 'Le numéro de téléphone est déjà enregistré.',
  3612.                     'phone' => $audioMap["phone"],
  3613.                     'code' => "phone_exist",
  3614.                     'status' => 409 
  3615.                 ], 500); */
  3616.                     $audio->setPhone($audioMap["phone"]);
  3617.                     //$audio->setAdeli($audioMap["adeli"]);
  3618.                     if ($data["isImported"] !== '')
  3619.                         $audio->setCodeParrainage($data["isImported"]);
  3620.                     $audio->setIsIndie(false);
  3621.                     // set default pass for audio inserted
  3622.                     $audioMap["password"] !== "" $audio->setPassword(password_hash($audioMap["password"], PASSWORD_DEFAULT)) : $audio->setPassword(password_hash("myaudio2023"PASSWORD_DEFAULT));
  3623.                     $audio->setPin($audioMap["pin"]);
  3624.                     // $audio->setDescription($audioMap["description"]);
  3625.                     if (isset($audioMap["imgUrl"]))
  3626.                         $audio->setImgUrl($audioMap["imgUrl"]);
  3627.                     $entityManager $this->getDoctrine()->getManager();
  3628.                     foreach ($audioMap["diplome"] as $diplomeObject) {
  3629.                         $diplome $this->getDoctrine()
  3630.                             ->getRepository(Diplome::class)
  3631.                             ->findOneBy(['id' => $diplomeObject["id"]]);
  3632.                         if ($diplome == null) {
  3633.                             /*$audioDiplome = new AudioDiplome();
  3634.                         if(isset($diplomeObject["year"]))
  3635.                         {
  3636.                             if(!empty($diplomeObject["year"]))
  3637.                             {
  3638.                                 $audioDiplome->setYear($diplomeObject["year"]);
  3639.                             }
  3640.                         }
  3641.                         $audioDiplome->setUrl($diplomeObject["url"]);
  3642.                         $audioDiplome->setOther($data['otherdDiplom'][$key]);
  3643.                         $audioDiplome->setIdAudio($audio);
  3644.                         $entityManager->persist($audioDiplome);*/
  3645.                             return $this->json([
  3646.                                 'message' => 'Error, no diplome found at this id ' $diplomeObject["id"],
  3647.                                 'path' => 'src/Controller/AudioController.php',
  3648.                                 "status" => 401
  3649.                             ], 401);
  3650.                         } else {
  3651.                             $audioDiplome = new AudioDiplome();
  3652.                             if (isset($diplomeObject["year"])) {
  3653.                                 if (!empty($diplomeObject["year"])) {
  3654.                                     $audioDiplome->setYear($diplomeObject["year"]);
  3655.                                 }
  3656.                             }
  3657.                             $audioDiplome->setUrl($diplomeObject["url"]);
  3658.                             $audioDiplome->setIdDiplome($diplome);
  3659.                             $audioDiplome->setIdAudio($audio);
  3660.                             $entityManager->persist($audioDiplome);
  3661.                         }
  3662.                     }
  3663.                     // $entityManager->persist($audio);
  3664.                     $entityManager->persist($this->createPermanantMotif(60"#FF00FF"$audio,  11));
  3665.                     $entityManager->persist($this->createPermanantMotif(90"#00FFFF"$audio,  21));
  3666.                     $entityManager->persist($this->createPermanantMotif(30"#FFFF00"$audio,  31));
  3667.                     $entityManager->persist($this->createPermanantMotif(60"#FF0000"$audio,  41));
  3668.                     $entityManager->persist($this->createPermanantMotif(60"#FFCC59"$audio692));
  3669.                     $entityManager->persist($this->createPermanantMotif(30"#33B679"$audio1061));
  3670.                     $entityManager->persist($this->createPermanantMotif(30"#F6BF25"$audio1071));
  3671.                     $entityManager->persist($this->createPermanantMotif(30"#E67C73"$audio1081));
  3672.                     $entityManager->persist($this->createPermanantMotif(30"#7886CB"$audio1091));
  3673.                     //  $entityManager->persist($this->createPermanantMotif(60, "#FF0000", $audio,  5));
  3674.                     $entityManager->persist($audio);
  3675.                     if ($gerant == null$gerant $audio;
  3676.                     $audioCentre = new AudioCentre();
  3677.                     $audioCentre->setIdAudio($audio);
  3678.                     $audioCentre->setIdCentre($centre);
  3679.                     $audioCentre->setIsConfirmed(true);
  3680.                     $audioCentre->setHoraire($publicFunction->centreHoraire2);
  3681.                     $centerHoliday json_decode($publicFunction->centreHoraire4true);
  3682.                     $audioCentre->setHorairesHoliday($centerHoliday);
  3683.                     $entityManager->persist($audioCentre);
  3684.                     // SEN MAIL NOTIF JUST FOR AUDIOS ADDED NOT FOR GERANT
  3685.                     // $entityManager->flush();
  3686.                 }
  3687.                 $resultAudio->add([
  3688.                     "id" => $audio->getId(),
  3689.                     "civilite" => $audio->getCivilite(),
  3690.                     "name" => $audio->getName(),
  3691.                     "lastname" => $audio->getLastname(),
  3692.                     "birthdate" => $audio->getBirthdate(),
  3693.                     "mail" => $audio->getMail(),
  3694.                     "phone" => $audio->getPhone(),
  3695.                     "adeli" => $audio->getAdeli(),
  3696.                     "pin" => $audio->getPin(),
  3697.                     "description" => $audio->getDescription(),
  3698.                     "imgUrl" => $audio->getImgUrl(),
  3699.                 ]);
  3700.             }
  3701.         } else {
  3702.             return new Response(json_encode([
  3703.                 'message' => 'Error, no audio found',
  3704.                 'path' => 'src/Controller/CentreController.php',
  3705.             ]), 404);
  3706.         }
  3707.         // generate color code 
  3708.         $colors = array(
  3709.             "#FFC0CB"// Pink
  3710.             "#FFD700"// Gold
  3711.             "#90EE90"// Light Green
  3712.             "#87CEFA"// Light Sky Blue
  3713.             "#FFA07A"// Light Salmon
  3714.             "#F0E68C"// Khaki
  3715.             "#B0C4DE"// Light Steel Blue
  3716.             "#98FB98"// Pale Green
  3717.             "#FFB6C1"// Light Pink
  3718.             "#ADD8E6"// Light Blue
  3719.             "#FF69B4"// Hot Pink
  3720.             "#FFA500"// Orange
  3721.             "#00FF7F"// Spring Green
  3722.             "#AFEEEE"// Pale Turquoise
  3723.             "#FF8C00"// Dark Orange
  3724.             "#FFE4B5"// Moccasin
  3725.             "#00CED1"// Dark Turquoise
  3726.             "#7FFFD4"// Aquamarine
  3727.             "#FF4500"// Orange Red
  3728.             "#00FA9A"// Medium Spring Green
  3729.             "#FFF0F5"// Lavender Blush
  3730.             "#00BFFF"// Deep Sky Blue
  3731.             "#FF6347"// Tomato
  3732.             "#20B2AA"// Light Sea Green
  3733.             "#FFFF00"// Yellow
  3734.             "#32CD32"// Lime Green
  3735.             "#FFF5EE"// Seashell
  3736.             "#1E90FF"// Dodger Blue
  3737.             "#CD5C5C"// Indian Red
  3738.             "#8FBC8F"// Dark Sea Green
  3739.             "#F0FFFF"// Azure
  3740.             "#4169E1"// Royal Blue
  3741.             "#FF8B00"// Dark Orange
  3742.             "#66CDAA"// Medium Aquamarine
  3743.             "#FFFACD"// Lemon Chiffon
  3744.             "#6495ED"// Cornflower Blue
  3745.             "#FF7F50"// Coral
  3746.             "#00FF00"// Lime
  3747.             "#FAFAD2"// Light Goldenrod Yellow
  3748.             "#87CEEB"// Sky Blue
  3749.             "#DC143C"// Crimson
  3750.             "#2E8B57"// Sea Green
  3751.             "#F5DEB3"// Wheat
  3752.             "#4682B4"// Steel Blue
  3753.             "#CD853F"// Peru
  3754.             "#8A2BE2"// Blue Violet
  3755.             "#D2691E"// Chocolate
  3756.             "#6A5ACD"// Slate Blue
  3757.             "#F5F5DC"// Beige
  3758.             "#7B68EE"// Medium Slate Blue
  3759.         );
  3760.         // short initial 
  3761.         $name $data['name'];
  3762.         $words explode(' '$name);
  3763.         $initials '';
  3764.         foreach ($words as $word) {
  3765.             $initials .= strtoupper(substr($word01));
  3766.         }
  3767.         $initials strtoupper($initials);
  3768.         $shortName substr($initials02);
  3769.         $randomColor $colors[array_rand($colors)];
  3770.         // generate slug url 
  3771.         $slug $this->slugger->slug($data["name"])->lower();
  3772.         $centre->setName(strtoupper($data["name"]));
  3773.         $slugify $this->getDoctrine()
  3774.             ->getRepository(Centre::class)
  3775.             ->findOneBy(array('slug' => $slug));
  3776.         if ($slugify) {
  3777.             $centre->setSlug($slug "-1");
  3778.         } else {
  3779.             $centre->setSlug($slug);
  3780.         }
  3781.         if (isset($data["imgUrl"]))
  3782.             $centre->setImgUrl($data["imgUrl"]);
  3783.         if (isset($data["finessURL"]))
  3784.             $centre->setFinessUrl($data["finessURL"]);
  3785.         $centre->setIsRdvDomicile($data["isRdvDomicile"]);
  3786.         $centre->setIdGerant($gerant);
  3787.         $centre->setAddress($data["address"]);
  3788.         $centre->setPostale($data["postal"]);
  3789.         $centre->setCity(strtoupper($data["city"]));
  3790.         $centre->setFiness($data["finess"]);
  3791.         $centre->setSocialName($data["companyName"]);
  3792.         $centre->setSiret($data["siret"]);
  3793.         $centre->setInitial($shortName);
  3794.         $centre->setWebsite($data["website"]);
  3795.         $centre->setSignupDate(new \DateTime());
  3796.         $centre->setCalendarColor($randomColor);
  3797.         // set the galeries for images by default
  3798.         // Define an array of default image URLs
  3799.         $defaultImages = ["by-default-1.jpeg""by-default-2.jpeg""by-default-3.jpeg"];
  3800.         // Iterate through each default image
  3801.         foreach ($defaultImages as $imageUrl) {
  3802.             $centerImage = new CenterImage();
  3803.             $centerImage->setType("image");
  3804.             $centerImage->setUrl($imageUrl);
  3805.             // Associate the center image with the current center
  3806.             $centerImage->setCenter($centre);
  3807.             $entityManager->persist($centerImage);
  3808.         }
  3809.         /*$centrePhoneTest = $this->getDoctrine()
  3810.             ->getRepository(Centre::class)
  3811.             ->findOneBy(['phone' => $data["phone"]]);
  3812.         if ($centrePhoneTest)
  3813.             return $this->json([
  3814.                 'message' => 'Centre phone',
  3815.                 'path' => 'src/Controller/CentreController.php',
  3816.                 "status" => 401
  3817.             ], 401);*/
  3818.         $centre->setPhone($data["phone"]);
  3819.         $centre->setIsHandicap($data["isHandicap"]);
  3820.         $centre->setLongitude($data["longitude"]);
  3821.         $centre->setLatitude($data["latitude"]);
  3822.         $centre->setHoraire($publicFunction->centreHoraire2);
  3823.         $centerHoliday json_decode($publicFunction->centreHoraire4true);
  3824.         $centre->setHorairesHoliday($centerHoliday);
  3825.         $centre->setZoneKm(5);
  3826.        
  3827.        
  3828.        
  3829.         $entityManager $this->getDoctrine()->getManager();
  3830.         $entityManager->persist($centre);
  3831.         // for audio on multi centre creation
  3832.         
  3833.          
  3834.         $accessCentre = new AccessCentre();
  3835.         //  $accessData = $data["access"];
  3836.         $entityManager->flush();
  3837.         // save print setting 
  3838.         $setting = new Setting();
  3839.         $setting->setName($data["name"]);
  3840.         $setting->setAddress($data["address"]);
  3841.         $setting->setPhone($data["phone"]);
  3842.         $setting->setLogoUrl($centre->getImgUrl());
  3843.         $setting->setWebsite($data["website"]);
  3844.         $setting->setFirstname($audio->getName());
  3845.         $setting->setLastname($audio->getLastname());
  3846.         $setting->setEmail($gerant->getMail());
  3847.         $setting->setSeuilCaDroite(true);
  3848.         $setting->setSeuilCaGauche(true);
  3849.         $setting->setSeuilConfortDroite(true);
  3850.         $setting->setSeuilConfortGauche(true);
  3851.         $setting->setSeuilinconfortDroite(true);
  3852.         $setting->setSeuilInConfortGauche(true);
  3853.         $setting->setSeuilCoDroite(true);
  3854.         $setting->setSeuilCoGauche(true);
  3855.         $setting->setSeuilCaMaskingDroite(true);
  3856.         $setting->setSeuilCaMaskingGauche(true);
  3857.         $setting->setSeuilCoMaskingDroite(true);
  3858.         $setting->setSeuilCoMaskingGauche(true);
  3859.         /* $setting->setCasqueDroite(false);
  3860.         $setting->setCasqueGauche(false);
  3861.         $setting->setCasqueBinaural(false);
  3862.         $setting->setChampsLibreDroite(false);
  3863.         $setting->setChampsLibreGauche(false);
  3864.         $setting->setChampsLibreBinaural(false);
  3865.         $setting->setChampsLibreAppDroite(false);
  3866.         $setting->setChampsLibreAppGauche(false);
  3867.         $setting->setChampsLibreAppBinaural(false);*/
  3868.         $setting->setCasqueDroite(true);
  3869.         $setting->setCasqueGauche(true);
  3870.         $setting->setCasqueBinaural(true);
  3871.         $setting->setChampsLibreDroite(true);
  3872.         $setting->setChampsLibreGauche(true);
  3873.         $setting->setChampsLibreBinaural(true);
  3874.         $setting->setChampsLibreAppDroite(true);
  3875.         $setting->setChampsLibreAppGauche(true);
  3876.         $setting->setChampsLibreAppBinaural(true);
  3877.         $setting->setCentre($centre);
  3878.         $entityManager->persist($setting);
  3879.         $entityManager->flush();
  3880.         $tokenString $publicFunction->generateRandomString(30);
  3881.         $params = array(
  3882.             "lien" => "{$_ENV['BASE_client']}confirmation_email/{$data["audio"][0]["mail"]}?token={$tokenString}",
  3883.             "nom" => "",
  3884.             "texte" => "Veuillez cliquer sur le bouton ci-dessous pour confirmer votre adresse mail",
  3885.             "titre" => "Confirmer mon email",
  3886.             "bouton" => "Confirmer mon Email",
  3887.         );
  3888.         $publicFunction->sendEmail($params$data["audio"][0]["mail"], "myaudio""Confirmation d'inscription sur My Audio Pro"122);
  3889.         $token = new Token();
  3890.         $token->setCreationDate(new DateTime());
  3891.         $token->setToken($tokenString);
  3892.         $token->setMail($audio->getMail());
  3893.         $entityManager $this->getDoctrine()->getManager();
  3894.         $entityManager->persist($token);
  3895.         $entityManager->flush();
  3896.              // create the sheet of ads
  3897.              $postales $this->getPostalCodes($centre);
  3898.              $dataSheet = [
  3899.                  $centre->getId() ?? ''// id centre
  3900.                  $centre->getName() ?? '',  // Nom
  3901.                  $centre->getCity() ?? '',  // ville
  3902.                  $centre->getLongitude() ?? ''// longitude
  3903.                  $centre->getLatitude() ?? '',  // lattitude
  3904.                  $centre->getZoneKm() ?? '',  // zone km
  3905.                  ($centre->getIdGerant()->getLastName() ?? '') . ' ' . ($centre->getIdGerant()->getName() ?? ''),
  3906.                  $centre->getAddress() ?? '',
  3907.                  $centre->getPostale() ?? '',
  3908.                  $postales ?? '' // in case postales is missing
  3909.              ];
  3910.              
  3911.          
  3912.              $this->googleSheetsService->appendToSheetZoneKm($dataSheet'centersByZoneKm');
  3913.         
  3914.              // create the sheet of marketing
  3915.              $entityManager $this->getDoctrine()->getManager();
  3916.              $sheetName 'AIntegrer';
  3917.              
  3918.              // Get already existing postals from column D
  3919.              $existingValues $this->googleSheetsService->getColumnValues($sheetName4); // column D
  3920.              $existingPostales array_filter($existingValues); 
  3921.              $existingPostales array_map('strval'$existingPostales); 
  3922.              
  3923.              if (!$centre) {
  3924.                  throw new \Exception('Centre not found.');
  3925.              }
  3926.              
  3927.              $rowsToAppend = [];
  3928.              
  3929.              $postales $this->getPostalCodesMarket($centre);
  3930.              $postales array_unique($postales);
  3931.              
  3932.              $newPostales array_diff($postales$existingPostales);
  3933.              $newPostales array_values($newPostales); // reset keys
  3934.              
  3935.              if (count($newPostales) > 0) {
  3936.                  $now = (new \DateTime())->format('d/m/Y');
  3937.                  $centerPostal $centre->getPostale();
  3938.              
  3939.                  foreach ($newPostales as $index => $postal) {
  3940.                      if ($index === 0) {
  3941.                          $rowsToAppend[] = [false$now$centerPostal$postal];
  3942.                      } else {
  3943.                          $rowsToAppend[] = [''''''$postal];
  3944.                      }
  3945.                  }
  3946.              
  3947.                  $this->googleSheetsService->appendToSheetMarketing($rowsToAppend$sheetName);
  3948.              }
  3949.              
  3950.         /* $user = [
  3951.             "prenomAudioprothesiste" => $gerant->getName(),
  3952.             "urlDemo" => "https://calendar.google.com/calendar/u/0/appointments/schedules/AcZssZ0Ry72UDE9m8d2IylSycOMQVerlY0jHt1DLWFD6Pso4hg79sQ9nUAlxtZYOPH6wSubDX4vqVQWh",
  3953.         ];
  3954.         // we send parametre for the trait methid
  3955.         $params = $this->emailNotificationDemoService->prepareEmailParams($user);
  3956.         // send email notifcation
  3957.         $this->emailNotificationDemoService->sendEmail($params, $gerant->getMail(), 'Organisez votre Démo personnalisée de My Audio Pro', 143);
  3958.         */
  3959.         // set order datable patient 
  3960.         $this->orderPatient->createOrderPatient($audio);
  3961.         $plan $this->getDoctrine()->getRepository(Plan::class)
  3962.             ->findOneBy(["slug" => $data['plan']["planName"]]);
  3963.         $dataSubsc = [];
  3964.               $dataSubsc['created'] = $subscriptionData['created'];
  3965.         $dataSubsc['currentPeriodStart'] = $subscriptionData['current_period_start'];
  3966.         $dataSubsc['currentPeriodEnd'] = $subscriptionData['current_period_end'];
  3967.         $dataSubsc['centerId'] = $centre->getId();
  3968.         $dataSubsc['audioId'] = $audio->getId();
  3969.         $dataSubsc['id'] = $subscriptionData['subscriptionId'];
  3970.         $dataSubsc['invoiceId'] = $subscriptionData['invoiceId'];
  3971.         $dataSubsc['customer'] = $subscriptionData['customerId'];
  3972.         $dataSubsc['payment_method'] = $subscriptionData['default_payment_method'];
  3973.         $dataSubsc['amount'] = $data["price"]["finalPrice"] ?? $data["price"];
  3974.         $dataSubsc['quantity'] = $data["quantity"];
  3975.         $dataSubsc['recurring'] = ($data["price"]["recurring"] === "monthly") ? "month" 
  3976.         (($data["price"]["recurring"] === "yearly") ? "year" $data["price"]["recurring"]);
  3977.         $dataSubsc['planId'] = $plan->getId();
  3978.         $dataSubsc['status'] = "succeeded";
  3979.         //$this->logger->info("stripe end date",["endDate" => $currentPeriodEnd->format('Y-m-d H:i:s')]);
  3980.         $subscrition->createSubscription($dataSubsc);
  3981.         //$this->logger->info("databse end date",["endDate" => $sub]);
  3982.         // generate rdvurl
  3983.         $name $centre->getName();
  3984.         $city $centre->getCity();
  3985.         $postal $centre->getPostale();
  3986.         $nameSlug strtolower(preg_replace('/[^a-zA-Z0-9]+/''-'trim($name)));
  3987.         $citySlug strtolower(preg_replace('/[^a-zA-Z0-9]+/''-'trim($city)));
  3988.         $baseClient $_ENV['BASE_client'] ?? 'https://default-client-url.com';
  3989.         $urlRdv "{$baseClient}audioprothesiste/{$citySlug}/{$postal}/{$nameSlug}/prise-de-rdvaudioprothesiste-rapide/{$centre->getId()}";
  3990.         if (!$centre->getUrlRdv() || $centre->getUrlRdv() !== $urlRdv) {
  3991.             $centre->setUrlRdv($urlRdv);
  3992.             $entityManager->persist($centre);
  3993.             $entityManager->flush();
  3994.         }
  3995.         // post categorie de contrat cda
  3996.         $quantity $data["quantity"];
  3997.         $contractCategory $entityManager->getRepository(ContractCategory::class)->find(5);
  3998.         $plan $entityManager->getRepository(Plan::class)->find($plan->getId());
  3999.         if ($contractCategory && $plan && $quantity 0) {
  4000.             $specificSubscription = new SpecificSubscription();
  4001.             $specificSubscription->setContractCategory($contractCategory);
  4002.             $specificSubscription->setPlan($plan);
  4003.             $specificSubscription->setQuantity($quantity);
  4004.             $specificSubscription->setCenter($centre);
  4005.             $specificSubscription->setStatus(false);
  4006.             $specificSubscription->setAudio($audio);
  4007.             $entityManager->persist($specificSubscription);
  4008.             $entityManager->flush();
  4009.         }
  4010.     // Find the audio/user who owns the referral code
  4011.     $referrer $audio// the user who shared the code
  4012.     // Make sure key exists
  4013.     $codeParrain $data['codeParrain'] ?? null;  // null if not provided
  4014.     if ($codeParrain) {
  4015.       // Find the new user/referee who is using the code 
  4016.       $referee $entityManager->getRepository(Audio::class)->findOneBy([
  4017.           'referralCode' => $codeParrain
  4018.       ]);
  4019.     if ($referee) {
  4020.         $referral = new Referral();
  4021.         $referral->setReferrerType('audio'); 
  4022.         $referral->setReferrerId($referrer->getId()); 
  4023.         $referral->setRefereeType('audio'); 
  4024.         $referral->setRefereeId($referee->getId()); 
  4025.         $referral->setCodeUsed($codeParrain); 
  4026.         $referral->setStatus('completed');
  4027.         $referral->setRewardAmount(100); 
  4028.         $referral->setCreatedAt(new \DateTime());
  4029.         $entityManager->persist($referral);
  4030.         $entityManager->flush();
  4031.     }
  4032.     
  4033.     $stripeService->refundReferralReward($referee->getId());
  4034.     }
  4035.         return $this->json([
  4036.             "audioId" => $audio->getId(),
  4037.             "centerId" => $centre->getId(),
  4038.             "name" => $centre->getName(),
  4039.             "imgUrl" => $centre->getImgUrl(),
  4040.             "isRdvDomicile" => $centre->getIsRdvDomicile(),
  4041.             "audio_id" => $centre->getIdGerant()->getId(),
  4042.             "address" => $centre->getAddress(),
  4043.             "postale" => $centre->getPostale(),
  4044.             "city" => $centre->getCity(),
  4045.             "finess" => $centre->getFiness(),
  4046.             "siret" => $centre->getSiret(),
  4047.             "website" => $centre->getWebsite(),
  4048.             "phone" => $centre->getPhone(),
  4049.             "isHandicap" => $centre->getIsHandicap(),
  4050.             //"audio" => $resultAudio->toArray(),
  4051.             "centerId" => $centre->getId(),
  4052.             "audioId" => $audio->getId(),
  4053.             "status" => 200,
  4054.         ]);
  4055.     }
  4056.     
  4057. /**
  4058.      * @Route("/centre/new-inscription-atol", name="postCentreNewInscriptionAtol", methods={"POST"})
  4059.      */
  4060.     public function postCentreNewInscriptionAtol(Request $requestPublicFunction $publicFunctionStripeService $stripeServiceSubscriptionService $subscritionBillingAtolService $invoiceAtol): Response
  4061.     {
  4062.         $data json_decode($request->getContent(), true);
  4063.       //  dd($data);
  4064.       /*  $requestData = [
  4065.             "name" => $data["audio"][0]["name"],
  4066.             "email" => $data["audio"][0]["mail"],
  4067.             "address" => $data["address"],
  4068.             "quantity" => $data["quantity"],
  4069.             "price" => $data["price"]["finalPrice"] ?? $data["price"],
  4070.             "recurring" => "atol",
  4071.             "paymentMethodId" => $data["paymentMethodId"],
  4072.             "offerName" => $data["plan"]["planName"],
  4073.         ];
  4074.         
  4075.        $createSubscription = $stripeService->createSubscriptionStripe($requestData);
  4076.       */
  4077.        // dd($createSubscription);
  4078.         $subscriptionData $data['subscription'];
  4079.         $centre = new Centre();
  4080.         $resultAudio = new ArrayCollection();
  4081.         $gerant null;
  4082.         if($data['gerant'] !== "")
  4083.                {
  4084.                 $gerant $this->getDoctrine()
  4085.                 ->getRepository(Audio::class)
  4086.                 ->find($data['gerant']);
  4087.                }
  4088.         if (isset($data["audio"])) {
  4089.             $entityManager $this->getDoctrine()->getManager();
  4090.             foreach ($data["audio"] as $key=>$audioMap) {
  4091.                // check if audio exist to collect on new center 
  4092.                if($audioMap['registredAudio'] !== "")
  4093.                {
  4094.                    $audio $this->getDoctrine()
  4095.                    ->getRepository(Audio::class)
  4096.                    ->find($audioMap['registredAudio']);
  4097.                    $audioCentre = new AudioCentre();
  4098.                    $audioCentre->setIdAudio($audio);
  4099.                    $audioCentre->setIdCentre($centre);
  4100.                    $audioCentre->setIsConfirmed(true);
  4101.                    $audioCentre->setHoraire($publicFunction->centreHoraire2);
  4102.                    $entityManager->persist($audioCentre);
  4103.                }
  4104.                
  4105.                else {
  4106.                $role $this->getDoctrine()
  4107.                ->getRepository(Role::class)
  4108.                ->find($audioMap["role"]);
  4109.                $audio = new Audio();
  4110.                
  4111.                $audio->setBirthdate(\DateTime::createFromFormat("d/m/Y"$audioMap["birthdate"]));
  4112.                $audio->setRole($role);
  4113.                $audio->setSignupDate(new \DateTime());
  4114.                $audio->setAdeli($data["audio"]["0"]["adeli"]);
  4115.                $audio->setCivilite($data["audio"]["0"]["civilite"]);
  4116.                $audio->setLastName($data["audio"]["0"]["lastname"]);
  4117.                $audio->setName($data["audio"]["0"]["name"]);
  4118.                // set notification by default selected
  4119.                $audio->setConfirmRdvMail(true);
  4120.                $audio->setConfirmRdvSms(true);
  4121.                $audio->setModifRdvMail(true);
  4122.                $audio->setModifRdvSms(true);
  4123.                $audio->setModifNote(true);
  4124.                $audioMailTest $this->getDoctrine()
  4125.                    ->getRepository(Audio::class)
  4126.                    ->findOneBy(['mail' => $audioMap["mail"]]);
  4127.                 /*if ($audioMailTest)
  4128.                 return $this->json([
  4129.                     'message' => "L'adresse e-mail est déjà enregistrée.",
  4130.                     'mail' => $audioMap["mail"],
  4131.                     'code' => "mail_exist",
  4132.                     'status' => 409 
  4133.                 ], 500); */
  4134.                 
  4135.                 $audio->setMail($audioMap["mail"]);
  4136.                 $audioPhoneTest $this->getDoctrine()
  4137.                     ->getRepository(Audio::class)
  4138.                     ->findOneBy(['phone' => $audioMap["phone"]]);
  4139.                 /*if ($audioPhoneTest)
  4140.                 return $this->json([
  4141.                     'message' => 'Le numéro de téléphone est déjà enregistré.',
  4142.                     'phone' => $audioMap["phone"],
  4143.                     'code' => "phone_exist",
  4144.                     'status' => 409 
  4145.                 ], 500); */
  4146.                 
  4147.                 $audio->setMailValid(true);
  4148.                 $audio->setPhone($audioMap["phone"]);
  4149.                 //$audio->setAdeli($audioMap["adeli"]);
  4150.                 if($data["isImported"] !== '')
  4151.                 $audio->setCodeParrainage($data["isImported"]);
  4152.                 $audio->setIsIndie(false);
  4153.                 // set default pass for audio inserted
  4154.                 $audioMap["password"] !== "" $audio->setPassword(password_hash($audioMap["password"], PASSWORD_DEFAULT)) : $audio->setPassword(password_hash("myaudio2023"PASSWORD_DEFAULT));
  4155.                 $audio->setPin($audioMap["pin"]);
  4156.                // $audio->setDescription($audioMap["description"]);
  4157.                 if (isset($audioMap["imgUrl"]))
  4158.                     $audio->setImgUrl($audioMap["imgUrl"]);
  4159.                 $entityManager $this->getDoctrine()->getManager();
  4160.                 foreach ($audioMap["diplome"] as $diplomeObject) {
  4161.                     $diplome $this->getDoctrine()
  4162.                         ->getRepository(Diplome::class)
  4163.                         ->findOneBy(['id' => $diplomeObject["id"]]);
  4164.                     if ($diplome == null) {
  4165.                         /*$audioDiplome = new AudioDiplome();
  4166.                         if(isset($diplomeObject["year"]))
  4167.                         {
  4168.                             if(!empty($diplomeObject["year"]))
  4169.                             {
  4170.                                 $audioDiplome->setYear($diplomeObject["year"]);
  4171.                             }
  4172.                         }
  4173.                         $audioDiplome->setUrl($diplomeObject["url"]);
  4174.                         $audioDiplome->setOther($data['otherdDiplom'][$key]);
  4175.                         $audioDiplome->setIdAudio($audio);
  4176.                         $entityManager->persist($audioDiplome);*/
  4177.                         return $this->json([
  4178.                             'message' => 'Error, no diplome found at this id ' $diplomeObject["id"],
  4179.                             'path' => 'src/Controller/AudioController.php',
  4180.                             "status" => 401
  4181.                         ], 401);
  4182.                     } else {
  4183.                         $audioDiplome = new AudioDiplome();
  4184.                         if(isset($diplomeObject["year"]))
  4185.                         {
  4186.                             if(!empty($diplomeObject["year"]))
  4187.                             {
  4188.                                 $audioDiplome->setYear($diplomeObject["year"]);
  4189.                             }
  4190.                         }
  4191.                         $audioDiplome->setUrl($diplomeObject["url"]);
  4192.                         $audioDiplome->setIdDiplome($diplome);
  4193.                         $audioDiplome->setIdAudio($audio);
  4194.                         $entityManager->persist($audioDiplome);
  4195.                     }
  4196.                 }
  4197.                
  4198.                 
  4199.       
  4200.                // $entityManager->persist($audio);
  4201.                $entityManager->persist($this->createPermanantMotif(60"#FF00FF"$audio,  11));
  4202.                 $entityManager->persist($this->createPermanantMotif(90"#00FFFF"$audio,  21));
  4203.                 $entityManager->persist($this->createPermanantMotif(30"#FFFF00"$audio,  31));
  4204.                 $entityManager->persist($this->createPermanantMotif(60"#FF0000"$audio,  41));
  4205.                 $entityManager->persist($this->createPermanantMotif(60"#FFCC59"$audio692));
  4206.                 $entityManager->persist($this->createPermanantMotif(30"#33B679"$audio1061));
  4207.                 $entityManager->persist($this->createPermanantMotif(30"#F6BF25"$audio1071));
  4208.                 $entityManager->persist($this->createPermanantMotif(30"#E67C73"$audio1081));
  4209.                 $entityManager->persist($this->createPermanantMotif(30"#7886CB"$audio1091));
  4210.               //  $entityManager->persist($this->createPermanantMotif(60, "#FF0000", $audio,  5));
  4211.                 $entityManager->persist($audio);
  4212.                 if ($gerant == null$gerant $audio;
  4213.                 $audioCentre = new AudioCentre();
  4214.                 $audioCentre->setIdAudio($audio);
  4215.                 $audioCentre->setIdCentre($centre);
  4216.                 $audioCentre->setIsConfirmed(true);
  4217.                 $audioCentre->setHoraire($publicFunction->centreHoraire2);
  4218.                 $centerHoliday json_decode($publicFunction->centreHoraire4true);
  4219.                 $audioCentre->setHorairesHoliday($centerHoliday);
  4220.                 $entityManager->persist($audioCentre);
  4221.                 // SEN MAIL NOTIF JUST FOR AUDIOS ADDED NOT FOR GERANT
  4222.                
  4223.                 
  4224.        // $entityManager->flush();
  4225.                
  4226.             }
  4227.                 $resultAudio->add([
  4228.                     "id" => $audio->getId(),
  4229.                     "civilite" => $audio->getCivilite(),
  4230.                     "name" => $audio->getName(),
  4231.                     "lastname" => $audio->getLastname(),
  4232.                     "birthdate" => $audio->getBirthdate(),
  4233.                     "mail" => $audio->getMail(),
  4234.                     "phone" => $audio->getPhone(),
  4235.                     "adeli" => $audio->getAdeli(),
  4236.                     "pin" => $audio->getPin(),
  4237.                     "description" => $audio->getDescription(),
  4238.                     "imgUrl" => $audio->getImgUrl(),
  4239.                 ]);
  4240.             }
  4241.         } else {
  4242.             return new Response(json_encode([
  4243.                 'message' => 'Error, no audio found',
  4244.                 'path' => 'src/Controller/CentreController.php',
  4245.             ]), 404);
  4246.         }
  4247.         // generate color code 
  4248.         $colors = array(
  4249.             "#FFC0CB"// Pink
  4250.             "#FFD700"// Gold
  4251.             "#90EE90"// Light Green
  4252.             "#87CEFA"// Light Sky Blue
  4253.             "#FFA07A"// Light Salmon
  4254.             "#F0E68C"// Khaki
  4255.             "#B0C4DE"// Light Steel Blue
  4256.             "#98FB98"// Pale Green
  4257.             "#FFB6C1"// Light Pink
  4258.             "#ADD8E6"// Light Blue
  4259.             "#FF69B4"// Hot Pink
  4260.             "#FFA500"// Orange
  4261.             "#00FF7F"// Spring Green
  4262.             "#AFEEEE"// Pale Turquoise
  4263.             "#FF8C00"// Dark Orange
  4264.             "#FFE4B5"// Moccasin
  4265.             "#00CED1"// Dark Turquoise
  4266.             "#7FFFD4"// Aquamarine
  4267.             "#FF4500"// Orange Red
  4268.             "#00FA9A"// Medium Spring Green
  4269.             "#FFF0F5"// Lavender Blush
  4270.             "#00BFFF"// Deep Sky Blue
  4271.             "#FF6347"// Tomato
  4272.             "#20B2AA"// Light Sea Green
  4273.             "#FFFF00"// Yellow
  4274.             "#32CD32"// Lime Green
  4275.             "#FFF5EE"// Seashell
  4276.             "#1E90FF"// Dodger Blue
  4277.             "#CD5C5C"// Indian Red
  4278.             "#8FBC8F"// Dark Sea Green
  4279.             "#F0FFFF"// Azure
  4280.             "#4169E1"// Royal Blue
  4281.             "#FF8B00"// Dark Orange
  4282.             "#66CDAA"// Medium Aquamarine
  4283.             "#FFFACD"// Lemon Chiffon
  4284.             "#6495ED"// Cornflower Blue
  4285.             "#FF7F50"// Coral
  4286.             "#00FF00"// Lime
  4287.             "#FAFAD2"// Light Goldenrod Yellow
  4288.             "#87CEEB"// Sky Blue
  4289.             "#DC143C"// Crimson
  4290.             "#2E8B57"// Sea Green
  4291.             "#F5DEB3"// Wheat
  4292.             "#4682B4"// Steel Blue
  4293.             "#CD853F"// Peru
  4294.             "#8A2BE2"// Blue Violet
  4295.             "#D2691E"// Chocolate
  4296.             "#6A5ACD"// Slate Blue
  4297.             "#F5F5DC"// Beige
  4298.             "#7B68EE"// Medium Slate Blue
  4299.         );
  4300.         // short initial 
  4301.         $name $data['name'];
  4302. $words explode(' '$name);
  4303. $initials '';
  4304. foreach ($words as $word) {
  4305.     $initials .= strtoupper(substr($word01));
  4306. }
  4307. $initials strtoupper($initials);
  4308. $shortName substr($initials02);
  4309.         $randomColor $colors[array_rand($colors)];
  4310.         // generate slug url 
  4311.         $slug $this->slugger->slug($data["name"])->lower();
  4312.         $centre->setName(strtoupper($data["name"]));
  4313.         $slugify $this->getDoctrine() 
  4314.         ->getRepository(Centre::class)
  4315.         ->findOneBy(array('slug' => $slug));
  4316.         
  4317.         if($slugify)
  4318.         {
  4319.             $centre->setSlug($slug."-1");
  4320.         }
  4321.         else 
  4322.         {
  4323.             $centre->setSlug($slug);
  4324.         }
  4325.         if (isset($data["imgUrl"]))
  4326.             $centre->setImgUrl($data["imgUrl"]);
  4327.         if (isset($data["finessURL"]))
  4328.         $centre->setFinessUrl($data["finessURL"]);
  4329.         $centre->setIsRdvDomicile($data["isRdvDomicile"]);
  4330.         $centre->setIdGerant($gerant);
  4331.         $centre->setAddress($data["address"]);
  4332.         $centre->setPostale($data["postal"]);
  4333.         $centre->setCity(strtoupper($data["city"]));
  4334.         $centre->setFiness($data["finess"]);
  4335.         $centre->setSocialName($data["companyName"]);
  4336.         $centre->setSiret($data["siret"]);
  4337.         $centre->setInitial($shortName);
  4338.         $centre->setWebsite($data["website"]);
  4339.         $centre->setSignupDate(new \DateTime());
  4340.         $centre->setCalendarColor($randomColor);
  4341.         $centre->setZoneKm(5);
  4342.         
  4343.         // set the galeries for images by default
  4344.         // Define an array of default image URLs
  4345.         $defaultImages = ["by-default-1.jpeg""by-default-2.jpeg""by-default-3.jpeg"];
  4346.         // Iterate through each default image
  4347.        foreach ($defaultImages as $imageUrl) {
  4348.         $centerImage = new CenterImage();
  4349.         $centerImage->setType("image");
  4350.         $centerImage->setUrl($imageUrl);
  4351.         // Associate the center image with the current center
  4352.         $centerImage->setCenter($centre);
  4353.         $entityManager->persist($centerImage);
  4354.          }
  4355.         /*$centrePhoneTest = $this->getDoctrine()
  4356.             ->getRepository(Centre::class)
  4357.             ->findOneBy(['phone' => $data["phone"]]);
  4358.         if ($centrePhoneTest)
  4359.             return $this->json([
  4360.                 'message' => 'Centre phone',
  4361.                 'path' => 'src/Controller/CentreController.php',
  4362.                 "status" => 401
  4363.             ], 401);*/
  4364.         $centre->setPhone($data["phone"]);
  4365.         $centre->setIsHandicap($data["isHandicap"]);
  4366.         $centre->setLongitude($data["longitude"]);
  4367.         $centre->setLatitude($data["latitude"]);
  4368.         $centre->setHoraire($publicFunction->centreHoraire2);
  4369.         $centerHoliday json_decode($publicFunction->centreHoraire4true);
  4370.         $centre->setHorairesHoliday($centerHoliday);
  4371.        
  4372.         $atolAudition $this->getDoctrine()
  4373.             ->getRepository(AtoLauditionPartner::class)->findOneBy(["codeMag" => $data["codeAdherant"]]);
  4374.         $centre->setAtoLauditionPartner($atolAudition);
  4375.         $entityManager $this->getDoctrine()->getManager();
  4376.         
  4377.             
  4378.         $entityManager->persist($centre);
  4379.         // for audio on multi centre creation
  4380.         $accessCentre = new AccessCentre();
  4381.         
  4382.         //  $accessData = $data["access"];
  4383.   
  4384.         $entityManager->flush();
  4385.         // save print setting 
  4386.  
  4387.         $setting = new Setting();
  4388.         $setting->setName($data["name"]);
  4389.         $setting->setAddress($data["address"]);
  4390.         $setting->setPhone($data["phone"]);
  4391.         $setting->setLogoUrl($centre->getImgUrl());
  4392.         $setting->setWebsite($data["website"]);
  4393.         $setting->setFirstname($audio->getName());
  4394.         $setting->setLastname($audio->getLastname());
  4395.         $setting->setEmail($gerant->getMail());
  4396.         $setting->setSeuilCaDroite(true);
  4397.         $setting->setSeuilCaGauche(true);
  4398.         $setting->setSeuilConfortDroite(true);
  4399.         $setting->setSeuilConfortGauche(true);
  4400.         $setting->setSeuilinconfortDroite(true);
  4401.         $setting->setSeuilInConfortGauche(true);
  4402.         $setting->setSeuilCoDroite(true);
  4403.         $setting->setSeuilCoGauche(true);
  4404.         $setting->setSeuilCaMaskingDroite(true);
  4405.         $setting->setSeuilCaMaskingGauche(true);
  4406.         $setting->setSeuilCoMaskingDroite(true);
  4407.         $setting->setSeuilCoMaskingGauche(true);
  4408.        /* $setting->setCasqueDroite(false);
  4409.         $setting->setCasqueGauche(false);
  4410.         $setting->setCasqueBinaural(false);
  4411.         $setting->setChampsLibreDroite(false);
  4412.         $setting->setChampsLibreGauche(false);
  4413.         $setting->setChampsLibreBinaural(false);
  4414.         $setting->setChampsLibreAppDroite(false);
  4415.         $setting->setChampsLibreAppGauche(false);
  4416.         $setting->setChampsLibreAppBinaural(false);*/
  4417.         $setting->setCasqueDroite(true);
  4418.         $setting->setCasqueGauche(true);
  4419.         $setting->setCasqueBinaural(true);
  4420.         $setting->setChampsLibreDroite(true);
  4421.         $setting->setChampsLibreGauche(true);
  4422.         $setting->setChampsLibreBinaural(true);
  4423.         $setting->setChampsLibreAppDroite(true);
  4424.         $setting->setChampsLibreAppGauche(true);
  4425.         $setting->setChampsLibreAppBinaural(true);
  4426.         $setting->setCentre($centre);
  4427.         $entityManager->persist($setting);
  4428.         $entityManager->flush();
  4429.  $tokenString $publicFunction->generateRandomString(30);
  4430.       /*  $params = array(  
  4431.             "lien" =>"{$_ENV['BASE_client']}confirmation_email/{$data["audio"][0]["mail"]}?token={$tokenString}",
  4432.             "nom" =>"",
  4433.             "texte" =>"Veuillez cliquer sur le bouton ci-dessous pour confirmer votre adresse mail",
  4434.             "titre"=> "Confirmer mon email",
  4435.             "bouton"=> "Confirmer mon Email",
  4436.         );
  4437.         $publicFunction->sendEmail($params, $data["audio"][0]["mail"],"myaudio", "Confirmation d'inscription sur My Audio Pro", 122 );
  4438. */
  4439.         $token = new Token();
  4440.         $token->setCreationDate(new DateTime());
  4441.         $token->setToken($tokenString);
  4442.         $token->setMail($audio->getMail());
  4443.         $entityManager $this->getDoctrine()->getManager();
  4444.         $entityManager->persist($token);
  4445.         
  4446.         $entityManager->flush();     
  4447.          // create the sheet of ads
  4448.          $postales $this->getPostalCodes($centre);
  4449.          $dataSheet = [
  4450.              $centre->getId() ?? ''// id centre
  4451.              $centre->getName() ?? '',  // Nom
  4452.              $centre->getCity() ?? '',  // ville
  4453.              $centre->getLongitude() ?? ''// longitude
  4454.              $centre->getLatitude() ?? '',  // lattitude
  4455.              $centre->getZoneKm() ?? '',  // zone km
  4456.              ($centre->getIdGerant()->getLastName() ?? '') . ' ' . ($centre->getIdGerant()->getName() ?? ''),
  4457.              $centre->getAddress() ?? '',
  4458.              $centre->getPostale() ?? '',
  4459.              $postales ?? '' // in case postales is missing
  4460.          ];
  4461.          
  4462.      
  4463.          $this->googleSheetsService->appendToSheetZoneKm($dataSheet'centersByZoneKm');
  4464.                       // create the sheet of marketing
  4465.                       $entityManager $this->getDoctrine()->getManager();
  4466.                       $sheetName 'AIntegrer';
  4467.                       
  4468.                       // Get already existing postals from column D
  4469.                       $existingValues $this->googleSheetsService->getColumnValues($sheetName4); // column D
  4470.                       $existingPostales array_filter($existingValues); 
  4471.                       $existingPostales array_map('strval'$existingPostales); 
  4472.                       
  4473.                       // Use a specific centre instance instead of findAll
  4474.                       
  4475.                       if (!$centre) {
  4476.                           throw new \Exception('Centre not found.');
  4477.                       }
  4478.                       
  4479.                       $rowsToAppend = [];
  4480.                       
  4481.                       $postales $this->getPostalCodesMarket($centre);
  4482.                       $postales array_unique($postales);
  4483.                       
  4484.                       $newPostales array_diff($postales$existingPostales);
  4485.                       $newPostales array_values($newPostales); // reset keys
  4486.                       
  4487.                       if (count($newPostales) > 0) {
  4488.                           $now = (new \DateTime())->format('d/m/Y');
  4489.                           $centerPostal $centre->getPostale();
  4490.                       
  4491.                           foreach ($newPostales as $index => $postal) {
  4492.                               if ($index === 0) {
  4493.                                   $rowsToAppend[] = [false$now$centerPostal$postal];
  4494.                               } else {
  4495.                                   $rowsToAppend[] = [''''''$postal];
  4496.                               }
  4497.                           }
  4498.                       
  4499.                           $this->googleSheetsService->appendToSheetMarketing($rowsToAppend$sheetName);
  4500.                       }
  4501.                       
  4502.          
  4503.        /* $user = [
  4504.             "prenomAudioprothesiste" => $gerant->getName(),
  4505.             "urlDemo" => "https://calendar.google.com/calendar/u/0/appointments/schedules/AcZssZ0Ry72UDE9m8d2IylSycOMQVerlY0jHt1DLWFD6Pso4hg79sQ9nUAlxtZYOPH6wSubDX4vqVQWh",
  4506.         ];
  4507.         // we send parametre for the trait methid
  4508.         $params = $this->emailNotificationDemoService->prepareEmailParams($user);
  4509.         // send email notifcation
  4510.         $this->emailNotificationDemoService->sendEmail($params, $gerant->getMail(), 'Organisez votre Démo personnalisée de My Audio Pro', 143);
  4511.         */
  4512.         // set order datable patient 
  4513.         $this->orderPatient->createOrderPatient($audio);
  4514.         $plan $this->getDoctrine()->getRepository(Plan::class)
  4515.         ->findOneBy(["slug" => $data['plan']["planName"]] );
  4516. //dd($plan);
  4517.         $dataSubsc = [];
  4518.       
  4519.         $dataSubsc['created'] = $subscriptionData['created'];
  4520.         $dataSubsc['currentPeriodStart'] = $subscriptionData['current_period_start'];
  4521.         $dataSubsc['currentPeriodEnd'] = $subscriptionData['current_period_end'];
  4522.         $dataSubsc['centerId'] = $centre->getId();
  4523.         $dataSubsc['audioId'] = $audio->getId();
  4524.         $dataSubsc['id'] = $subscriptionData['subscriptionId'];
  4525.         $dataSubsc['invoiceId'] = $subscriptionData['invoiceId'];
  4526.         $dataSubsc['customer'] = $subscriptionData['customerId'];
  4527.         $dataSubsc['payment_method'] = $subscriptionData['default_payment_method'];
  4528.         $dataSubsc['amount'] = $data["price"]["finalPrice"] ?? $data["price"];
  4529.         $dataSubsc['quantity'] = $data["quantity"];
  4530.         $dataSubsc['recurring'] = ($data["price"]["recurring"] === "monthly") ? "month" 
  4531.         (($data["price"]["recurring"] === "yearly") ? "year" $data["price"]["recurring"]);
  4532.         $dataSubsc['planId'] = $plan->getId();
  4533.         $dataSubsc['status'] = "succeeded";
  4534.                  
  4535.       
  4536.         //$this->logger->info("stripe end date",["endDate" => $currentPeriodEnd->format('Y-m-d H:i:s')]);
  4537.         $subscrition->createSubscription($dataSubsc);
  4538.         //$this->logger->info("databse end date",["endDate" => $sub]);
  4539.         // generate rdvurl
  4540.         $name $centre->getName();
  4541.         $city $centre->getCity();
  4542.         $postal $centre->getPostale();
  4543.         $nameSlug strtolower(preg_replace('/[^a-zA-Z0-9]+/''-'trim($name)));
  4544.         $citySlug strtolower(preg_replace('/[^a-zA-Z0-9]+/''-'trim($city)));
  4545.         $baseClient $_ENV['BASE_client'] ?? 'https://default-client-url.com';
  4546.         $urlRdv "{$baseClient}audioprothesiste/{$citySlug}/{$postal}/{$nameSlug}/prise-de-rdvaudioprothesiste-rapide/{$centre->getId()}";
  4547.         if (!$centre->getUrlRdv() || $centre->getUrlRdv() !== $urlRdv) {
  4548.             $centre->setUrlRdv($urlRdv);
  4549.             $entityManager->persist($centre);
  4550.             $entityManager->flush();
  4551.         }
  4552.          // post categorie de contrat cda
  4553.          $quantity $data["quantity"];
  4554.          $contractCategory $entityManager->getRepository(ContractCategory::class)->find(7);
  4555.          $plan $entityManager->getRepository(Plan::class)->find($plan->getId());
  4556.          if ($contractCategory && $plan && $quantity 0) {
  4557.             
  4558.              $specificSubscription = new SpecificSubscription();
  4559.              $specificSubscription->setContractCategory($contractCategory);
  4560.              $specificSubscription->setPlan($plan);
  4561.              $specificSubscription->setQuantity($quantity);
  4562.              $specificSubscription->setCenter($centre);
  4563.              $specificSubscription->setStatus(false);
  4564.              $specificSubscription->setStripeCustomer($subscriptionData['customerId']);
  4565.              $specificSubscription->setPaymentMethod($subscriptionData['default_payment_method']);
  4566.              $specificSubscription->setPaidAmount($data["price"]["finalPrice"] ?? $data["price"]);
  4567.              $specificSubscription->setAudio($audio);
  4568.              $entityManager->persist($specificSubscription);
  4569.              $entityManager->flush();     
  4570.          }
  4571.         // call docage and create it
  4572.         $this->callAtolDocage($centre);
  4573.         // create invoice we will switch later after signature not here
  4574.         $invoiceAtol->createClient($centre$data);
  4575.  
  4576.         return $this->json([
  4577.             "audioId" => $audio->getId(),
  4578.             "centerId" => $centre->getId(),
  4579.             "name" => $centre->getName(),
  4580.             "imgUrl" => $centre->getImgUrl(),
  4581.             "isRdvDomicile" => $centre->getIsRdvDomicile(),
  4582.             "audio_id" => $centre->getIdGerant()->getId(),
  4583.             "address" => $centre->getAddress(),
  4584.             "postale" => $centre->getPostale(),
  4585.             "city" => $centre->getCity(),
  4586.             "finess" => $centre->getFiness(),
  4587.             "siret" => $centre->getSiret(),
  4588.             "website" => $centre->getWebsite(),
  4589.             "phone" => $centre->getPhone(),
  4590.             "isHandicap" => $centre->getIsHandicap(),
  4591.             //"audio" => $resultAudio->toArray(),
  4592.             "centerId" => $centre->getId(),
  4593.             "audioId" => $audio->getId(),
  4594.             "status" => 200,
  4595.         ]);
  4596.     }
  4597.   /**
  4598.      * @Route("/relance/valide/mail/token", name="relancerValidationMail", methods={"POST"})
  4599.      */
  4600.     public function relancerValidationMail(Request $requestPublicFunction $publicFunction)
  4601.     {
  4602.         $entityManager $this->getDoctrine()->getManager();
  4603.         $data json_decode($request->getContent(), true);
  4604.         $tokenString $publicFunction->generateRandomString(30);
  4605.         $params = array(
  4606.             "lien" => "{$_ENV['BASE_client']}confirmation_email/{$data['mail']}?token={$tokenString}",
  4607.             "nom" => "",
  4608.             "texte" => "Veuillez cliquer sur le bouton ci-dessous pour confirmer votre adresse mail",
  4609.             "titre" => "Confirmer mon email",
  4610.             "bouton" => "Confirmer mon Email",
  4611.         );
  4612.         $publicFunction->sendEmail($params$data['mail'], $data['mail'], "Confirmation d'inscription sur My Audio Pro"122);
  4613.         $token = new Token();
  4614.         $token->setCreationDate(new DateTime());
  4615.         $token->setToken($tokenString);
  4616.         $token->setMail($data['mail']);
  4617.         $entityManager $this->getDoctrine()->getManager();
  4618.         $entityManager->persist($token);
  4619.         $entityManager->flush();
  4620.         return new Response(json_encode([
  4621.             "message" => "Un mail viens de vous etre envoyé",
  4622.             "status" => 200,
  4623.         ]));
  4624.     }
  4625.     /**
  4626.      * @Route("/valider/mail/token", name="validerMailGerant", methods={"POST"})
  4627.      */
  4628.     public function validerMailGerant(Request $request)
  4629.     {
  4630.         // get all data including the client that matches the mail stored in the token
  4631.         $entityManager $this->getDoctrine()->getManager();
  4632.         $data json_decode($request->getContent(), true);
  4633.         if (isset($data["token"])) {
  4634.             $token $this->getDoctrine()
  4635.                 ->getRepository(Token::class)
  4636.                 ->findOneBy(['token' => $data["token"]]);
  4637.             if (!$token) {
  4638.                 return new Response(json_encode([
  4639.                     'message' => 'Erreur',
  4640.                     'path' => 'src/Controller/CentreController.php',
  4641.                 ]), 200);
  4642.             }
  4643.         } else {
  4644.             return new Response(json_encode([
  4645.                 "message" => "Erreur",
  4646.                 "status" => 401,
  4647.             ]), 200);
  4648.         }
  4649.         $audio $this->getDoctrine()
  4650.             ->getRepository(Audio::class)
  4651.             ->findOneBy(['mail' => $token->getMail()]);
  4652.         if (!$audio) {
  4653.             return new Response(json_encode([
  4654.                 'message' => 'Erreur',
  4655.                 'path' => 'src/Controller/CentreController.php',
  4656.             ]), 200);
  4657.         }
  4658.         $start_date $token->getCreationDate();
  4659.         $since_start $start_date->diff(new DateTime());
  4660.         if ($since_start->10) {
  4661.             //success
  4662.             $audio->setMailValid(1);
  4663.             $audio->getAudioCentre()[0]->getIdCentre()->setIsValid(1);
  4664.             $entityManager->remove($token);
  4665.             $entityManager->flush();
  4666.             //TODO envoyer un mail avec lien pro
  4667.             return new Response(json_encode([
  4668.                 "message" => "ok",
  4669.                 "status" => 200,
  4670.             ]));
  4671.             // if it's more than 01 minutes
  4672.         } else {
  4673.             $entityManager->remove($token);
  4674.             $entityManager->flush();
  4675.             return new Response(json_encode([
  4676.                 "message" => "nok",
  4677.                 "status" => 401,
  4678.             ]), 200);
  4679.         }
  4680.     }
  4681.     /**
  4682.      * @Route("/centre/image", name="postCentreImage", methods={"POST"})
  4683.      */
  4684.     public function postCentreImage(Request $requestFileUploader $fileUploader): Response
  4685.     {
  4686.         $image $request->files->get('image');
  4687.         $fileUploader->upload($image"images/setting/");
  4688.         return new Response(json_encode([
  4689.             "imgUrl" => $fileUploader->upload($image"images/centre/"),
  4690.             "status" => 200,
  4691.         ]));
  4692.     }
  4693.     /**
  4694.      * @Route("/centre/image/fData-newinscription", name="postCentreImageByFormDataNewInscription", methods={"POST"})
  4695.      */
  4696.     public function postCentreImageByFormDataNewInscription(Request $requestFileUploader $fileUploader): Response
  4697.     {
  4698.         $newfilename "";
  4699.         $audioFile "";
  4700.         $diplomeFile "";
  4701.         $finessfilename "";
  4702.         $audioId $request->request->get('audioId');
  4703.         $centreId $request->request->get('centreId');
  4704.         $facadeFile $request->files->get('image_facade');
  4705.         $fitnessFile $request->files->get('image_interieur');
  4706.         $profilFile $request->files->get('image_profil');
  4707.         $diplomeFile $request->files->get('image_diplome');
  4708.         $audio =  $this->getDoctrine()
  4709.             ->getRepository(Audio::class)
  4710.             ->find($audioId);
  4711.         $center =  $this->getDoctrine()
  4712.             ->getRepository(Centre::class)
  4713.             ->find($centreId);
  4714.         $entityManager $this->getDoctrine()->getManager();
  4715.         // add image galerie
  4716.         // delete the default image united 
  4717.         if ($facadeFile || $fitnessFile || $diplomeFile) {
  4718.             $oldImages $this->getDoctrine()
  4719.                 ->getRepository(CenterImage::class)
  4720.                 ->findBy(["center" => $center]);
  4721.             if ($oldImages) {
  4722.                 foreach ($oldImages as $image) {
  4723.                     $entityManager->remove($image);
  4724.                 }
  4725.                 $entityManager->flush();
  4726.             }
  4727.         }
  4728.         // Post image centre
  4729.         $facadeFile $request->files->get('image_facade');
  4730.         if ($facadeFile) {
  4731.             $fileArray = [
  4732.                 'name' => $facadeFile->getClientOriginalName(),
  4733.                 'type' => $facadeFile->getMimeType(),
  4734.                 'tmp_name' => $facadeFile->getPathname(),
  4735.                 'error' => $facadeFile->getError(),
  4736.                 'size' => $facadeFile->getSize(),
  4737.             ];
  4738.             $newfilename $fileUploader->uploadFormData($fileArray"images/centre/""images/centres/");
  4739.             $center->setImgUrl($newfilename);
  4740.             $entityManager->persist($center);
  4741.             $image = new CenterImage();
  4742.             $image->setCenter($center);
  4743.             $image->setType('image');
  4744.             if ($newfilename) {
  4745.                 $image->setUrl($newfilename);
  4746.                 $entityManager->persist($image);
  4747.             }
  4748.             $entityManager->flush();
  4749.             $publicImagePath $this->getParameter('kernel.project_dir') . '/public/assets/images/centre/' $newfilename;
  4750.             $assetsImagePath $this->getParameter('kernel.project_dir') . '/assets/images/centre/' $newfilename;
  4751.             if (file_exists($assetsImagePath)) {
  4752.                 copy($assetsImagePath$publicImagePath);
  4753.             }
  4754.             $publicImagePathCtrs $this->getParameter('kernel.project_dir') . '/public/assets/images/centres/' $newfilename;
  4755.             $assetsImagePathCtrs $this->getParameter('kernel.project_dir') . '/assets/images/centres/' $newfilename;
  4756.             if (file_exists($assetsImagePathCtrs)) {
  4757.                 copy($assetsImagePathCtrs$publicImagePathCtrs);
  4758.             }
  4759.         }
  4760.         // Post FINESS centre
  4761.         $fitnessFile $request->files->get('image_interieur');
  4762.         if ($fitnessFile) {
  4763.             $fileArray = [
  4764.                 'name' => $fitnessFile->getClientOriginalName(),
  4765.                 'type' => $fitnessFile->getMimeType(),
  4766.                 'tmp_name' => $fitnessFile->getPathname(),
  4767.                 'error' => $fitnessFile->getError(),
  4768.                 'size' => $fitnessFile->getSize(),
  4769.             ];
  4770.             $finessfilename $fileUploader->uploadFormData($fileArray"images/centres/");
  4771.             $image = new CenterImage();
  4772.             $image->setCenter($center);
  4773.             $image->setType('image');
  4774.             if ($finessfilename) {
  4775.                 $image->setUrl($finessfilename);
  4776.                 $entityManager->persist($image);
  4777.             }
  4778.             $entityManager->flush();
  4779.             $publicImagePath $this->getParameter('kernel.project_dir') . '/public/assets/images/centres/' $finessfilename;
  4780.             $assetsImagePath $this->getParameter('kernel.project_dir') . '/assets/images/centres/' $finessfilename;
  4781.             if (file_exists($assetsImagePath)) {
  4782.                 copy($assetsImagePath$publicImagePath);
  4783.             }
  4784.         }
  4785.         // Post audio profile
  4786.         $profilFile $request->files->get('image_profil');
  4787.         if ($profilFile) {
  4788.             $fileArray = [
  4789.                 'name' => $profilFile->getClientOriginalName(),
  4790.                 'type' => $profilFile->getMimeType(),
  4791.                 'tmp_name' => $profilFile->getPathname(),
  4792.                 'error' => $profilFile->getError(),
  4793.                 'size' => $profilFile->getSize(),
  4794.             ];
  4795.             $audioFilename $fileUploader->uploadFormData($fileArray"images/audio/");
  4796.             $audio->setImgUrl($audioFilename);
  4797.             $entityManager->persist($audio);
  4798.             $publicImagePath $this->getParameter('kernel.project_dir') . '/public/assets/images/audio/' $audioFilename;
  4799.             $assetsImagePath $this->getParameter('kernel.project_dir') . '/assets/images/audio/' $audioFilename;
  4800.             if (file_exists($assetsImagePath)) {
  4801.                 copy($assetsImagePath$publicImagePath);
  4802.             }
  4803.         }
  4804.         // Post audio diplome
  4805.         $diplomeFile $request->files->get('image_diplome');
  4806.         if ($diplomeFile) {
  4807.             $fileArray = [
  4808.                 'name' => $diplomeFile->getClientOriginalName(),
  4809.                 'type' => $diplomeFile->getMimeType(),
  4810.                 'tmp_name' => $diplomeFile->getPathname(),
  4811.                 'error' => $diplomeFile->getError(),
  4812.                 'size' => $diplomeFile->getSize(),
  4813.             ];
  4814.             $d $fileUploader->uploadFormData($fileArray"document/audio/""images/centres/");
  4815.             $audioDiplome = new AudioDiplome();
  4816.             $image = new CenterImage();
  4817.             $image->setCenter($center);
  4818.             $image->setType('image');
  4819.             $newfilename $d;
  4820.             if ($newfilename) {
  4821.                 $image->setUrl($newfilename);
  4822.                 $entityManager->persist($image);
  4823.             }
  4824.             $entityManager->flush();
  4825.         }
  4826.         $entityManager->flush();
  4827.         return new Response(json_encode([
  4828.             "message" => "updated succesfully"
  4829.         ]));
  4830.     }
  4831.     /**
  4832.      * @Route("/centre/image/fData", name="postCentreImageByFormDataInscription", methods={"POST"})
  4833.      */
  4834.     public function postCentreImageByFormDataInscription(Request $requestFileUploader $fileUploader): Response
  4835.     {
  4836.         $newfilename "";
  4837.         $audioFile "";
  4838.         $diplomeFile "";
  4839.         $finessfilename "";
  4840.         $entityManager $this->getDoctrine()->getManager();
  4841.         //post image centre
  4842.         if (isset($_FILES["picCentre"]) && $_FILES["picCentre"]["size"] != 0) {
  4843.             $newfilename $fileUploader->uploadFormData($_FILES["picCentre"], "images/setting/""images/centre/");
  4844.             $publicImagePath $this->getParameter('kernel.project_dir') . '/public/assets/images/centre/' $newfilename;
  4845.             $assetsImagePath $this->getParameter('kernel.project_dir') . '/assets/images/centre/' $newfilename;
  4846.             if (file_exists($assetsImagePath)) {
  4847.                 copy($assetsImagePath$publicImagePath);
  4848.             }
  4849.         } else {
  4850.             $publicImagePath $this->getParameter('kernel.project_dir') . '/public/assets/images/centre/imgOreille.png';
  4851.             $assetsImagePath $this->getParameter('kernel.project_dir') . '/assets/images/centre/imgOreille.png';
  4852.             if (file_exists($assetsImagePath)) {
  4853.                 copy($assetsImagePath$publicImagePath);
  4854.             }
  4855.             $newfilename 'imgOreille.png';
  4856.         }
  4857.         //post FINESS centre
  4858.         if (isset($_FILES["fileFiness"]) && $_FILES["fileFiness"]["size"] != 0) {
  4859.             $finessfilename $fileUploader->uploadFormData($_FILES["fileFiness"], "document/centre/finess");
  4860.         }
  4861.         $audioFile = array();
  4862.         $diplomeFile = array();
  4863.         //post image audio
  4864.         if (isset($_POST['nombreAudio'])) {
  4865.             for ($i 1$i <= $_POST['nombreAudio']; $i++) {
  4866.                 if (isset($_FILES["picAudio" $i]) && $_FILES["picAudio" $i]["size"] != 0) {
  4867.                     $audioFilename $fileUploader->uploadFormData($_FILES["picAudio" $i], "images/audio/");
  4868.                     array_push($audioFile$audioFilename);
  4869.                 }
  4870.                 // post audio diplome
  4871.                 $dip = array();
  4872.                 for ($j 1$j <= 5$j++) {
  4873.                     if (isset($_FILES["fileDilpomeA" $i $j]) && $_FILES["fileDilpomeA" $i $j]["size"] != 0) {
  4874.                         $d $fileUploader->uploadFormData($_FILES["fileDilpomeA" $i $j], "document/audio/");
  4875.                         array_push($dip$d);
  4876.                     }
  4877.                 }
  4878.                 array_push($diplomeFile$dip);
  4879.             }
  4880.         }
  4881.         $entityManager->flush();
  4882.         return new Response(json_encode([
  4883.             "fileName" => $newfilename,
  4884.             "audioFile" => $audioFile,
  4885.             "diplomeFile" => $diplomeFile,
  4886.             "finessfilename" => $finessfilename
  4887.         ]));
  4888.     }
  4889.     /**
  4890.      * @Route("/centre/fData/{id}", name="postCentreImageByFormData", methods={"POST"})
  4891.      */
  4892.     public function postCentreImageByFormData(Centre $centreRequest $requestFileUploader $fileUploader): Response
  4893.     {
  4894.         if (!$request->query->get('token')) {
  4895.             return new Response(json_encode([
  4896.                 "message" => "Pas de token n'a été spécifié",
  4897.                 "status" => 401,
  4898.             ]), 401);
  4899.         }
  4900.         $entityManager $this->getDoctrine()->getManager();
  4901.         /** @var Token */
  4902.         $token $this->getDoctrine()
  4903.             ->getRepository(Token::class)
  4904.             ->findOneBy(['token' => $request->query->get('token'), 'id_audio' => $centre->getIdGerant()]);
  4905.         if (!$token) {
  4906.             return new Response(json_encode([
  4907.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4908.                 "status" => 404,
  4909.             ]), 404);
  4910.         }
  4911.         // get token age
  4912.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4913.         // if the token if older than 7 days
  4914.         if ($dateDiff->7) {
  4915.             $entityManager $this->getDoctrine()->getManager();
  4916.             $entityManager->remove($token);
  4917.             $entityManager->flush();
  4918.             return $this->json([
  4919.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4920.                 'path' => 'src/Controller/AudioController.php',
  4921.                 "status" => 401,
  4922.             ], 401);
  4923.         }
  4924.         if (isset($_FILES["pic"]) && $_FILES["pic"]["size"] != 0) {
  4925.             $newfilename $fileUploader->uploadFormData($_FILES["pic"], "images/centre/");
  4926.             $centre->setImgUrl($newfilename);
  4927.         }
  4928.         $entityManager->flush();
  4929.         return $this->json([
  4930.             "imgUrl" => $centre->getImgUrl(),
  4931.         ]);
  4932.     }
  4933.     /**
  4934.      * @Route("/centre/{id}/access", name="editAccessByCentreByID", methods={"PUT"})
  4935.      */
  4936.     public function editAccessCentreByCentreID(Centre $centreRequest $request)
  4937.     {
  4938.         $entityManager $this->getDoctrine()->getManager();
  4939.         $data json_decode($request->getContent(), true);
  4940.         if (!isset($data['token']))
  4941.             return new Response(json_encode([
  4942.                 "message" => "Pas de token n'a été spécifié",
  4943.                 "status" => 401,
  4944.             ]), 401);
  4945.         $entityManager $this->getDoctrine()->getManager();
  4946.         /** @var Token */
  4947.         $token $this->getDoctrine()
  4948.             ->getRepository(Token::class)
  4949.             ->findOneBy(['token' => $data['token'], 'id_audio' => $centre->getIdGerant()]);
  4950.         if (!$token)
  4951.             return new Response(json_encode([
  4952.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4953.                 "status" => 404,
  4954.             ]), 404);
  4955.         // get token age
  4956.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4957.         // if the token if older than 7 days
  4958.         if ($dateDiff->7) {
  4959.             $entityManager->remove($token);
  4960.             $entityManager->flush();
  4961.             return $this->json([
  4962.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4963.                 'path' => 'src/Controller/ClientController.php',
  4964.                 "status" => 401
  4965.             ], 401);
  4966.         }
  4967.         $centre $this->getDoctrine()
  4968.             ->getRepository(Centre::class)
  4969.             ->findOneBy(['id' => $centre->getId()]);
  4970.         if (!$centre) {
  4971.             return new Response(json_encode([
  4972.                 'message' => 'Error, no Centre found at this id',
  4973.                 'path' => 'src/Controller/CentreController.php',
  4974.             ]));
  4975.         } else {
  4976.             $accessCentre $this->getDoctrine()
  4977.                 ->getRepository(AccessCentre::class)
  4978.                 ->findOneBy(['id_centre' => $centre->getId()]);
  4979.             if (isset($data["Métro"]))
  4980.                 $accessCentre->setMetro($data["Métro"]);
  4981.             if (isset($data["Bus"]))
  4982.                 $accessCentre->setBus($data["Bus"]);
  4983.             if (isset($data["Tram"]))
  4984.                 $accessCentre->setTram($data["Tram"]);
  4985.             if (isset($data["RER"]))
  4986.                 $accessCentre->setRer($data["RER"]);
  4987.             if (isset($data["Parking Public"]))
  4988.                 $accessCentre->setParkingPublic($data["Parking Public"]);
  4989.             if (isset($data["Parking Privé"]))
  4990.                 $accessCentre->setParkingPrivate($data["Parking Privé"]);
  4991.             if (isset($data["Autre"]))
  4992.                 $accessCentre->setOther($data["Autre"]);
  4993.             $entityManager->persist($accessCentre);
  4994.             $entityManager->flush();
  4995.             return new Response(json_encode([
  4996.                 "idCentre" => $centre->getId(),
  4997.                 "metro" => $accessCentre->getMetro(),
  4998.                 "tram" => $accessCentre->getTram(),
  4999.                 "bus" => $accessCentre->getBus(),
  5000.                 "rer" => $accessCentre->getRer(),
  5001.                 "Parking Public" => $accessCentre->getParkingPublic(),
  5002.                 "Parking Privé" => $accessCentre->getParkingPrivate(),
  5003.                 "autre" => $accessCentre->getOther(),
  5004.             ]));
  5005.         }
  5006.     }
  5007.     /**
  5008.      * @Route("/centre/{id}", name="editCentreByID", methods={"PUT"})
  5009.      */
  5010.     public function editCentreByID(Centre $centreRequest $request)
  5011.     {
  5012.         $entityManager $this->getDoctrine()->getManager();
  5013.         $data json_decode($request->getContent(), true);
  5014.         if (!isset($data['token']))
  5015.             return new Response(json_encode([
  5016.                 "message" => "Pas de token n'a été spécifié",
  5017.                 "status" => 401,
  5018.             ]), 401);
  5019.         $entityManager $this->getDoctrine()->getManager();
  5020.         /** @var Token */
  5021.         $token $this->getDoctrine()
  5022.             ->getRepository(Token::class)
  5023.             ->findOneBy(['token' => $data['token'], 'id_audio' => $centre->getIdGerant()]);
  5024.         if (!$token)
  5025.             return new Response(json_encode([
  5026.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5027.                 "status" => 404,
  5028.             ]), 404);
  5029.         // get token age
  5030.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5031.         // if the token if older than 7 days
  5032.         if ($dateDiff->7) {
  5033.             $entityManager->remove($token);
  5034.             $entityManager->flush();
  5035.             return $this->json([
  5036.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5037.                 'path' => 'src/Controller/ClientController.php',
  5038.                 "status" => 401
  5039.             ], 401);
  5040.         }
  5041.         if (isset($data["audio_id"])) {
  5042.             $audio $this->getDoctrine()
  5043.                 ->getRepository(Audio::class)
  5044.                 ->findOneBy(['id' => $data["audio_id"]]);
  5045.             if (!$audio)
  5046.                 return new Response(json_encode([
  5047.                     'message' => 'Error, no Audio found at this id',
  5048.                     'path' => 'src/Controller/AudioController.php',
  5049.                 ]));
  5050.             $centre->setIdGerant($audio);
  5051.         }
  5052.         if (isset($data["name"]))
  5053.             $centre->setName($data["name"]);
  5054.         if (isset($data["imgUrl"]))
  5055.             $centre->setImgUrl($data["imgUrl"]);
  5056.         if (isset($data["isRdvDomicile"]))
  5057.             $centre->setIsRdvDomicile($data["isRdvDomicile"]);
  5058.         if (isset($data["address"]))
  5059.             $centre->setAddress($data["address"]);
  5060.         if (isset($data["numero"]))
  5061.             $centre->setNumero($data["numero"]);
  5062.         if (isset($data["voie"]))
  5063.             $centre->setVoie($data["voie"]);
  5064.         if (isset($data["rue"]))
  5065.             $centre->setRue($data["rue"]);
  5066.         if (isset($data["description"]))
  5067.             $centre->setDescription($data["description"]);
  5068.         if (isset($data["longitude"]))
  5069.             $centre->setLongitude($data["longitude"]);
  5070.         if (isset($data["latitude"]))
  5071.             $centre->setLatitude($data["latitude"]);
  5072.         if (isset($data["postale"]))
  5073.             $centre->setPostale($data["postale"]);
  5074.         if (isset($data["city"]))
  5075.             $centre->setCity($data["city"]);
  5076.         if (isset($data["finess"]))
  5077.             $centre->setFiness($data["finess"]);
  5078.         if (isset($data["siret"]))
  5079.             $centre->setSiret($data["siret"]);
  5080.         if (isset($data["website"]))
  5081.             $centre->setWebsite($data["website"]);
  5082.         if (isset($data["phone"])) {
  5083.             $centrePhoneTest $this->getDoctrine()
  5084.                 ->getRepository(Centre::class)
  5085.                 ->findOneBy(['phone' => $data["phone"]]);
  5086.             if ($centrePhoneTest)
  5087.                 return $this->json([
  5088.                     'message' => 'Ce numéro de téléphone est déjà attribué.',
  5089.                     'path' => 'src/Controller/CentreController.php',
  5090.                     "status" => 401
  5091.                 ], 401);
  5092.             $centre->setPhone($data["phone"]);
  5093.         }
  5094.         if (isset($data["isHandicap"]))
  5095.             $centre->setIsHandicap($data["isHandicap"]);
  5096.         $entityManager->flush();
  5097.         return new Response(json_encode([
  5098.             "id" => $centre->getId(),
  5099.             "audio_id" => $centre->getIdGerant()->getId(),
  5100.             "name" => $centre->getName(),
  5101.             "imgUrl" => $centre->getImgUrl(),
  5102.             "isRdvDomicile" => $centre->getIsRdvDomicile(),
  5103.             "address" => $centre->getAddress(),
  5104.             "numero" => $centre->getNumero(),
  5105.             "voie" => $centre->getVoie(),
  5106.             "rue" => $centre->getRue(),
  5107.             "postale" => $centre->getPostale(),
  5108.             "city" => $centre->getCity(),
  5109.             "finess" => $centre->getFiness(),
  5110.             "siret" => $centre->getSiret(),
  5111.             "website" => $centre->getWebsite(),
  5112.             "phone" => $centre->getPhone(),
  5113.             "isHandicap" => $centre->getIsHandicap(),
  5114.         ]));
  5115.     }
  5116.     public function createPermanantMotif(int $durationString $colorAudio $audioint $id_motifint $type): AudioMotif
  5117.     {
  5118.         $audioMotif = new AudioMotif();
  5119.         $audioMotif->setDuration($duration);
  5120.         $audioMotif->setColor($color);
  5121.         $audioMotif->setIsRDVonline(true);
  5122.         $audioMotif->setIsDeleted(false);
  5123.         $audioMotif->setType($type);
  5124.         // change when that feature will be implemented.
  5125.         $audioMotif->setIdAudio($audio);
  5126.         $motif $this->getDoctrine()
  5127.             ->getRepository(Motif::class)
  5128.             ->findOneBy(['id' => $id_motif]);
  5129.         $audioMotif->setIdMotif($motif);
  5130.         return $audioMotif;
  5131.     }
  5132.     /**
  5133.      * @Route("centre/{id}/dockage/", name="callDocages", methods={"GET"})
  5134.      */
  5135.     public function callDocage(Centre $centre)
  5136.     {
  5137.         $entityManager $this->getDoctrine()->getManager();
  5138.         /** @var Token */
  5139.         $centre $this->getDoctrine()
  5140.             ->getRepository(Centre::class)
  5141.             ->findOneBy(['id' => $centre->getId()]);
  5142.         if ($centre->getIdDockage() != null) {
  5143.             $transaction $this->lancementSignatureDocument($centre$centre->getIdDockage());
  5144.         } else {
  5145.             $idDocage $this->createContactDockage($centre);
  5146.             $transaction $this->lancementSignatureDocument($centre$idDocage);
  5147.         }
  5148.         return new Response(json_encode([
  5149.             "response" => $transaction,
  5150.             "transactionId" => $centre->getTransactionId(),
  5151.             "documentId" => $centre->getDocumentId(),
  5152.             "isSign" => $centre->getIsSign(),
  5153.             "gerant" => $centre->getIdGerant()->getMail()
  5154.         ]));
  5155.     }
  5156.     /**
  5157.      * @Route("centre/{id}/dockage-ATOL/", name="callAtolDocages", methods={"GET"})
  5158.      */
  5159.     public function callAtolDocage(Centre $centre)
  5160.     {
  5161.         $entityManager $this->getDoctrine()->getManager();
  5162.         /** @var Token */
  5163.         $centre $this->getDoctrine()
  5164.             ->getRepository(Centre::class)
  5165.             ->findOneBy(['id' => $centre->getId()]);
  5166.         
  5167.         if($centre->getIdDockage() != null)
  5168.         {
  5169.             $transaction $this->lancementSignatureAtolDocument($centre$centre->getIdDockage());
  5170.            
  5171.         } else {
  5172.             $idDocage $this->createContactAtolDockage($centre);
  5173.             $transaction $this->lancementSignatureAtolDocument($centre$idDocage);
  5174.         }
  5175.     
  5176.         
  5177.         return new Response(json_encode([
  5178.             "response" => $transaction,
  5179.             "transactionId" => $centre->getTransactionId(),
  5180.             "documentId" => $centre->getDocumentId(),
  5181.             "isSign" => $centre->getIsSign(),
  5182.             "gerant" => $centre->getIdGerant()->getMail()
  5183.         ]));
  5184.     }
  5185.     public function createContactDockage($centre){
  5186.             $entityManager $this->getDoctrine()->getManager();
  5187.         $emailGerant $centre->getIdGerant()->getMail();
  5188.         $firstName $centre->getIdGerant()->getName();
  5189.         $lastName $centre->getIdGerant()->getLastName();
  5190.         $address $centre->getAddress();
  5191.         $phone $centre->getIdGerant()->getPhone();
  5192.         $city $centre->getCity();
  5193.         $imgUrl $centre->getImgUrl();
  5194.         $centreName $centre->getName();
  5195.         $postal $centre->getPostale();
  5196.         $codeAdherant "";
  5197.         $civilite $centre->getIdGerant()->getCivilite();
  5198.         if ($civilite == "Monsieur") {
  5199.             $genre 1;
  5200.         } elseif ($civilite "Madame") {
  5201.             $genre 2;
  5202.         } else {
  5203.             $genre 3;
  5204.         }
  5205.         $curl curl_init();
  5206.         curl_setopt_array($curl, array(
  5207.             CURLOPT_URL => 'https://api.docage.com/Contacts',
  5208.             CURLOPT_RETURNTRANSFER => true,
  5209.             CURLOPT_ENCODING => '',
  5210.             CURLOPT_MAXREDIRS => 10,
  5211.             CURLOPT_TIMEOUT => 0,
  5212.             CURLOPT_FOLLOWLOCATION => true,
  5213.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  5214.             CURLOPT_CUSTOMREQUEST => 'POST',
  5215.             CURLOPT_USERPWD => 'contact@myaudio.fr' ":" 'f32c08a2-7f91-4aa4-a88d-1acc5bdd97f3',
  5216.             CURLOPT_POSTFIELDS => '{
  5217.                 "Email": "' $emailGerant '",
  5218.                 "FirstName": "' $firstName '",
  5219.                 "LastName": "' $lastName '",
  5220.                 "Address1": "' $address '",
  5221.                 "Address2": "' $codeAdherant '",
  5222.                 "City": "' $city '",
  5223.                 "State": "",
  5224.                 "ZipCode": "' $postal '",
  5225.                 "Country": "France",
  5226.                 "Notes": "",
  5227.                 "Phone": "' $phone '",
  5228.                 "Mobile": "",
  5229.                 "Company": "' $centreName '",
  5230.                 "Gender": "' $genre '",
  5231.                 "Civility": "",
  5232.                 "ProfilePictureSmall": "' $imgUrl '",
  5233.                 "ProfilePictureMedium": "JVBERi0xLjQNCiXi48 [...] VPRgo=",
  5234.                 "ProfilePictureLarge": "JVBERi0xLjQNCiXi48 [...] VPRgo="
  5235.             }',
  5236.             CURLOPT_HTTPHEADER => array(
  5237.                 'Content-Type: application/json'
  5238.             ),
  5239.         ));
  5240.         $response1 curl_exec($curl);
  5241.         curl_close($curl);
  5242.         $idDocage json_decode($response1);
  5243.         $centre->setIdDockage($idDocage);
  5244.         $entityManager->flush();
  5245.         return $idDocage;
  5246.     }
  5247.     public function createContactAtolDockage($centre){
  5248.             $entityManager $this->getDoctrine()->getManager();
  5249.         $emailGerant $centre->getIdGerant()->getMail();
  5250.         $firstName $centre->getIdGerant()->getName();
  5251.         $lastName $centre->getIdGerant()->getLastName();
  5252.         $address $centre->getAddress();
  5253.         $phone $centre->getIdGerant()->getPhone();
  5254.         $city $centre->getCity();
  5255.         $imgUrl $centre->getImgUrl();
  5256.         $centreName $centre->getName();
  5257.         $postal $centre->getPostale();
  5258.         $codeAdherant $centre->getAtoLauditionPartner()->getCodeMag();
  5259.         $civilite $centre->getIdGerant()->getCivilite();
  5260.         if ($civilite == "Monsieur") {
  5261.             $genre 1;
  5262.         } elseif ($civilite "Madame") {
  5263.             $genre 2;
  5264.         } else {
  5265.             $genre 3;
  5266.         }
  5267.         $curl curl_init();
  5268.         curl_setopt_array($curl, array(
  5269.             CURLOPT_URL => 'https://api.docage.com/Contacts',
  5270.             CURLOPT_RETURNTRANSFER => true,
  5271.             CURLOPT_ENCODING => '',
  5272.             CURLOPT_MAXREDIRS => 10,
  5273.             CURLOPT_TIMEOUT => 0,
  5274.             CURLOPT_FOLLOWLOCATION => true,
  5275.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  5276.             CURLOPT_CUSTOMREQUEST => 'POST',
  5277.             CURLOPT_USERPWD => 'contact@myaudio.fr' ":" 'f32c08a2-7f91-4aa4-a88d-1acc5bdd97f3',
  5278.             CURLOPT_POSTFIELDS => '{
  5279.                 "Email": "' $emailGerant '",
  5280.                 "FirstName": "' $firstName '",
  5281.                 "LastName": "' $lastName '",
  5282.                 "Address1": "' $address '",
  5283.                 "Address2": "' $codeAdherant '",
  5284.                 "City": "' $city '",
  5285.                 "State": "",
  5286.                 "ZipCode": "' $postal '",
  5287.                 "Country": "France",
  5288.                 "Notes": "",
  5289.                 "Phone": "' $phone '",
  5290.                 "Mobile": "",
  5291.                 "Company": "' $centreName '",
  5292.                 "Gender": "' $genre '",
  5293.                 "Civility": "",
  5294.                 "ProfilePictureSmall": "' $imgUrl '",
  5295.                 "ProfilePictureMedium": "JVBERi0xLjQNCiXi48 [...] VPRgo=",
  5296.                 "ProfilePictureLarge": "JVBERi0xLjQNCiXi48 [...] VPRgo="
  5297.             }',
  5298.             CURLOPT_HTTPHEADER => array(
  5299.                 'Content-Type: application/json'
  5300.             ),
  5301.         ));
  5302.         $response1 curl_exec($curl);
  5303.         curl_close($curl);
  5304.         $idDocage json_decode($response1);
  5305.         $centre->setIdDockage($idDocage);
  5306.         $entityManager->flush();
  5307.         return $idDocage;
  5308.     }
  5309.     public function lancementSignatureDocument($centre$idDockage)
  5310.     {
  5311.         $entityManager $this->getDoctrine()->getManager();
  5312.         // $idDockage = $centre->getIdDockage();
  5313.         $curl curl_init();
  5314.         curl_setopt_array($curl, array(
  5315.             CURLOPT_URL => 'https://api.docage.com/Transactions/CreateFullTransaction',
  5316.             CURLOPT_RETURNTRANSFER => true,
  5317.             CURLOPT_ENCODING => '',
  5318.             CURLOPT_MAXREDIRS => 10,
  5319.             CURLOPT_TIMEOUT => 0,
  5320.             CURLOPT_FOLLOWLOCATION => true,
  5321.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  5322.             CURLOPT_CUSTOMREQUEST => 'POST',
  5323.             CURLOPT_USERPWD => 'contact@myaudio.fr' ":" 'f32c08a2-7f91-4aa4-a88d-1acc5bdd97f3',
  5324.             CURLOPT_POSTFIELDS => array('TemplateId' => 'd6fa147a-2bda-437f-8e1f-ce470b59aa06''Client' => $idDockage),
  5325.         ));
  5326.         $response1 curl_exec($curl);
  5327.         $transaction json_decode($response1);
  5328.         $centre->setDocumentId($transaction->TransactionFiles[0]->Id);
  5329.         $centre->setTransactionId($transaction->TransactionFiles[0]->TransactionId);
  5330.         $centre->setIsSign(0);
  5331.         $entityManager->flush();
  5332.         curl_close($curl);
  5333.         return json_decode($response1);
  5334.     }
  5335.     public function lancementSignatureAtolDocument($centre$idDockage)
  5336.     {
  5337.         $entityManager $this->getDoctrine()->getManager();
  5338.        // $idDockage = $centre->getIdDockage();
  5339.         $curl curl_init();
  5340.         curl_setopt_array($curl, array(
  5341.         CURLOPT_URL => 'https://api.docage.com/Transactions/CreateFullTransaction',
  5342.         CURLOPT_RETURNTRANSFER => true,
  5343.         CURLOPT_ENCODING => '',
  5344.         CURLOPT_MAXREDIRS => 10,
  5345.         CURLOPT_TIMEOUT => 0,
  5346.         CURLOPT_FOLLOWLOCATION => true,
  5347.         CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  5348.         CURLOPT_CUSTOMREQUEST => 'POST',
  5349.         CURLOPT_USERPWD => 'contact@myaudio.fr' ":" 'f32c08a2-7f91-4aa4-a88d-1acc5bdd97f3',
  5350.         CURLOPT_POSTFIELDS => array('TemplateId' => 'aac5b1ca-fa3d-438d-9e1d-e45d7032281f''Client' => $idDockage),
  5351.         ));
  5352.         $response1 curl_exec($curl);
  5353.         $transaction json_decode($response1);
  5354.         $centre->setDocumentId($transaction->TransactionFiles[0]->Id);
  5355.         $centre->setTransactionId($transaction->TransactionFiles[0]->TransactionId);
  5356.         $centre->setIsSign(0);
  5357.         $entityManager->flush();
  5358.         curl_close($curl);
  5359.         return json_decode($response1);
  5360.     }
  5361.     
  5362.     /**
  5363.      * @Route("centre/{id}/relance/dockage", name="relanceDocage", methods={"GET"})
  5364.      */
  5365.     public function relanceDocage(Centre $centre)
  5366.     {
  5367.         $output null;
  5368.         $retval null;
  5369.         //exec("curl --location --request GET 'https://api.docage.com/SendReminders/".$centre->getTransactionId()."'", $output, $retval);
  5370.         $curl curl_init();
  5371.         curl_setopt_array($curl, array(
  5372.             CURLOPT_URL => 'https://api.docage.com/SendReminders/' $centre->getTransactionId(),
  5373.             CURLOPT_RETURNTRANSFER => true,
  5374.             CURLOPT_ENCODING => '',
  5375.             CURLOPT_MAXREDIRS => 10,
  5376.             CURLOPT_TIMEOUT => 0,
  5377.             CURLOPT_FOLLOWLOCATION => true,
  5378.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  5379.             CURLOPT_CUSTOMREQUEST => 'GET',
  5380.             CURLOPT_USERPWD => 'contact@myaudio.fr' ":" 'f32c08a2-7f91-4aa4-a88d-1acc5bdd97f3',
  5381.         ));
  5382.         $response1 curl_exec($curl);
  5383.         curl_close($curl);
  5384.         return new Response(json_encode([
  5385.             "response" => $response1,
  5386.             "transactionId" => $centre->getTransactionId(),
  5387.             "documentId" => $centre->getDocumentId(),
  5388.             "isSign" => $centre->getIsSign(),
  5389.         ]));
  5390.     }
  5391.     /**
  5392.      * @Route("centre/{id}/get/document", name="getDocumentDocage", methods={"GET"})
  5393.      */
  5394.     public function getDocumentDocage(Centre $centre)
  5395.     {
  5396.         $output null;
  5397.         $retval null;
  5398.         $curl curl_init();
  5399.         curl_setopt_array($curl, array(
  5400.             CURLOPT_URL => 'https://api.docage.com/TransactionFiles/Download/' $centre->getDocumentId(),
  5401.             CURLOPT_RETURNTRANSFER => true,
  5402.             CURLOPT_ENCODING => '',
  5403.             CURLOPT_MAXREDIRS => 10,
  5404.             CURLOPT_TIMEOUT => 0,
  5405.             CURLOPT_FOLLOWLOCATION => true,
  5406.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  5407.             CURLOPT_CUSTOMREQUEST => 'GET',
  5408.             CURLOPT_USERPWD => 'contact@myaudio.fr' ":" 'f32c08a2-7f91-4aa4-a88d-1acc5bdd97f3',
  5409.         ));
  5410.         $response1 curl_exec($curl);
  5411.         curl_close($curl);
  5412.         $r str_replace('"'''$response1);
  5413.         $pdf_decoded base64_decode($r);
  5414.         //Write data back to pdf file
  5415.         $projectDir $this->getParameter('kernel.project_dir');
  5416.         //$pdfFilePath = $projectDir . '/assets/partner/facture' . $invoice->getToken() . '.pdf';
  5417.         $pdf fopen($projectDir '/assets/pdf/cga_' $centre->getId() . '.pdf''w');
  5418.         fwrite($pdf$pdf_decoded);
  5419.         //close output file
  5420.         fclose($pdf);
  5421.         return new Response($response1);
  5422.     }
  5423.     /**
  5424.      * @Route("centre/{id}/checkisSign", name="checkValid", methods={"GET"})
  5425.      */
  5426.     public function checkisSign(Centre $centre)
  5427.     {
  5428.         $entityManager $this->getDoctrine()->getManager();
  5429.         $curl curl_init();
  5430.         curl_setopt_array($curl, array(
  5431.             CURLOPT_URL => 'https://api.docage.com/Transactions/Status/' $centre->getTransactionId(),
  5432.             CURLOPT_RETURNTRANSFER => true,
  5433.             CURLOPT_ENCODING => '',
  5434.             CURLOPT_MAXREDIRS => 10,
  5435.             CURLOPT_TIMEOUT => 0,
  5436.             CURLOPT_FOLLOWLOCATION => true,
  5437.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  5438.             CURLOPT_CUSTOMREQUEST => 'GET',
  5439.             CURLOPT_USERPWD => 'contact@myaudio.fr' ":" 'f32c08a2-7f91-4aa4-a88d-1acc5bdd97f3',
  5440.         ));
  5441.         $response1 curl_exec($curl);
  5442.         curl_close($curl);
  5443.         if ($response1 == "Done") {
  5444.             $centre->setIsSign(1);
  5445.             $entityManager->flush();
  5446.         }
  5447.         return new Response($centre->getIsSign());
  5448.     }
  5449.     /**
  5450.      * @Route("/mandat/create", name="mandatCreate", methods={"GET"})
  5451.      */
  5452.     public function sendToCreateMandat(Request $request)
  5453.     {
  5454.         //live : live_jk-8FCTbZ0ydYSvXNeT4P8MCGO__VM9Vb2c1-teG
  5455.         $token $request->query->get('token');
  5456.         $centreId $request->query->get('centre');
  5457.         $access_token "{$_ENV['goCardless_api']}";
  5458.         $client = new \GoCardlessPro\Client([
  5459.             'access_token' => $access_token,
  5460.             'environment'  => \GoCardlessPro\Environment::LIVE,
  5461.         ]);
  5462.         $centre $this->getDoctrine()
  5463.             ->getRepository(Centre::class)
  5464.             ->findOneBy(['id' => $centreId]);
  5465.         $gerant $centre->getIdGerant();
  5466.         $redirectFlow $client->redirectFlows()->create([
  5467.             "params" => [
  5468.                 // This will be shown on the payment pages
  5469.                 "description" => "Abonnement My Audio",
  5470.                 // Not the access token
  5471.                 "session_token" => $token,
  5472.                 "success_redirect_url" => "{$_ENV['BASE_logiciel']}mandat/loading",
  5473.                 // Optionally, prefill customer details on the payment page
  5474.                 "prefilled_customer" => [
  5475.                     "given_name" => $gerant->getName(),
  5476.                     "family_name" => $gerant->getLastname(),
  5477.                     "email" => $gerant->getMail(),
  5478.                     "address_line1" => $centre->getAddress(),
  5479.                     "city" => $centre->getCity(),
  5480.                     "postal_code" => strval($centre->getPostale()),
  5481.                 ],
  5482.             ]
  5483.         ]);
  5484.         return $this->json([
  5485.             'idflow' => $redirectFlow->id,
  5486.             'url' => $redirectFlow->redirect_url,
  5487.             'redirect' => $redirectFlow
  5488.         ]);
  5489.     }
  5490.     /**
  5491.      * @Route("/mandat/validate", name="mandatValidate", methods={"GET"})
  5492.      */
  5493.     public function validateMandat(Request $request)
  5494.     {
  5495.         $entityManager $this->getDoctrine()->getManager();
  5496.         $token $request->query->get('token');
  5497.         $url $request->query->get('url');
  5498.         $centreId $request->query->get('centre');
  5499.         $access_token "{$_ENV['goCardless_api']}";
  5500.         $client = new \GoCardlessPro\Client([
  5501.             'access_token' => $access_token,
  5502.             'environment'  => \GoCardlessPro\Environment::LIVE,
  5503.         ]);
  5504.         $redirectFlow $client->redirectFlows()->complete(
  5505.             $url//The redirect flow ID from above.
  5506.             ["params" => ["session_token" => $token]]
  5507.         );
  5508.         $customers $client->customers()->list()->records;
  5509.         $mandats $client->mandates()->list();
  5510.         $confirmation $redirectFlow->confirmation_url;
  5511.         $client $this->getDoctrine()
  5512.             ->getRepository(Centre::class)
  5513.             ->findOneBy(['id' => $centreId]);
  5514.         $client->setMandat($redirectFlow->links->mandate);
  5515.         $entityManager->flush();
  5516.         return $this->json([
  5517.             'confirmation' => $confirmation,
  5518.             'clients' => $customers,
  5519.             'mandats' => $mandats,
  5520.             'mandatId' => $redirectFlow->links->mandate
  5521.         ]);
  5522.     }
  5523.     /**
  5524.      * @Route("/centre/{id}/mandat/", name="getCentreMandatById", methods={"GET"})
  5525.      */
  5526.     public function getCentreMandatGyId(Centre $centreRequest $request)
  5527.     {
  5528.         $mandat $centre->getMandat();
  5529.         if ($mandat != null) {
  5530.             $client = new \GoCardlessPro\Client(array(
  5531.                 'access_token' => "{$_ENV['goCardless_api']}",
  5532.                 'environment'  => \GoCardlessPro\Environment::LIVE,
  5533.             ));
  5534.             $infoMandat =  $client->mandates()->get($mandat);
  5535.         } else {
  5536.             $infoMandat "";
  5537.         }
  5538.         return $this->json([
  5539.             'mandat' => $infoMandat,
  5540.         ]);
  5541.     }
  5542.     /**
  5543.      * @Route("/checkFacturation/centres", name="checkFacturation", methods={"GET"})
  5544.      */
  5545.     public function checkFacturation()
  5546.     {
  5547.         $centres $this->getDoctrine()
  5548.             ->getRepository(Centre::class)
  5549.             ->findAll();
  5550.         foreach ($centres as $centre) {
  5551.             $inscription $centre->getSignupDate();
  5552.             $origin = new DateTime(date_format($inscription'Y-m-d'));
  5553.             $target = new DateTime('now');
  5554.             $interval $origin->diff($target);
  5555.             $month $interval->format('%m');
  5556.             if ($month 0) {
  5557.                 $dayNow $target->format("d");
  5558.                 $day $origin->format("d");
  5559.                 if ($day == $dayNow) {
  5560.                     $this->getFacturationByCentre($centre);
  5561.                 }
  5562.             }
  5563.         }
  5564.         return $this->json([
  5565.             'mandat' => $month,
  5566.         ]);
  5567.     }
  5568.     /**
  5569.      * @Route("/facturation/centre/{id}", name="getFacturationByCentre", methods={"GET"})
  5570.      */
  5571.     public function getFacturationByCentre(Centre $centre)
  5572.     {
  5573.         $entityManager $this->getDoctrine()->getManager();
  5574.         /**** ABONNEMENT ****/
  5575.         $dateInscription $centre->getSignupDate();
  5576.         $origin = new DateTime(date_format($dateInscription'Y-m-d'));
  5577.         $target = new DateTime('now');
  5578.         $interval $origin->diff($target);
  5579.         $month $interval->format('%m');
  5580.         if (intval($month) > 12) {
  5581.             $abonnement 49.90;
  5582.             $reduction 0.00;
  5583.         } elseif (intval($month) == 1) {
  5584.             $abonnement 49.90;
  5585.             $reduction 59.88;
  5586.         } else {
  5587.             $abonnement 39.90;
  5588.             $reduction 12.00;
  5589.         }
  5590.         /**** NOMBRE D'AUDIOS ****/
  5591.         $audios $this->getDoctrine()
  5592.             ->getRepository(AudioCentre::class)
  5593.             ->findBy(['id_centre' => $centre]);
  5594.         $audioSupplementaire count($audios) - 1;
  5595.         $audioAbonnement 19.90 $audioSupplementaire;
  5596.         $jour date("Y-m-d");
  5597.         $dateFin = new DateTime($jour);
  5598.         $dateDebut  strtotime($jour "- 1 months");
  5599.         $dateDebut date("Y-m-d"$dateDebut);
  5600.         $dateDebut = new DateTime($dateDebut);
  5601.         /**** MY RDV ****/
  5602.         $myrdv 0;
  5603.         $rdvs $this->getDoctrine()
  5604.             ->getRepository(Rdv::class)
  5605.             ->findRDVCentreBetweenDateWithoutTest($dateDebut$dateFin$centre->getID());
  5606.         $myrdv $myrdv + (50 count($rdvs));
  5607.         /**** MY RDV ADVANCED ****/
  5608.         $myRdvAdvanced 0;
  5609.         $rdvsA $this->getDoctrine()
  5610.             ->getRepository(Rdv::class)
  5611.             ->findRDVCentreBetweenDateWithTestId($dateDebut$dateFin$centre->getID());
  5612.         $myRdvAdvanced $myRdvAdvanced + (100 count($rdvsA));
  5613.         /**** MY LEAD ****/
  5614.         $mylead 0;
  5615.         $nbMyLead 0;
  5616.         $rdvsCanceled $this->getDoctrine()
  5617.             ->getRepository(Rdv::class)
  5618.             ->findCanceledRdvCentreBetweenDateWithoutTest($dateDebut$dateFin$centre->getID());
  5619.         foreach ($rdvsCanceled as $rdvc) {
  5620.             if (!is_null($rdvc->getIdClient())) {
  5621.                 $rdvClient $this->getDoctrine()
  5622.                     ->getRepository(Rdv::class)
  5623.                     ->findRDVLeadByClient($dateDebut$centre->getID(), $rdvc->getIdClient()->getID());
  5624.                 if (count($rdvClient) == 0) {
  5625.                     $mylead $mylead 35;
  5626.                     $nbMyLead $nbMyLead 1;
  5627.                 }
  5628.             }
  5629.         }
  5630.         /**** MY LEAD ADVANCED****/
  5631.         $myleadAdvanced 0;
  5632.         $nbMyLeadAdvanced 0;
  5633.         $rdvsCanceledA $this->getDoctrine()
  5634.             ->getRepository(Rdv::class)
  5635.             ->findCanceledRdvCentreBetweenDateWithTest($dateDebut$dateFin$centre->getID());
  5636.         foreach ($rdvsCanceledA as $rdvc) {
  5637.             if (!is_null($rdvc->getIdClient())) {
  5638.                 $rdvClient $this->getDoctrine()
  5639.                     ->getRepository(Rdv::class)
  5640.                     ->findRDVLeadByClient($dateDebut$centre->getID(), $rdvc->getIdClient()->getID());
  5641.                 if (count($rdvClient) == 0) {
  5642.                     $myleadAdvanced $myleadAdvanced 35;
  5643.                     $nbMyLeadAdvanced $nbMyLeadAdvanced 1;
  5644.                 }
  5645.             }
  5646.         }
  5647.         // Recuperation de l'ID vos facture ou creation 
  5648.         if (!is_null($centre->getFactureId())) {
  5649.             $factureId $centre->getFactureId();
  5650.         } else {
  5651.             $curl curl_init();
  5652.             curl_setopt_array($curl, array(
  5653.                 CURLOPT_URL => 'https://myaudio.vosfactures.fr/clients.json',
  5654.                 CURLOPT_RETURNTRANSFER => true,
  5655.                 CURLOPT_ENCODING => '',
  5656.                 CURLOPT_MAXREDIRS => 10,
  5657.                 CURLOPT_TIMEOUT => 0,
  5658.                 CURLOPT_FOLLOWLOCATION => true,
  5659.                 CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  5660.                 CURLOPT_CUSTOMREQUEST => 'POST',
  5661.                 CURLOPT_POSTFIELDS => '{ 
  5662.                 "api_token": "pRHakmigmSJuVSYbcBS",
  5663.                 "client": { 
  5664.                     "name":"' $centre->getName() . '", 
  5665.                     "city": "' $centre->getCity() . '", 
  5666.                     "country": "France", 
  5667.                     "email": "' $centre->getIdGerant()->getMail() . '", 
  5668.                     "post_code": "' $centre->getPostale() . '", 
  5669.                     "street":"' $centre->getAddress() . '",
  5670.                     "phone": "' $centre->getPhone() . '"
  5671.                 }
  5672.             }',
  5673.                 CURLOPT_HTTPHEADER => array(
  5674.                     'Accept: application/json',
  5675.                     'Content-Type: application/json'
  5676.                 ),
  5677.             ));
  5678.             $response1 curl_exec($curl);
  5679.             $rep =  json_decode($response1);
  5680.             $factureId $rep->{'id'};
  5681.             $centre->setFactureId($rep->{'id'});
  5682.             $entityManager->flush();
  5683.         }
  5684.         // Création de la nouvelle facture 
  5685.         $curl curl_init();
  5686.         curl_setopt_array($curl, array(
  5687.             CURLOPT_URL => 'https://myaudio.vosfactures.fr/invoices.json',
  5688.             CURLOPT_RETURNTRANSFER => true,
  5689.             CURLOPT_ENCODING => '',
  5690.             CURLOPT_MAXREDIRS => 10,
  5691.             CURLOPT_TIMEOUT => 0,
  5692.             CURLOPT_FOLLOWLOCATION => true,
  5693.             CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  5694.             CURLOPT_CUSTOMREQUEST => 'POST',
  5695.             CURLOPT_POSTFIELDS => '{ 
  5696.               "api_token": "pRHakmigmSJuVSYbcBS",
  5697.               "invoice": {
  5698.                 "department_id": 937362, 
  5699.                 "client_id": ' intval($centre->getFactureId()) . ',
  5700.                 "test": true,
  5701.                 "discount_kind":"amount",
  5702.                 "show_discount":true,
  5703.                 "positions":[
  5704.                     {"product_id": 102520343, "quantity":1, "discount": "' $reduction '"}, 
  5705.                     {"product_id": 103129798, "quantity": ' $audioSupplementaire '},
  5706.                     {"product_id": 102520426, "quantity": ' $nbMyLead '},
  5707.                     {"product_id": 102520439, "quantity": ' $nbMyLeadAdvanced '},
  5708.                     {"product_id": 102520392, "quantity": ' count($rdvs) . '},
  5709.                     {"product_id": 102520413, "quantity": ' count($rdvsA) . '}
  5710.                 ]
  5711.             }
  5712.           }',
  5713.             CURLOPT_HTTPHEADER => array(
  5714.                 'Accept: application/json',
  5715.                 'Content-Type: application/json'
  5716.             ),
  5717.         ));
  5718.         $fact curl_exec($curl);
  5719.         $fact =  json_decode($fact);
  5720.         $factId $fact->{'id'};
  5721.         $tokenId $fact->{'token'};
  5722.         $numeroFact $fact->{'number'};
  5723.         $montantHT $fact->{'price_net'};
  5724.         $montantTTC $fact->{'price_gross'};
  5725.         $dateFact $target;
  5726.         //POST FACTURE 
  5727.         $facture = new Factures();
  5728.         $facture->setId(intval($factId));
  5729.         $facture->setToken($tokenId);
  5730.         $facture->setDate($dateFact);
  5731.         $facture->setCentre($centre);
  5732.         $facture->setNumero($numeroFact);
  5733.         $facture->setPrixHT($montantHT);
  5734.         $facture->setPrixTTC($montantTTC);
  5735.         $entityManager->persist($facture);
  5736.         $entityManager->flush();
  5737.         $centimes floatval($montantTTC) * 100;
  5738.         //Envoi a Gocardless
  5739.         if (!is_null($centre->getMandat())) {
  5740.             $access_token "{$_ENV['goCardless_api']}";
  5741.             $client = new \GoCardlessPro\Client([
  5742.                 'access_token' => $access_token,
  5743.                 'environment'  => \GoCardlessPro\Environment::LIVE,
  5744.             ]);
  5745.             $redirectFlow $client->payments()->create([
  5746.                 "params" => [
  5747.                     "amount" => $centimes,
  5748.                     "currency" => "EUR",
  5749.                     "metadata" => [
  5750.                         "order_dispatch_date" => date("Y-m-d")
  5751.                     ],
  5752.                     "links" => [
  5753.                         "mandate" => $centre->getMandat()
  5754.                     ]
  5755.                 ]
  5756.             ]);
  5757.             $paiementId $redirectFlow->{'api_response'}->{'body'}->{'payments'}->{'id'};
  5758.             $facture->setPaiement($paiementId);
  5759.             $entityManager->persist($facture);
  5760.             $entityManager->flush();
  5761.         } else {
  5762.             $paiementId 0;
  5763.             $redirectFlow "";
  5764.         }
  5765.         return $this->json([
  5766.             'centre' => $centre->getID(),
  5767.             'reduction' => $reduction,
  5768.             'mandat' =>  $interval->format('%m mois'),
  5769.             'audio' => count($audios),
  5770.             'date_debut' => $dateDebut,
  5771.             'date_fin' => $dateFin,
  5772.             'MyRDV' => $myrdv,
  5773.             'MyRDVAdvanced' => $myRdvAdvanced,
  5774.             'MyLead' => $mylead,
  5775.             'MyLeadAdvanced' => $myleadAdvanced,
  5776.             'idFact' => $factureId,
  5777.             'factureId' => $factId,
  5778.             'tokenFact' => $tokenId,
  5779.             'dateFacture' => $dateFact,
  5780.             'numeroFact' => $numeroFact,
  5781.             'paiementId' => $paiementId,
  5782.             'redirect' => $redirectFlow
  5783.         ]);
  5784.     }
  5785.     /**
  5786.      * @Route("/getPaiement/", name="getPaiement", methods={"GET"})
  5787.      */
  5788.     public function getPaiement()
  5789.     {
  5790.         //Envoi a Gocardless
  5791.         $access_token "{$_ENV['goCardless_api']}";
  5792.         $client = new \GoCardlessPro\Client([
  5793.             'access_token' => $access_token,
  5794.             'environment'  => \GoCardlessPro\Environment::LIVE,
  5795.         ]);
  5796.         $redirectFlow $client->payments()->get("PM004RNN4TTSXJ");
  5797.         return $this->json([
  5798.             'redirect' => $redirectFlow
  5799.         ]);
  5800.     }
  5801.     /**
  5802.      * @Route("/gerantCenter/{id}/", name="getGerantCentre", methods={"GET","HEAD"})
  5803.      */
  5804.     public function getGerantCentres(Request $requestAudio $audio)
  5805.     {
  5806.         if (!$request->query->get('token')) {
  5807.             return new Response(json_encode([
  5808.                 "message" => "Pas de token n'a été spécifié",
  5809.                 "status" => 401,
  5810.             ]), 401);
  5811.         }
  5812.         $entityManager $this->getDoctrine()->getManager();
  5813.         $audioCentre $this->getDoctrine()
  5814.             ->getRepository(Centre::class)->findBy(['id_gerant' => $audio->getId()]);
  5815.         //dd($audioCentre);
  5816.         /** @var Token */
  5817.         $token $this->getDoctrine()
  5818.             ->getRepository(Token::class)
  5819.             ->findOneBy(['token' => $request->query->get('token'), 'id_audio' => $audio]);
  5820.         if (!$token) {
  5821.             return new Response(json_encode([
  5822.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5823.                 "status" => 404,
  5824.             ]), 404);
  5825.         }
  5826.         // get token age
  5827.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5828.         // if the token if older than 7 days
  5829.         if ($dateDiff->7) {
  5830.             $entityManager->remove($token);
  5831.             $entityManager->flush();
  5832.             return $this->json([
  5833.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5834.                 'path' => 'src/Controller/ClientController.php',
  5835.                 "status" => 401,
  5836.             ], 401);
  5837.         }
  5838.         // get plan 
  5839.         $planAudio $this->getDoctrine()
  5840.             ->getRepository(Subscription::class)
  5841.             ->findOneBy(['audio' => $audio->getId()]);
  5842.         if ($planAudio) {
  5843.             $planQuanity $planAudio->getPlan()->getId();
  5844.         } else {
  5845.             $planAudio $this->getDoctrine()
  5846.                 ->getRepository(SpecificSubscription::class)
  5847.                 ->findOneBy(['audio' => $audio->getId()]);
  5848.             if ($planAudio) {
  5849.                 $planQuanity $planAudio->getPlan()->getId();
  5850.             } else {
  5851.                 $planAudio $this->getDoctrine()
  5852.                     ->getRepository(PartnerSubscription::class)
  5853.                     ->findOneBy(['audio' => $audio->getId()]);
  5854.                 $planQuanity $planAudio->getPlan()->getId();
  5855.             }
  5856.         }
  5857.         if ($audio->getIsPartner()) {
  5858.             // get plan 
  5859.             $planAudio $this->getDoctrine()
  5860.                 ->getRepository(PartnerSubscription::class)
  5861.                 ->findOneBy(['audio' => $audio->getId()]);
  5862.         } else {
  5863.             // get plan 
  5864.             $planAudio $this->getDoctrine()
  5865.                 ->getRepository(Subscription::class)
  5866.                 ->findOneBy(['audio' => $audio->getId()]);
  5867.             if (!$planAudio) {
  5868.                 $planAudio $this->getDoctrine()
  5869.                     ->getRepository(SpecificSubscription::class)
  5870.                     ->findOneBy(['audio' => $audio->getId()]);
  5871.             }
  5872.         }
  5873.         if (!$planAudio)
  5874.             return $this->json([
  5875.                 "message" => "Plan nexiste pas",
  5876.                 "status" => 404,
  5877.             ]);
  5878.         if ($planAudio) {
  5879.             $planQuanity $planAudio->getQuantity();
  5880.             $planAmount $planAudio->getPaidAmount();
  5881.             $planName $planAudio->getPlan()->getName();
  5882.             $planInterval $planAudio->getPlanInterval();
  5883.             $planId $planAudio->getPlan()->getId();
  5884.         }
  5885.         $centers array_map(function ($centre) {
  5886.             return [
  5887.                 "id" => $centre->getId(),
  5888.                 "address" => $centre->getAddress(),
  5889.                 "city" => $centre->getCity(),
  5890.                 "name" => $centre->getName(),
  5891.                 "website" => $centre->getWebsite(),
  5892.                 "isSign" => $centre->getIsSign(),
  5893.                 'urlRdv' => $centre->getUrlRdv()
  5894.             ];
  5895.         }, $audioCentre);
  5896.         return $this->json([
  5897.             "centers" => $centers,
  5898.             "planId" => $planId,
  5899.             "planQuantity" => $planQuanity,
  5900.             "planAmount" => $planAmount,
  5901.             "planName" => $planName,
  5902.             "planInterval" => $planInterval,
  5903.             "status" => 200
  5904.         ]);
  5905.     }
  5906.     /**
  5907.      * @Route("/center/add", name="postCenterAudio", methods={"POST"})
  5908.      */
  5909.     public function postCenterPro(Request $requestPublicFunction $publicFunctionStripeService $stripeService): Response
  5910.     {
  5911.         $data json_decode($request->getContent(), true);
  5912.         $audioCheckTel $this->getDoctrine()
  5913.             ->getRepository(Centre::class)
  5914.             ->findOneBy(["phone" => $data['phone']]);
  5915.         if ($audioCheckTel && !$data['isSamePhone']) {
  5916.             return $this->json([
  5917.                 "message" => "Le numéro de téléphone existe déjà",
  5918.                 "status" => 404,
  5919.             ]);
  5920.         }
  5921.         if (!isset($data["token"])) {
  5922.             return new Response(json_encode([
  5923.                 "message" => "Pas de token n'a été spécifié",
  5924.                 "status" => 401,
  5925.             ]), 401);
  5926.         }
  5927.         $entityManager $this->getDoctrine()->getManager();
  5928.         /** @var Token */
  5929.         $token $this->getDoctrine()
  5930.             ->getRepository(Token::class)
  5931.             ->findOneBy(['token' => $data["token"], 'id_audio' => $data["gerant"]]);
  5932.         if (!$token) {
  5933.             return new Response(json_encode([
  5934.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5935.                 "status" => 404,
  5936.             ]), 404);
  5937.         }
  5938.         // get token age
  5939.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5940.         // if the token if older than 7 days
  5941.         if ($dateDiff->7) {
  5942.             $entityManager->remove($token);
  5943.             $entityManager->flush();
  5944.             return $this->json([
  5945.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5946.                 'path' => 'src/Controller/ClientController.php',
  5947.                 "status" => 401,
  5948.             ], 401);
  5949.         }
  5950.         $entityManager $this->getDoctrine()->getManager();
  5951.         // update subscription 
  5952.         if (isset($data["subscriptionId"])) {
  5953.             $planAudio $this->getDoctrine()
  5954.                 ->getRepository(Subscription::class)
  5955.                 ->find($data["subscriptionId"]);
  5956.             $quantity $planAudio->getQuantity() + 1;
  5957.             if ($planAudio->getPlanInterval() == "year") {
  5958.                 $discountPercentage 15.8;
  5959.                 $pricePerMonth $planAudio->getPlan()->getPrice();
  5960.                 $discountAnnual = ($pricePerMonth 12) * (- ($discountPercentage 100));
  5961.                 $amount $planAudio->getPaidAmount() + number_format($discountAnnual1);
  5962.             } else {
  5963.                 $amount $planAudio->getPaidAmount() + $planAudio->getPlan()->getPrice();
  5964.             }
  5965.             $planAudio->setQuantity($quantity);
  5966.             $planAudio->setPaidAmount($amount);
  5967.             $entityManager->persist($planAudio);
  5968.             if ($_ENV['APP_ENV']  === 'dev') {
  5969.                 $privateKey $_ENV['STRIPE_SECRET_KEY_TEST'];
  5970.             } else {
  5971.                 $privateKey $_ENV['STRIPE_SECRET_KEY_LIVE'];
  5972.             }
  5973.             $stripeProduct $stripeService->getPriceIdMap();
  5974.             \Stripe\Stripe::setApiKey($privateKey);
  5975.             $cusId $planAudio->getStripeCustomerId();
  5976.             // Retrieve the existing subscription
  5977.             $subscriptions \Stripe\Subscription::all(['customer' => $cusId]);
  5978.             $subscription $subscriptions->data[0];
  5979.             // Determine the price ID for the new product
  5980.             $newPriceId = ($planAudio->getPlanInterval() == "year") ? $stripeProduct['additionnalCenterYearly'] : $stripeProduct['additionnalCenter'];
  5981.             // Find if the price ID already exists in the subscription items
  5982.             $existingItem null;
  5983.             foreach ($subscription->items->data as $item) {
  5984.                 if ($item->price->id == $newPriceId) {
  5985.                     $existingItem $item;
  5986.                     break;
  5987.                 }
  5988.             }
  5989.             // Update quantity if the item exists, otherwise create a new item
  5990.             if ($planAudio->getQuantity() > 2) {
  5991.                 // Update the quantity of the existing item
  5992.                 $newQuantity $existingItem->quantity 1;
  5993.                 \Stripe\SubscriptionItem::update($existingItem->id, [
  5994.                     'quantity' => $newQuantity,
  5995.                 ]);
  5996.             } else {
  5997.                 // Create a new subscription item
  5998.                 \Stripe\SubscriptionItem::create([
  5999.                     'subscription' => $subscription->id,
  6000.                     'price' => $newPriceId,
  6001.                     'quantity' => 1,
  6002.                 ]);
  6003.             }
  6004.         }
  6005.         // generate color code 
  6006.         $colors = array(
  6007.             "#FFC0CB"// Pink
  6008.             "#FFD700"// Gold
  6009.             "#90EE90"// Light Green
  6010.             "#87CEFA"// Light Sky Blue
  6011.             "#FFA07A"// Light Salmon
  6012.             "#F0E68C"// Khaki
  6013.             "#B0C4DE"// Light Steel Blue
  6014.             "#98FB98"// Pale Green
  6015.             "#FFB6C1"// Light Pink
  6016.             "#ADD8E6"// Light Blue
  6017.             "#FF69B4"// Hot Pink
  6018.             "#FFA500"// Orange
  6019.             "#00FF7F"// Spring Green
  6020.             "#AFEEEE"// Pale Turquoise
  6021.             "#FF8C00"// Dark Orange
  6022.             "#FFE4B5"// Moccasin
  6023.             "#00CED1"// Dark Turquoise
  6024.             "#7FFFD4"// Aquamarine
  6025.             "#FF4500"// Orange Red
  6026.             "#00FA9A"// Medium Spring Green
  6027.             "#FFF0F5"// Lavender Blush
  6028.             "#00BFFF"// Deep Sky Blue
  6029.             "#FF6347"// Tomato
  6030.             "#20B2AA"// Light Sea Green
  6031.             "#FFFF00"// Yellow
  6032.             "#32CD32"// Lime Green
  6033.             "#FFF5EE"// Seashell
  6034.             "#1E90FF"// Dodger Blue
  6035.             "#CD5C5C"// Indian Red
  6036.             "#8FBC8F"// Dark Sea Green
  6037.             "#F0FFFF"// Azure
  6038.             "#4169E1"// Royal Blue
  6039.             "#FF8B00"// Dark Orange
  6040.             "#66CDAA"// Medium Aquamarine
  6041.             "#FFFACD"// Lemon Chiffon
  6042.             "#6495ED"// Cornflower Blue
  6043.             "#FF7F50"// Coral
  6044.             "#00FF00"// Lime
  6045.             "#FAFAD2"// Light Goldenrod Yellow
  6046.             "#87CEEB"// Sky Blue
  6047.             "#DC143C"// Crimson
  6048.             "#2E8B57"// Sea Green
  6049.             "#F5DEB3"// Wheat
  6050.             "#4682B4"// Steel Blue
  6051.             "#CD853F"// Peru
  6052.             "#8A2BE2"// Blue Violet
  6053.             "#D2691E"// Chocolate
  6054.             "#6A5ACD"// Slate Blue
  6055.             "#F5F5DC"// Beige
  6056.             "#7B68EE"// Medium Slate Blue
  6057.         );
  6058.         // short initial 
  6059.         $name $data['name'];
  6060.         $words explode(' '$name);
  6061.         $initials '';
  6062.         foreach ($words as $word) {
  6063.             $initials .= strtoupper(substr($word01));
  6064.         }
  6065.         $initials strtoupper($initials);
  6066.         $shortName substr($initials02);
  6067.         $randomColor $colors[array_rand($colors)];
  6068.         // get gerant
  6069.         $gerant $this->getDoctrine()
  6070.             ->getRepository(Audio::class)
  6071.             ->find($data['gerant']);
  6072.         // set center
  6073.         $centre = new Centre();
  6074.         // generate slug url 
  6075.         $slug $this->slugger->slug($data["name"])->lower();
  6076.         $slugify $this->getDoctrine()
  6077.             ->getRepository(Centre::class)
  6078.             ->findOneBy(array('slug' => $slug));
  6079.         if ($slugify) {
  6080.             $centre->setSlug($slug "-1");
  6081.         } else {
  6082.             $centre->setSlug($slug);
  6083.         }
  6084.         $centre->setName($data["name"]);
  6085.         if (isset($data["imgUrl"]))
  6086.             $centre->setImgUrl($data["imgUrl"]);
  6087.         if (isset($data["finessURL"]))
  6088.             $centre->setFinessUrl($data["finessURL"]);
  6089.         $centre->setIsRdvDomicile($data["isRdvDomicile"]);
  6090.         $centre->setIdGerant($gerant);
  6091.         $centre->setAddress($data["address"]);
  6092.         $centre->setPostale($data["postal"]);
  6093.         $centre->setCity($data["city"]);
  6094.         $centre->setFiness($data["finess"]);
  6095.         $centre->setIsValid(true);
  6096.         $centre->setSiret($data["siret"]);
  6097.         $centre->setIsSign(1);
  6098.         $centre->setWebsite($data["website"]);
  6099.         $centre->setSignupDate(new \DateTime());
  6100.         if ($data['isSamePhone']) {
  6101.             $principalCenter $this->getDoctrine()
  6102.                 ->getRepository(AudioCentre::class)
  6103.                 ->findOneBy(['id_audio' => $gerant]);
  6104.             $phone $principalCenter $principalCenter->getIdCentre()->getPhone() : "";
  6105.             $centre->setPhone($phone);
  6106.         } else {
  6107.             $centre->setPhone($data['phone']);
  6108.         }
  6109.         $centre->setIsHandicap($data["isHandicap"]);
  6110.         $centre->setInitial($shortName);
  6111.         $centre->setLongitude($data["longitude"]);
  6112.         $centre->setLatitude($data["latitude"]);
  6113.         $centre->setCalendarColor($randomColor);
  6114.         $centre->setHoraire($publicFunction->centreHoraire2);
  6115.         $centerHoliday json_decode($publicFunction->centreHoraire4true);
  6116.         $centre->setHorairesHoliday($centerHoliday);
  6117.         $entityManager->persist($centre);
  6118.         // set audio center
  6119.         $audioCentre = new AudioCentre();
  6120.         $audioCentre->setIdAudio($gerant);
  6121.         $audioCentre->setIdCentre($centre);
  6122.         $audioCentre->setIsConfirmed(true);
  6123.         $audioCentre->setHoraire($publicFunction->centreHoraire2);
  6124.         $centerHoliday json_decode($publicFunction->centreHoraire4true);
  6125.         $audioCentre->setHorairesHoliday($centerHoliday);
  6126.         $entityManager->persist($audioCentre);
  6127.         // set access to center
  6128.         $accessCentre = new AccessCentre();
  6129.         foreach ($data["access"] as $accessData) {
  6130.             if (isset($accessData["metro"]))
  6131.                 $accessCentre->setMetro(json_encode($accessData["metro"], JSON_FORCE_OBJECT));
  6132.             if (isset($accessData["bus"]))
  6133.                 $accessCentre->setBus(json_encode($accessData["bus"], JSON_FORCE_OBJECT));
  6134.             if (isset($accessData["tram"]))
  6135.                 $accessCentre->setTram(json_encode($accessData["tram"], JSON_FORCE_OBJECT));
  6136.             if (isset($accessData["rer"]))
  6137.                 $accessCentre->setRer(json_encode($accessData["rer"], JSON_FORCE_OBJECT));
  6138.             if (isset($accessData["parkingPublic"]))
  6139.                 $accessCentre->setParkingPublic(json_encode($accessData["parkingPublic"], JSON_FORCE_OBJECT));
  6140.             if (isset($accessData["parkingPrivate"]))
  6141.                 $accessCentre->setParkingPrivate(json_encode($accessData["parkingPrivate"], JSON_FORCE_OBJECT));
  6142.             if (isset($accessData["other"]))
  6143.                 $accessCentre->setOther(json_encode($accessData["other"], JSON_FORCE_OBJECT));
  6144.         }
  6145.         $accessCentre->setIdCentre($centre);
  6146.         $entityManager->persist($accessCentre);
  6147.         // save print setting 
  6148.         $setting = new Setting();
  6149.         $setting->setName($data["name"]);
  6150.         $setting->setAddress($data["address"]);
  6151.         $setting->setPhone($data["phone"]);
  6152.         $setting->setLogoUrl($centre->getImgUrl());
  6153.         $setting->setWebsite($data["website"]);
  6154.         $setting->setFirstname($gerant->getName());
  6155.         $setting->setLastname($gerant->getLastname());
  6156.         $setting->setEmail($gerant->getMail());
  6157.         $setting->setSeuilCaDroite(true);
  6158.         $setting->setSeuilCaGauche(true);
  6159.         $setting->setSeuilConfortDroite(true);
  6160.         $setting->setSeuilinconfortDroite(true);
  6161.         $setting->setSeuilInConfortGauche(true);
  6162.         $setting->setSeuilConfortGauche(true);
  6163.         $setting->setSeuilCoDroite(true);
  6164.         $setting->setSeuilCoGauche(true);
  6165.         $setting->setSeuilCaMaskingDroite(true);
  6166.         $setting->setSeuilCaMaskingGauche(true);
  6167.         $setting->setSeuilCoMaskingDroite(true);
  6168.         $setting->setSeuilCoMaskingGauche(true);
  6169.         /*
  6170.          $setting->setCasqueDroite(false);
  6171.          $setting->setCasqueGauche(false);
  6172.          $setting->setCasqueBinaural(false);
  6173.          $setting->setChampsLibreDroite(false);
  6174.          $setting->setChampsLibreGauche(false);
  6175.          $setting->setChampsLibreBinaural(false);
  6176.          $setting->setChampsLibreAppDroite(false);
  6177.          $setting->setChampsLibreAppGauche(false);
  6178.          $setting->setChampsLibreAppBinaural(false);*/
  6179.         $setting->setCasqueDroite(true);
  6180.         $setting->setCasqueGauche(true);
  6181.         $setting->setCasqueBinaural(true);
  6182.         $setting->setChampsLibreDroite(true);
  6183.         $setting->setChampsLibreGauche(true);
  6184.         $setting->setChampsLibreBinaural(true);
  6185.         $setting->setChampsLibreAppDroite(true);
  6186.         $setting->setChampsLibreAppGauche(true);
  6187.         $setting->setChampsLibreAppBinaural(true);
  6188.         $setting->setCentre($centre);
  6189.         $entityManager->persist($setting);
  6190.         //add the centre access
  6191.         if (isset($data["mutuelle"]))
  6192.             foreach ($data["mutuelle"] as $mutuelleObject) {
  6193.                 $mutuelle $this->getDoctrine()
  6194.                     ->getRepository(Mutuelle::class)
  6195.                     ->findOneBy(['id' => $mutuelleObject]);
  6196.                 if ($mutuelle == null) {
  6197.                     return new Response(json_encode([
  6198.                         'message' => 'Error, no mutuelle found at this id ' $mutuelleObject,
  6199.                         'path' => 'src/Controller/CentreController.php',
  6200.                     ]));
  6201.                 } else {
  6202.                     $centreMutuelle = new CentreMutuelle();
  6203.                     $centreMutuelle->setIdMutuelle($mutuelle);
  6204.                     $centreMutuelle->setIdCentre($centre);
  6205.                     if (isset($data["otherMutuelle"]) && $mutuelle->getLibelle() == "Autres")
  6206.                         $centreMutuelle->setOther(json_encode($data["otherMutuelle"], JSON_FORCE_OBJECT));
  6207.                     $entityManager->persist($centreMutuelle);
  6208.                 }
  6209.             }
  6210.         //other spetiality 
  6211.         if (isset($data["otherSpetiality"])) {
  6212.             $audioSpecialite = new AudioSpecialite();
  6213.             // $audioSpecialite->setIdSpecialite($specialite);
  6214.             $audioSpecialite->setIdAudio($audio);
  6215.             $audioSpecialite->setOther(json_encode($data["otherSpetiality"], JSON_FORCE_OBJECT));
  6216.             $entityManager->persist($audioSpecialite);
  6217.         }
  6218.         if (isset($data["prestation"]))
  6219.             foreach ($data["prestation"] as $prestationId) {
  6220.                 $prestation $this->getDoctrine()
  6221.                     ->getRepository(Prestation::class)
  6222.                     ->findOneBy(['id' => $prestationId]);
  6223.                 if ($prestation == null) {
  6224.                     return new Response(json_encode([
  6225.                         'message' => 'Error, no prestation found at this id ' $prestationId,
  6226.                         'path' => 'src/Controller/CentreController.php',
  6227.                     ]));
  6228.                 } else {
  6229.                     $centrePrestation = new CentrePrestation();
  6230.                     $centrePrestation->setIdPrestation($prestation);
  6231.                     $centrePrestation->setIdCentre($centre);
  6232.                     $entityManager->persist($centrePrestation);
  6233.                 }
  6234.             }
  6235.         // set the galeries for images by default
  6236.         // Define an array of default image URLs
  6237.         $defaultImages = ["by-default-1.jpeg""by-default-2.jpeg""by-default-3.jpeg"];
  6238.         // Iterate through each default image
  6239.         foreach ($defaultImages as $imageUrl) {
  6240.             $centerImage = new CenterImage();
  6241.             $centerImage->setType("image");
  6242.             $centerImage->setUrl($imageUrl);
  6243.             // Associate the center image with the current center
  6244.             $centerImage->setCenter($centre);
  6245.             $entityManager->persist($centerImage);
  6246.         }
  6247.         /* if (isset($data["tier"]))
  6248.         foreach ($data["tier"] as $tierObject) {
  6249.             $tier = $this->getDoctrine()
  6250.                 ->getRepository(Tier::class)
  6251.                 ->findOneBy(['id' => $tierObject]);
  6252.             if ($tier == null) {
  6253.                 return new Response(json_encode([
  6254.                     'message' => 'Error, no tier found at this id ' . $tierObject,
  6255.                     'path' => 'src/Controller/CentreController.php',
  6256.                 ]));
  6257.             } else {
  6258.                 $centreTier = new CentreTier();
  6259.                 $centreTier->setIdTier($tier);
  6260.                 $centreTier->setIdCentre($centre);
  6261.                 $entityManager->persist($centreTier);
  6262.             }
  6263.         }*/
  6264.         $entityManager->flush();
  6265.         $name $centre->getName();
  6266.         $city $centre->getCity();
  6267.         $postal $centre->getPostale();
  6268.         $nameSlug strtolower(preg_replace('/[^a-zA-Z0-9]+/''-'trim($name)));
  6269.         $citySlug strtolower(preg_replace('/[^a-zA-Z0-9]+/''-'trim($city)));
  6270.         $baseClient $_ENV['BASE_client'] ?? 'https://default-client-url.com';
  6271.         $urlRdv "{$baseClient}audioprothesiste/{$citySlug}/{$postal}/{$nameSlug}/prise-de-rdvaudioprothesiste-rapide/{$centre->getId()}";
  6272.         if (!$centre->getUrlRdv() || $centre->getUrlRdv() !== $urlRdv) {
  6273.             $centre->setUrlRdv($urlRdv);
  6274.             $entityManager->persist($centre);
  6275.             $entityManager->flush();
  6276.         }
  6277.         return $this->json([
  6278.             'message' => 'centre a été ajouté',
  6279.             "status" => 200
  6280.         ]);
  6281.     }
  6282.     /**
  6283.      * @Route("/getcentre/{id}", name="getCentreId", methods={"GET","HEAD"})
  6284.      */
  6285.     public function getCentreId(Centre $centrePublicFunction $publicFunction): Response
  6286.     {
  6287.         $accessCentre $this->getDoctrine()->getRepository(AccessCentre::class)
  6288.             ->findOneBy(array('id_centre' => $centre->getId()));
  6289.         /*if (!$accessCentre)
  6290.             return new Response(json_encode([
  6291.                 'message' => 'Error, no accessCentre found at this id',
  6292.                 'path' => 'src/Controller/CentreController.php',
  6293.             ]), 404);
  6294.        */
  6295.         /** @var CentrePrestation[]*/
  6296.         $prestations $this->getDoctrine()->getRepository(CentrePrestation::class)
  6297.             ->findBy(array('id_centre' => $centre->getId()));
  6298.         $resultPrestation = new ArrayCollection();
  6299.         foreach ($prestations as $prestation) {
  6300.             $resultPrestation->add([
  6301.                 "id" => $prestation->getIdPrestation()->getId(),
  6302.                 "titre" => $prestation->getIdPrestation()->getLibelle(),
  6303.             ]);
  6304.         }
  6305.         /** @var CentreMutuelle[]*/
  6306.         $mutuelles $this->getDoctrine()->getRepository(CentreMutuelle::class)
  6307.             ->findBy(array('id_centre' => $centre->getId()));
  6308.         $resultMutuelle = new ArrayCollection();
  6309.         foreach ($mutuelles as $mutuelle) {
  6310.             $resultMutuelle->add([
  6311.                 "id" => $mutuelle->getIdMutuelle()->getId(),
  6312.                 "titre" => $mutuelle->getIdMutuelle()->getLibelle(),
  6313.             ]);
  6314.         }
  6315.         if ($accessCentre) {
  6316.             $metroIDs json_decode($accessCentre->getMetro(), true);
  6317.             $metroNames = [];
  6318.             if (is_array($metroIDs)) {
  6319.                 $stations $this->getDoctrine()->getRepository(Station::class)->findBy(['id' => $metroIDs]);
  6320.                 foreach ($stations as $station) {
  6321.                     $metroNames[] = [
  6322.                         "name" => $station->getName(),
  6323.                         "value" => $station->getId(),
  6324.                     ];
  6325.                 }
  6326.             }
  6327.             return $this->json([
  6328.                 "tram" => json_decode($accessCentre->getTram(), true),
  6329.                 "rer" => json_decode($accessCentre->getRer(), true),
  6330.                 "metro" => $metroNames,
  6331.                 "bus" => json_decode($accessCentre->getBus(), true),
  6332.                 "parking" => json_decode($accessCentre->getParkingPublic(), true),
  6333.                 "parkingPrivate" => json_decode($accessCentre->getParkingPrivate(), true),
  6334.                 "other" => json_decode($accessCentre->getOther(), true),
  6335.                 "id" => $centre->getId(),
  6336.                 "audio_id" => $centre->getIdGerant()->getId(),
  6337.                 "name" => $centre->getName(),
  6338.                 "imgUrl" => $centre->getImgUrl(),
  6339.                 "isRdvDomicile" => $centre->getIsRdvDomicile(),
  6340.                 "address" => $centre->getAddress(),
  6341.                 "numero" => $centre->getNumero(),
  6342.                 "voie" => $centre->getVoie(),
  6343.                 "rue" => $centre->getRue(),
  6344.                 "description" => $centre->getDescription(),
  6345.                 "postale" => $centre->getPostale(),
  6346.                 "city" => $centre->getCity(),
  6347.                 "finess" => $centre->getFiness(),
  6348.                 "siret" => $centre->getSiret(),
  6349.                 "website" => $centre->getWebsite(),
  6350.                 "phone" => $centre->getPhone(),
  6351.                 "imgUrl" => $centre->getImgUrl(),
  6352.                 "aditionnelInfo" => $centre->getAditionnelInfo(),
  6353.                 "initial" => $centre->getInitial(),
  6354.                 "calendarColor" => $centre->getCalendarColor(),
  6355.                 "isHandicap" => $centre->getIsHandicap(),
  6356.                 "longitude" => $centre->getLongitude(),
  6357.                 "latitude" => $centre->getLatitude(),
  6358.                 "isSign" => $centre->getIsSign(),
  6359.                 //"comments" => $comments,
  6360.                 "mutuelles" => $resultMutuelle->toArray(),
  6361.                 "prestations" => $resultPrestation->toArray(),
  6362.                 //"tiers" => $resultTier->toArray(),
  6363.                 //"audio" => $resultAudio->toArray(),
  6364.                 "schedule" => $centre->getHoraire(),
  6365.                 "status" => 200,
  6366.             ]);
  6367.         } else {
  6368.             return $this->json([
  6369.                 "id" => $centre->getId(),
  6370.                 "audio_id" => $centre->getIdGerant()->getId(),
  6371.                 "name" => $centre->getName(),
  6372.                 "imgUrl" => $centre->getImgUrl(),
  6373.                 "isRdvDomicile" => $centre->getIsRdvDomicile(),
  6374.                 "address" => $centre->getAddress(),
  6375.                 "numero" => $centre->getNumero(),
  6376.                 "voie" => $centre->getVoie(),
  6377.                 "rue" => $centre->getRue(),
  6378.                 "description" => $centre->getDescription(),
  6379.                 "postale" => $centre->getPostale(),
  6380.                 "city" => $centre->getCity(),
  6381.                 "finess" => $centre->getFiness(),
  6382.                 "siret" => $centre->getSiret(),
  6383.                 "website" => $centre->getWebsite(),
  6384.                 "phone" => $centre->getPhone(),
  6385.                 "imgUrl" => $centre->getImgUrl(),
  6386.                 "aditionnelInfo" => $centre->getAditionnelInfo(),
  6387.                 "initial" => $centre->getInitial(),
  6388.                 "calendarColor" => $centre->getCalendarColor(),
  6389.                 "isHandicap" => $centre->getIsHandicap(),
  6390.                 "longitude" => $centre->getLongitude(),
  6391.                 "latitude" => $centre->getLatitude(),
  6392.                 // "averageRating" => $publicFunction->calculateRating($centreRdvs),
  6393.                 //"nbrReview" => count($centreRdvs),
  6394.                 "tram" => null,
  6395.                 "rer" => null,
  6396.                 "metro" => null,
  6397.                 "bus" => null,
  6398.                 "parking" => null,
  6399.                 "parkingPrivate" => null,
  6400.                 "other" => null,
  6401.                 "isSign" => $centre->getIsSign(),
  6402.                 //"comments" => $comments,
  6403.                 "mutuelles" => $resultMutuelle->toArray(),
  6404.                 "prestations" => $resultPrestation->toArray(),
  6405.                 //"tiers" => $resultTier->toArray(),
  6406.                 //"audio" => $resultAudio->toArray(),
  6407.                 "schedule" => $centre->getHoraire(),
  6408.                 "status" => 200,
  6409.             ]);
  6410.         }
  6411.     }
  6412.     /**
  6413.      * @Route("/center/update/{id}", name="updateCenterAudio", methods={"POST"})
  6414.      */
  6415.     public function EditCentreBy(Request $requestCentre $centrePublicFunction $publicFunction): Response
  6416.     {
  6417.         $data json_decode($request->getContent(), true);
  6418.         if (!isset($data["token"])) {
  6419.             return new Response(json_encode([
  6420.                 "message" => "Pas de token n'a été spécifié",
  6421.                 "status" => 401,
  6422.             ]), 401);
  6423.         }
  6424.         $audioCheckTel $this->getDoctrine()
  6425.             ->getRepository(Centre::class)
  6426.             ->findOneBy(["phone" => $data['phone']]);
  6427.         /* if ($audioCheckTel)
  6428.         return $this->json([
  6429.             "message" => "Le numéro de téléphone existe déjà",
  6430.             "status" => 404,
  6431.         ]);
  6432.         */
  6433.         $entityManager $this->getDoctrine()->getManager();
  6434.         /** @var Token */
  6435.         $token $this->getDoctrine()
  6436.             ->getRepository(Token::class)
  6437.             ->findOneBy(['token' => $data["token"], 'id_audio' => $data["gerant"]]);
  6438.         if (!$token) {
  6439.             return new Response(json_encode([
  6440.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6441.                 "status" => 404,
  6442.             ]), 404);
  6443.         }
  6444.         // get token age
  6445.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6446.         // if the token if older than 7 days
  6447.         if ($dateDiff->7) {
  6448.             $entityManager->remove($token);
  6449.             $entityManager->flush();
  6450.             return $this->json([
  6451.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6452.                 'path' => 'src/Controller/ClientController.php',
  6453.                 "status" => 401,
  6454.             ], 401);
  6455.         }
  6456.         $entityManager $this->getDoctrine()->getManager();
  6457.         if (isset($data["name"]))
  6458.             $centre->setName($data["name"]);
  6459.         if (isset($data["imgUrl"]))
  6460.             $centre->setImgUrl($data["imgUrl"]);
  6461.         if (isset($data["finessURL"]))
  6462.             $centre->setFinessUrl($data["finessURL"]);
  6463.         if (isset($data["isRdvDomicile"]))
  6464.             $centre->setIsRdvDomicile($data["isRdvDomicile"]);
  6465.         if (isset($data["address"]))
  6466.             $centre->setAddress($data["address"]);
  6467.         if (isset($data["postal"]))
  6468.             $centre->setPostale($data["postal"]);
  6469.         if (isset($data["city"]))
  6470.             $centre->setCity($data["city"]);
  6471.         if (isset($data["finess"]))
  6472.             $centre->setFiness($data["finess"]);
  6473.         if (isset($data["siret"]))
  6474.             $centre->setSiret($data["siret"]);
  6475.         if (isset($data["description"]))
  6476.             $centre->setDescription($data["description"]);
  6477.         if (isset($data["initial"]))
  6478.             $centre->setInitial($data["initial"]);
  6479.         if (isset($data["calendarColor"]))
  6480.             $centre->setCalendarColor($data["calendarColor"]);
  6481.         if (isset($data["website"]))
  6482.             $centre->setWebsite($data["website"]);
  6483.         if (isset($data["aditionnelInfo"]))
  6484.             $centre->setAditionnelInfo($data["aditionnelInfo"]);
  6485.         // Toujours défini à la date actuelle
  6486.         $centre->setSignupDate(new \DateTime());
  6487.         if (isset($data["phone"]))
  6488.             $centre->setPhone($data["phone"]);
  6489.         if (isset($data["isHandicap"]))
  6490.             $centre->setIsHandicap($data["isHandicap"]);
  6491.         if (isset($data["longitude"]))
  6492.             $centre->setLongitude($data["longitude"]);
  6493.         if (isset($data["latitude"]))
  6494.             $centre->setLatitude($data["latitude"]);
  6495.         //  $centre->setHoraire($publicFunction->centreHoraire2);
  6496.         $entityManager->persist($centre);
  6497.         // Fetch access centre data
  6498.         // Fetch access centre data
  6499.         $accessCentre $entityManager->getRepository(AccessCentre::class)->findOneBy(['id_centre' => $centre->getId()]);
  6500.         if ($accessCentre) {
  6501.             // Set the values from the form inputs
  6502.             foreach ($data["access"] as $accessData) {
  6503.                 if (isset($accessData["metro"]))
  6504.                     $accessCentre->setMetro(json_encode($accessData["metro"], JSON_FORCE_OBJECT));
  6505.                 if (isset($accessData["bus"]))
  6506.                     $accessCentre->setBus(json_encode($accessData["bus"], JSON_FORCE_OBJECT));
  6507.                 if (isset($accessData["tram"]))
  6508.                     $accessCentre->setTram(json_encode($accessData["tram"], JSON_FORCE_OBJECT));
  6509.                 if (isset($accessData["rer"]))
  6510.                     $accessCentre->setRer(json_encode($accessData["rer"], JSON_FORCE_OBJECT));
  6511.                 if (isset($accessData["parkingPublic"]))
  6512.                     $accessCentre->setParkingPublic(json_encode($accessData["parkingPublic"], JSON_FORCE_OBJECT));
  6513.                 if (isset($accessData["parkingPrivate"]))
  6514.                     $accessCentre->setParkingPrivate(json_encode($accessData["parkingPrivate"], JSON_FORCE_OBJECT));
  6515.                 if (isset($accessData["other"]))
  6516.                     $accessCentre->setOther(json_encode($accessData["other"], JSON_FORCE_OBJECT));
  6517.             }
  6518.             //$accessCentre->setIdCentre($centre);
  6519.             /*if (isset($data['metro'])) {
  6520.     $metroValues = explode(',', $data['metro']);
  6521.     $accessCentre->setMetro(json_encode($metroValues, JSON_FORCE_OBJECT));
  6522. }
  6523. if (isset($data['bus'])) {
  6524.     $busValues = explode(',', $data['bus']);
  6525.     $accessCentre->setBus(json_encode($busValues, JSON_FORCE_OBJECT));
  6526. }
  6527. if (isset($data['tram'])) {
  6528.     $tramValues = explode(',', $data['tram']);
  6529.     $accessCentre->setTram(json_encode($tramValues, JSON_FORCE_OBJECT));
  6530. }
  6531. if (isset($data['rer'])) {
  6532.     $rerValues = explode(',', $data['rer']);
  6533.     $accessCentre->setRer(json_encode($rerValues, JSON_FORCE_OBJECT));
  6534. }
  6535. if (isset($data['parking'])) {
  6536.     $parkingValues = explode(',', $data['parking']);
  6537.     $accessCentre->setParkingPublic(json_encode($parkingValues, JSON_FORCE_OBJECT));
  6538. }
  6539. if (isset($data['parkingPrivate'])) {
  6540.     $parkingPrivateValues = explode(',', $data['parkingPrivate']);
  6541.     $accessCentre->setParkingPrivate(json_encode($parkingPrivateValues, JSON_FORCE_OBJECT));
  6542. }
  6543. if (isset($data['other'])) {
  6544.     $otherValues = explode(',', $data['other']);
  6545.     $accessCentre->setOther(json_encode($otherValues, JSON_FORCE_OBJECT));
  6546. }*/
  6547.         } else {
  6548.             // Create an instance of AccessCentre
  6549.             $accessCentre = new AccessCentre();
  6550.             // Set the values from the form inputs
  6551.             if (isset($accessData["metro"]))
  6552.                 $accessCentre->setMetro(json_encode($accessData["metro"], JSON_FORCE_OBJECT));
  6553.             if (isset($accessData["bus"]))
  6554.                 $accessCentre->setBus(json_encode($accessData["bus"], JSON_FORCE_OBJECT));
  6555.             if (isset($accessData["tram"]))
  6556.                 $accessCentre->setTram(json_encode($accessData["tram"], JSON_FORCE_OBJECT));
  6557.             if (isset($accessData["rer"]))
  6558.                 $accessCentre->setRer(json_encode($accessData["rer"], JSON_FORCE_OBJECT));
  6559.             if (isset($accessData["parkingPublic"]))
  6560.                 $accessCentre->setParkingPublic(json_encode($accessData["parkingPublic"], JSON_FORCE_OBJECT));
  6561.             if (isset($accessData["parkingPrivate"]))
  6562.                 $accessCentre->setParkingPrivate(json_encode($accessData["parkingPrivate"], JSON_FORCE_OBJECT));
  6563.             if (isset($accessData["other"]))
  6564.                 $accessCentre->setOther(json_encode($accessData["other"], JSON_FORCE_OBJECT));
  6565.             if (isset($data['other'])) {
  6566.                 $otherValues explode(','$data['other']);
  6567.                 $accessCentre->setOther(json_encode($otherValuesJSON_FORCE_OBJECT));
  6568.             }
  6569.         }
  6570.         $mutuels $this->getDoctrine()
  6571.             ->getRepository(CentreMutuelle::class)
  6572.             ->findBy(['id_centre' => $centre->getId()]);
  6573.         $prestations $this->getDoctrine()
  6574.             ->getRepository(CentrePrestation::class)
  6575.             ->findBy(['id_centre' => $centre->getId()]);
  6576.         $entityManager $this->getDoctrine()->getManager();
  6577.         foreach ($mutuels as $mutuel) {
  6578.             $entityManager->remove($mutuel);
  6579.         }
  6580.         foreach ($prestations as $prestation) {
  6581.             $entityManager->remove($prestation);
  6582.         }
  6583.         if (isset($data["mutuelle"]))
  6584.             foreach ($data["mutuelle"] as $mutuelleObject) {
  6585.                 $mutuelle $this->getDoctrine()
  6586.                     ->getRepository(Mutuelle::class)
  6587.                     ->findOneBy(['id' => $mutuelleObject]);
  6588.                 if ($mutuelle == null) {
  6589.                     return new Response(json_encode([
  6590.                         'message' => 'Error, no mutuelle found at this id ' $mutuelleObject,
  6591.                         'path' => 'src/Controller/CentreController.php',
  6592.                     ]));
  6593.                 } else {
  6594.                     $centreMutuelle = new CentreMutuelle();
  6595.                     $centreMutuelle->setIdMutuelle($mutuelle);
  6596.                     $centreMutuelle->setIdCentre($centre);
  6597.                     if (isset($data["otherMutuelle"]) && $mutuelle->getLibelle() == "Autres")
  6598.                         $centreMutuelle->setOther(json_encode($data["otherMutuelle"], JSON_FORCE_OBJECT));
  6599.                     $entityManager->persist($centreMutuelle);
  6600.                 }
  6601.             }
  6602.         //other spetiality 
  6603.         if (isset($data["otherSpetiality"])) {
  6604.             $audioSpecialite = new AudioSpecialite();
  6605.             // $audioSpecialite->setIdSpecialite($specialite);
  6606.             $audioSpecialite->setIdAudio($audio);
  6607.             $audioSpecialite->setOther(json_encode($data["otherSpetiality"], JSON_FORCE_OBJECT));
  6608.             $entityManager->persist($audioSpecialite);
  6609.         }
  6610.         if (isset($data["prestation"]))
  6611.             foreach ($data["prestation"] as $prestationId) {
  6612.                 $prestation $this->getDoctrine()
  6613.                     ->getRepository(Prestation::class)
  6614.                     ->findOneBy(['id' => $prestationId]);
  6615.                 if ($prestation == null) {
  6616.                     return new Response(json_encode([
  6617.                         'message' => 'Error, no prestation found at this id ' $prestationId,
  6618.                         'path' => 'src/Controller/CentreController.php',
  6619.                     ]));
  6620.                 } else {
  6621.                     $centrePrestation = new CentrePrestation();
  6622.                     $centrePrestation->setIdPrestation($prestation);
  6623.                     $centrePrestation->setIdCentre($centre);
  6624.                     $entityManager->persist($centrePrestation);
  6625.                 }
  6626.             }
  6627.         // Set the centre ID
  6628.         $accessCentre->setIdCentre($centre);
  6629.         // Persist the access centre entity
  6630.         $entityManager->persist($accessCentre);
  6631.         $entityManager->flush();
  6632.         return $this->json([
  6633.             'message' => 'centre a été modifié avec succée',
  6634.             "status" => 200
  6635.         ]);
  6636.     }
  6637.     /**
  6638.      * @Route("/centresingle/horaire/{id}", name="setCentreHoraireSingle", methods={"PUT"})
  6639.      */
  6640.     public function setCentreSingleHoraire(Centre $centrePublicFunction $publicFunctionRequest $request)
  6641.     {
  6642.         if (!$request->query->get('token')) {
  6643.             return new Response(json_encode([
  6644.                 "message" => "Pas de token n'a été spécifié",
  6645.                 "status" => 401,
  6646.             ]), 401);
  6647.         }
  6648.         $entityManager $this->getDoctrine()->getManager();
  6649.         /** @var Token */
  6650.         $token $this->getDoctrine()
  6651.             ->getRepository(Token::class)
  6652.             ->findOneBy(['token' => $request->query->get('token'), 'id_audio' => $request->query->get('audio')]);
  6653.         if (!$token) {
  6654.             return new Response(json_encode([
  6655.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6656.                 "status" => 404,
  6657.             ]), 404);
  6658.         }
  6659.         // get token age
  6660.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6661.         // if the token if older than 7 days
  6662.         if ($dateDiff->7) {
  6663.             $entityManager->remove($token);
  6664.             $entityManager->flush();
  6665.             return $this->json([
  6666.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6667.                 'path' => 'src/Controller/AudioController.php',
  6668.                 "status" => 401,
  6669.             ], 401);
  6670.         }
  6671.         $entityManager $this->getDoctrine()->getManager();
  6672.         $data json_decode($request->getContent(), true);
  6673.         $centre->setHoraire($data["horaires"]);
  6674.         $entityManager->flush();
  6675.         return $this->json([
  6676.             "id" => $centre->getId(),
  6677.             "horaires" => $data["horaires"]
  6678.         ]);
  6679.     }
  6680.     /**
  6681.      * @Route("/centresingle/horaire-holiday/{id}", name="setCentreHoraireHolidaySingle", methods={"PUT"})
  6682.      */
  6683.     public function setCentreHoraireHolidaySingle(Centre $centrePublicFunction $publicFunctionRequest $request)
  6684.     {
  6685.         if (!$request->query->get('token')) {
  6686.             return new Response(json_encode([
  6687.                 "message" => "Pas de token n'a été spécifié",
  6688.                 "status" => 401,
  6689.             ]), 401);
  6690.         }
  6691.         $entityManager $this->getDoctrine()->getManager();
  6692.         /** @var Token */
  6693.         $token $this->getDoctrine()
  6694.             ->getRepository(Token::class)
  6695.             ->findOneBy(['token' => $request->query->get('token'), 'id_audio' => $request->query->get('audio')]);
  6696.         if (!$token) {
  6697.             return new Response(json_encode([
  6698.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6699.                 "status" => 404,
  6700.             ]), 404);
  6701.         }
  6702.         // get token age
  6703.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6704.         // if the token if older than 7 days
  6705.         if ($dateDiff->7) {
  6706.             $entityManager->remove($token);
  6707.             $entityManager->flush();
  6708.             return $this->json([
  6709.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6710.                 'path' => 'src/Controller/AudioController.php',
  6711.                 "status" => 401,
  6712.             ], 401);
  6713.         }
  6714.         $entityManager $this->getDoctrine()->getManager();
  6715.         $data json_decode($request->getContent(), true);
  6716.         $centre->setHorairesHoliday($data["horaires"]);
  6717.         $entityManager->flush();
  6718.         return $this->json([
  6719.             "id" => $centre->getId(),
  6720.             "horaires" => $data["horaires"]
  6721.         ]);
  6722.     }
  6723.     /**
  6724.      * @Route("/centres/fData/{id}", name="postCentresImageByFormData", methods={"POST"})
  6725.      */
  6726.     public function postCentresImageByFormData(Centre $centreRequest $requestFileUploader $fileUploader): Response
  6727.     {
  6728.         if (!$request->query->get('token')) {
  6729.             return new Response(json_encode([
  6730.                 "message" => "Pas de token n'a été spécifié",
  6731.                 "status" => 401,
  6732.             ]), 401);
  6733.         }
  6734.         $entityManager $this->getDoctrine()->getManager();
  6735.         /** @var Token */
  6736.         $token $this->getDoctrine()
  6737.             ->getRepository(Token::class)
  6738.             ->findOneBy(['token' => $request->query->get('token'), 'id_audio' => $centre->getIdGerant()]);
  6739.         if (!$token) {
  6740.             return new Response(json_encode([
  6741.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6742.                 "status" => 404,
  6743.             ]), 404);
  6744.         }
  6745.         // get token age
  6746.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6747.         // if the token if older than 7 days
  6748.         if ($dateDiff->7) {
  6749.             $entityManager $this->getDoctrine()->getManager();
  6750.             $entityManager->remove($token);
  6751.             $entityManager->flush();
  6752.             return $this->json([
  6753.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6754.                 'path' => 'src/Controller/AudioController.php',
  6755.                 "status" => 401,
  6756.             ], 401);
  6757.         }
  6758.         // Handle updates to existing images
  6759.         if (isset($_FILES["file"])) {
  6760.             foreach ($_FILES["file"]["error"] as $key => $error) {
  6761.                 if ($error == UPLOAD_ERR_OK) {
  6762.                     $file = [
  6763.                         "name" => $_FILES["file"]["name"][$key],
  6764.                         "type" => $_FILES["file"]["type"][$key],
  6765.                         "tmp_name" => $_FILES["file"]["tmp_name"][$key],
  6766.                         "error" => $_FILES["file"]["error"][$key],
  6767.                         "size" => $_FILES["file"]["size"][$key],
  6768.                     ];
  6769.                     // Extract the image ID from the key
  6770.                     $imageId $key// Ensure this matches how you're identifying images
  6771.                     $image $entityManager->getRepository(CenterImage::class)->find($imageId);
  6772.                     if ($image) {
  6773.                         // Delete old file from the filesystem
  6774.                         $oldFilePath "images/centres/" $image->getUrl();
  6775.                         if (file_exists($oldFilePath)) {
  6776.                             unlink($oldFilePath);
  6777.                         }
  6778.                     } else {
  6779.                         // If no existing image, create a new entity
  6780.                         $image = new CenterImage();
  6781.                         $image->setCenter($centre);
  6782.                     }
  6783.                     // Determine file type (image or video) based on MIME type
  6784.                     $fileType mime_content_type($file['tmp_name']);
  6785.                     if (strpos($fileType'image') !== false) {
  6786.                         // File is an image
  6787.                         $image->setType('image');
  6788.                     } elseif (strpos($fileType'video') !== false) {
  6789.                         // File is a video
  6790.                         $image->setType('video');
  6791.                     }
  6792.                     $newfilename $fileUploader->uploadFormData($file"images/centres/");
  6793.                     if ($newfilename) {
  6794.                         $image->setUrl($newfilename);
  6795.                         $entityManager->persist($image);
  6796.                     }
  6797.                 }
  6798.             }
  6799.         }
  6800.         // Handle new image uploads
  6801.         if (isset($_FILES['newFile'])) {
  6802.             foreach ($_FILES['newFile']['error'] as $key => $error) {
  6803.                 if ($error == UPLOAD_ERR_OK) {
  6804.                     $file = [
  6805.                         'name' => $_FILES['newFile']['name'][$key],
  6806.                         'type' => $_FILES['newFile']['type'][$key],
  6807.                         'tmp_name' => $_FILES['newFile']['tmp_name'][$key],
  6808.                         'error' => $_FILES['newFile']['error'][$key],
  6809.                         'size' => $_FILES['newFile']['size'][$key],
  6810.                     ];
  6811.                     $image = new CenterImage();
  6812.                     $image->setCenter($centre);
  6813.                     $fileType mime_content_type($file['tmp_name']);
  6814.                     if (strpos($fileType'image') !== false) {
  6815.                         $image->setType('image');
  6816.                     } elseif (strpos($fileType'video') !== false) {
  6817.                         $image->setType('video');
  6818.                     }
  6819.                     $newfilename $fileUploader->uploadFormData($file"images/centres/");
  6820.                     if ($newfilename) {
  6821.                         $image->setUrl($newfilename);
  6822.                         $entityManager->persist($image);
  6823.                     }
  6824.                 }
  6825.             }
  6826.         }
  6827.         $entityManager->flush(); // Apply changes to the database
  6828.         return $this->json([
  6829.             "imgUrl" => $centre->getImgUrl(),
  6830.         ]);
  6831.     }
  6832.     /**
  6833.      * @Route("/centre/images/{id}", name="getCentresImage", methods={"GET"})
  6834.      */
  6835.     public function getCentresImage(Centre $centerPublicFunction $publicFunction): Response
  6836.     {
  6837.         $images $this->getDoctrine()
  6838.             ->getRepository(CenterImage::class)
  6839.             ->findBy(['center' => $center]);
  6840.         $imageCenter array_map(function ($image) {
  6841.             return [
  6842.                 "id" => $image->getId(),
  6843.                 "url" => $image->getUrl(),
  6844.                 "type" => $image->getType(),
  6845.             ];
  6846.         }, $images);
  6847.         return $this->json([
  6848.             "images" => $imageCenter,
  6849.         ]);
  6850.     }
  6851.     /**
  6852.      * @Route("/center/images/{url}", name="getCentresByImages", methods={"GET"})
  6853.      */
  6854.     public function getCentresByImages(string $urlPublicFunction $publicFunction): Response
  6855.     {
  6856.         return $publicFunction->replyWithFile('images/centres/'$url);
  6857.     }
  6858.     /**
  6859.      * @Route("centre/images/delete/", name="deleteCentresImage", methods={"POST"})
  6860.      */
  6861.     public function deleteCentresImage(Request $request): Response
  6862.     {
  6863.         $imageId $request->request->get("imageId");
  6864.         $imageGalerie $this->getDoctrine()->getRepository(CenterImage::class)
  6865.             ->find($imageId);
  6866.         $defaultImageUrls = ["by-default-1.jpeg""by-default-2.jpeg""by-default-3.jpeg"];
  6867.         if (!in_array($imageGalerie->getUrl(), $defaultImageUrls)) {
  6868.             $filePath $this->getParameter('kernel.project_dir') . "/assets/images/centres/" $imageGalerie->getUrl();
  6869.             if (file_exists($filePath)) {
  6870.                 unlink($filePath);
  6871.             }
  6872.         }
  6873.         $entityManager $this->getDoctrine()->getManager();
  6874.         $entityManager->remove($imageGalerie);
  6875.         $entityManager->flush();
  6876.         return $this->json(["status" => 200]);
  6877.     }
  6878.     /**
  6879.      * @Route("/center-update-description/{id}", name="setCentreDescription", methods={"PUT"})
  6880.      */
  6881.     public function setCentreDescription(Centre $centrePublicFunction $publicFunctionRequest $request)
  6882.     {
  6883.         $data json_decode($request->getContent(), true);
  6884.         if (!$data['token']) {
  6885.             return new Response(json_encode([
  6886.                 "message" => "Pas de token n'a été spécifié",
  6887.                 "status" => 401,
  6888.             ]), 401);
  6889.         }
  6890.         $entityManager $this->getDoctrine()->getManager();
  6891.         /** @var Token */
  6892.         $token $this->getDoctrine()
  6893.             ->getRepository(Token::class)
  6894.             ->findOneBy(['token' => $data['token'], 'id_audio' => $data['audio']]);
  6895.         if (!$token) {
  6896.             return new Response(json_encode([
  6897.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6898.                 "status" => 404,
  6899.             ]), 404);
  6900.         }
  6901.         // get token age
  6902.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6903.         // if the token if older than 7 days
  6904.         if ($dateDiff->7) {
  6905.             $entityManager->remove($token);
  6906.             $entityManager->flush();
  6907.             return $this->json([
  6908.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6909.                 'path' => 'src/Controller/AudioController.php',
  6910.                 "status" => 401,
  6911.             ], 401);
  6912.         }
  6913.         $date1 = new DateTime();
  6914.         $date2 = new DateTime();
  6915.         $entityManager $this->getDoctrine()->getManager();
  6916.         $centre->setDescription($data["description"]);
  6917.         $entityManager->flush();
  6918.         return $this->json([
  6919.             "id" => $centre->getId(),
  6920.             "status" => "200"
  6921.         ]);
  6922.     }
  6923.     /**
  6924.      * @Route("/audioschedule/centre", name="getScheduleCentre", methods={"GET","HEAD"})
  6925.      */
  6926.     public function getScheduleCentre(Request $requestPublicFunction $publicFunction)
  6927.     {
  6928.         $data $request->query->all();
  6929.         //dd($data);
  6930.         if (!$data['token']) {
  6931.             return new Response(json_encode([
  6932.                 "message" => "Pas de token n'a été spécifié",
  6933.                 "status" => 401,
  6934.             ]), 401);
  6935.         }
  6936.         $entityManager $this->getDoctrine()->getManager();
  6937.         /** @var Token */
  6938.         $token $this->getDoctrine()
  6939.             ->getRepository(Token::class)
  6940.             ->findOneBy(['token' => $data['token'], 'id_audio' => $data['audio']]);
  6941.         if (!$token) {
  6942.             return new Response(json_encode([
  6943.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6944.                 "status" => 404,
  6945.             ]), 404);
  6946.         }
  6947.         // get token age
  6948.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6949.         // if the token if older than 7 days
  6950.         if ($dateDiff->7) {
  6951.             $entityManager->remove($token);
  6952.             $entityManager->flush();
  6953.             return $this->json([
  6954.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6955.                 'path' => 'src/Controller/AudioController.php',
  6956.                 "status" => 401,
  6957.             ], 401);
  6958.         }
  6959.         $audio $this->getDoctrine()
  6960.             ->getRepository(Audio::class)
  6961.             ->find($data['audio']);
  6962.         $centre $this->getDoctrine()
  6963.             ->getRepository(Centre::class)
  6964.             ->find($data['center']);
  6965.         $date1 = new DateTime();
  6966.         $date2 = new DateTime();
  6967.         return $this->json([
  6968.             "schedule" => [
  6969.                 $publicFunction->calculSchedule($audio, new \DateTime(), $centre),
  6970.                 $publicFunction->calculSchedule($audio$date1->add(new DateInterval('P7D')), $centre),
  6971.                 $publicFunction->calculSchedule($audio$date2->add(new DateInterval('P14D')), $centre)
  6972.             ],
  6973.             "status" => "200"
  6974.         ]);
  6975.     }
  6976.     /**
  6977.      * @Route("/villes", name="getVilleCentre", methods={"GET","HEAD"})
  6978.      */
  6979.     public function getVilleCentre(Request $requestPublicFunction $publicFunction)
  6980.     {
  6981.         $data $request->query->all();
  6982.         //dd($data);
  6983.         $villes $this->getDoctrine()
  6984.             ->getRepository(Ville::class)
  6985.             ->findAll();
  6986.         $getVilles array_map(function ($ville) {
  6987.             return [
  6988.                 "id" => $ville->getId(),
  6989.                 "nom" => $ville->getNom(),
  6990.                 "slug" => $ville->getSlug(),
  6991.             ];
  6992.         }, $villes);
  6993.         return $this->json([
  6994.             "villes" => $getVilles,
  6995.             "status" => "200"
  6996.         ]);
  6997.     }
  6998.     /**
  6999.      * @Route("/assets/pdf/{filename}", name="download_pdf", methods={"GET"})
  7000.      */
  7001.     public function downloadPdf(string $filename): Response
  7002.     {
  7003.         $filePath '../assets/pdf/' $filename;
  7004.         if (!file_exists($filePath)) {
  7005.             return new Response('File not found.'Response::HTTP_NOT_FOUND);
  7006.         }
  7007.         return new BinaryFileResponse($filePath);
  7008.     }
  7009.     /**
  7010.      * @Route("/checkphoneclient", name="checkPhoneClient", methods={"GET","HEAD"})
  7011.      */
  7012.     public function checkPhoneClient(Request $requestPublicFunction $publicFunction)
  7013.     {
  7014.         $clientPhoneTest $this->getDoctrine()
  7015.             ->getRepository(Client::class)
  7016.             ->findOneBy(['phone' => $request->query->get('phone')]);
  7017.         if ($clientPhoneTest) {
  7018.             return $this->json([
  7019.                 'message' => 'Ce numéro de téléphone est déjà attribué.',
  7020.                 'path' => 'src/Controller/ClientController.php',
  7021.                 "status" => 401,
  7022.             ], 200);
  7023.         }
  7024.         return $this->json([
  7025.             'message' => 'Le numéro n\'est pas utilisé.',
  7026.             "status" => 200,
  7027.         ]);
  7028.     }
  7029.     /**
  7030.      * @Route("/checkemailclient", name="checkEmailClient", methods={"GET","HEAD"})
  7031.      */
  7032.     public function checkEmailClient(Request $requestPublicFunction $publicFunction)
  7033.     {
  7034.         $clientMailTest $this->getDoctrine()
  7035.             ->getRepository(Client::class)
  7036.             ->findOneBy(['mail' => $request->query->get('mail')]);
  7037.         if ($clientMailTest) {
  7038.             return $this->json([
  7039.                 'message' => 'Ce mail est déjà attribué.',
  7040.                 'path' => 'src/Controller/ClientController.php',
  7041.                 "status" => 401,
  7042.             ], 200);
  7043.         }
  7044.         return $this->json([
  7045.             'message' => 'Le mail n\'est pas utilisé.',
  7046.             "status" => 200,
  7047.         ]);
  7048.     }
  7049.     /**
  7050.      * @Route("/audioprothesiste/{ville}/{codePostal}/{nomDuCentre}/prise-de-rdv/{id}", name="getCentreByDetails", methods={"GET","HEAD"})
  7051.      */
  7052.     public function getCentreByDetails(string $villestring $codePostalstring $nomDuCentreint $idPublicFunction $publicFunctionRequest $request): Response
  7053.     {
  7054.         // Récupération du centre par ville, code postal et nom
  7055.         $centre $this->getDoctrine()->getRepository(Centre::class)->find($id);
  7056.         if (!$centre) {
  7057.             return new Response(json_encode([
  7058.                 'message' => 'Error, no centre found for these details.',
  7059.                 'path' => 'src/Controller/CentreController.php',
  7060.             ]), 404);
  7061.         }
  7062.         /** @var CentrePrestation[]*/
  7063.         $prestations $this->getDoctrine()->getRepository(CentrePrestation::class)
  7064.             ->findBy(array('id_centre' => $centre->getId()));
  7065.         $resultPrestation = new ArrayCollection();
  7066.         foreach ($prestations as $prestation) {
  7067.             $resultPrestation->add([
  7068.                 "id" => $prestation->getIdPrestation()->getId(),
  7069.                 "titre" => $prestation->getIdPrestation()->getLibelle(),
  7070.             ]);
  7071.         }
  7072.         /** @var CentreMutuelle[]*/
  7073.         $mutuelles $this->getDoctrine()->getRepository(CentreMutuelle::class)
  7074.             ->findBy(array('id_centre' => $centre->getId()));
  7075.         $resultMutuelle = new ArrayCollection();
  7076.         foreach ($mutuelles as $mutuelle) {
  7077.             $resultMutuelle->add([
  7078.                 "id" => $mutuelle->getIdMutuelle()->getId(),
  7079.                 "titre" => $mutuelle->getIdMutuelle()->getLibelle(),
  7080.             ]);
  7081.         }
  7082.         /** @var CentreTier[]*/
  7083.         $tiers $this->getDoctrine()->getRepository(CentreTier::class)
  7084.             ->findBy(array('id_centre' => $centre->getId()));
  7085.         $resultTier = new ArrayCollection();
  7086.         foreach ($tiers as $tier) {
  7087.             $resultTier->add([
  7088.                 "id" => $tier->getIdTier()->getId(),
  7089.                 "titre" => $tier->getIdTier()->getLibelle(),
  7090.             ]);
  7091.         }
  7092.         /** @var AudioCentre[] */
  7093.         $liaisons $this->getDoctrine()->getRepository(AudioCentre::class)
  7094.             ->findBy(array('id_centre' => $centre'isConfirmed' => true));
  7095.         $resultAudio = new ArrayCollection();
  7096.         foreach ($liaisons as $liaison) {
  7097.             /** @var Audio */
  7098.             $audio $this->getDoctrine()->getRepository(Audio::class)
  7099.                 ->findOneBy(array('id' => $liaison->getIdAudio()));
  7100.             // Motifs
  7101.             /** @var AudioMotif[] */
  7102.             $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  7103.                 ->findBy(array('id_audio' => $liaison->getIdAudio()));
  7104.             // will test whether or not the audio has the necessery motif to be added
  7105.             $resultMotif = new ArrayCollection();
  7106.             foreach ($motifs as $motif) {
  7107.                 // ignore deleted motif
  7108.                 if (!$motif->getIsDeleted() && $motif->getType() !== 2)
  7109.                     $resultMotif->add([
  7110.                         "id" => $motif->getIdMotif()->getId(),
  7111.                         "titre" => $motif->getIdMotif()->getTitre(),
  7112.                         "consigne" => $motif->getConsigne(),
  7113.                         "duration" => $motif->getDuration(),
  7114.                     ]);
  7115.             }
  7116.             // Specialities
  7117.             /** @var AudioSpecialite[] */
  7118.             $specialities $this->getDoctrine()->getRepository(AudioSpecialite::class)
  7119.                 ->findBy(array('id_audio' => $liaison->getIdAudio()));
  7120.             //speciality filter
  7121.             $resultSpeciality = new ArrayCollection();
  7122.             foreach ($specialities as $speciality) {
  7123.                 if ($speciality->getIdSpecialite() !== null) {
  7124.                     $resultSpeciality->add([
  7125.                         "id" => $speciality->getIdSpecialite()->getId(),
  7126.                         "titre" => $speciality->getIdSpecialite()->getLibelle(),
  7127.                     ]);
  7128.                 }
  7129.             }
  7130.             //schedule
  7131.             $date = new DateTime();
  7132.             //add audio in the result 
  7133.             if ($centre->getHoraire() == null || $centre->getHoraire() == []) continue;
  7134.             /** @var Rdv[] */
  7135.             $audioRdvs $this->getDoctrine()->getRepository(Rdv::class)
  7136.                 ->findAllReviewsAudio($audio->getId());
  7137.             $resultAudio->add([
  7138.                 "id" => $audio->getId(),
  7139.                 "civilite" => $audio->getCivilite(),
  7140.                 "name" => $audio->getName(),
  7141.                 "lastname" => $audio->getLastname(),
  7142.                 "birthdate" => $audio->getBirthdate(),
  7143.                 "mail" => $audio->getMail(),
  7144.                 "phone" => $audio->getPhone(),
  7145.                 "adeli" => $audio->getAdeli(),
  7146.                 "pin" => $audio->getPin(),
  7147.                 "description" => $audio->getDescription(),
  7148.                 "imgUrl" => $audio->getImgUrl(),
  7149.                 "averageRating" => $publicFunction->calculateRating($audioRdvs),
  7150.                 "nbrReview" => count($audioRdvs),
  7151.                 "motifs" => $resultMotif->toArray(),
  7152.                 "specialities" => $resultSpeciality->toArray(),
  7153.                 "schedule" => [
  7154.                     $publicFunction->calculSchedule($audio, new \DateTime(), $centre),
  7155.                     $publicFunction->calculSchedule($audio$date->add(new DateInterval('P7D')), $centre),
  7156.                     $publicFunction->calculSchedule($audio$date->add(new DateInterval('P14D')), $centre)
  7157.                 ],
  7158.             ]);
  7159.         }
  7160.         /** @var AccessCentre*/
  7161.         $accessCentre $this->getDoctrine()->getRepository(AccessCentre::class)
  7162.             ->findOneBy(array('id_centre' => $centre->getId()));
  7163.         if (!$accessCentre) {
  7164.             $tram = [];
  7165.             $rer = [];
  7166.             $metro = [];
  7167.             $bus = [];
  7168.             $parking = [];
  7169.             $pp = [];
  7170.             $other = [];
  7171.         } else {
  7172.             $metroIDs json_decode($accessCentre->getMetro(), true);
  7173.             $metroNames = array();
  7174.             if ($metroIDs) {
  7175.                 foreach ($metroIDs as $key => $stationID) {
  7176.                     $station $this->getDoctrine()->getRepository(Station::class)->find($stationID);
  7177.                     if ($station) {
  7178.                         $metroNames[$key] = $station->getName();
  7179.                     } else {
  7180.                         $metroNames[$key] = "Station Not Found";
  7181.                     }
  7182.                 }
  7183.             }
  7184.             $tram $accessCentre->getTram();
  7185.             $rer $accessCentre->getRer();
  7186.             $metro $metroNames;
  7187.             $bus $accessCentre->getBus();
  7188.             $parking $accessCentre->getParkingPublic();
  7189.             $pp $accessCentre->getParkingPrivate();
  7190.             $other $accessCentre->getOther();
  7191.         }
  7192.         /** @var Rdv[] */
  7193.         $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  7194.             ->findAllReviewsCentre($centre->getId());
  7195.         // Comment
  7196.         /** @var Rdv[] */
  7197.         $rdvs $this->getDoctrine()->getRepository(Rdv::class)
  7198.             ->findBy(array('id_centre' => $centre));
  7199.         $comments = [];
  7200.         foreach ($rdvs as $rdv)
  7201.             if ($rdv->getComment() && $rdv->getReview() && $rdv->getIdClient())
  7202.                 array_push($comments, [
  7203.                     "id" => $rdv->getIdClient()->getId(),
  7204.                     "name" => $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname()[0] . ".",
  7205.                     "comment" => $rdv->getComment(),
  7206.                     "isMale" => $rdv->getIdClient()->getCivilite() == "Monsieur",
  7207.                     "review" => $rdv->getReview(),
  7208.                 ]);
  7209.         $audioCentre $this->getDoctrine()->getRepository(AudioCentre::class)
  7210.             ->findOneBy(['id_centre' => $centre->getId()]);
  7211.         $audio $this->getDoctrine()->getRepository(Audio::class)
  7212.             ->findOneBy(['id' => $audioCentre->getIdAudio()]);
  7213.         //$doctor = $audio->serialize();
  7214.         return new Response(json_encode([
  7215.             "id" => $centre->getId(),
  7216.             "audio_id" => $centre->getIdGerant()->getId(),
  7217.             "name" => $centre->getName(),
  7218.             "imgUrl" => $centre->getImgUrl(),
  7219.             "isRdvDomicile" => $centre->getIsRdvDomicile(),
  7220.             "address" => $centre->getAddress(),
  7221.             "numero" => $centre->getNumero(),
  7222.             "voie" => $centre->getVoie(),
  7223.             "rue" => $centre->getRue(),
  7224.             "description" => $centre->getDescription(),
  7225.             "postale" => $centre->getPostale(),
  7226.             "city" => $centre->getCity(),
  7227.             "finess" => $centre->getFiness(),
  7228.             "siret" => $centre->getSiret(),
  7229.             "website" => $centre->getWebsite(),
  7230.             "phone" => $centre->getPhone(),
  7231.             "isHandicap" => $centre->getIsHandicap(),
  7232.             "longitude" => $centre->getLongitude(),
  7233.             "latitude" => $centre->getLatitude(),
  7234.             "averageRating" => $publicFunction->calculateRating($centreRdvs),
  7235.             "nbrReview" => count($centreRdvs),
  7236.             "tram" => $tram,
  7237.             "rer" => $rer,
  7238.             "metro" => $metro,
  7239.             "bus" => $bus,
  7240.             "parking" => $parking,
  7241.             "parkingPrivate" => $pp,
  7242.             "other" => $other,
  7243.             "comments" => $comments,
  7244.             "mutuelles" => $resultMutuelle->toArray(),
  7245.             "prestations" => $resultPrestation->toArray(),
  7246.             "tiers" => $resultTier->toArray(),
  7247.             "audio" => $resultAudio->toArray(),
  7248.             "schedule" => $centre->getHoraire(),
  7249.             //"doctor" => $doctor,
  7250.             "status" => 200,
  7251.         ]));
  7252.     }
  7253.     /**
  7254.      * @Route("/centres/generate-url-rdv", name="generateUrlRdvForAllCentres", methods={"POST"})
  7255.      */
  7256.     public function generateUrlRdvForAllCentres(): Response
  7257.     {
  7258.         $entityManager $this->getDoctrine()->getManager();
  7259.         $repository $this->getDoctrine()->getRepository(Centre::class);
  7260.         // Récupération de tous les centres
  7261.         $centres $repository->findAll();
  7262.         if (empty($centres)) {
  7263.             return new Response(json_encode([
  7264.                 'message' => 'No centres found in the database.',
  7265.             ]), 404, ['Content-Type' => 'application/json']);
  7266.         }
  7267.         $baseClient $_ENV['BASE_client'] ?? 'https://default-client-url.com';
  7268.         $updatedCentres = [];
  7269.         foreach ($centres as $centre) {
  7270.             // Récupération des informations nécessaires
  7271.             $id $centre->getId();
  7272.             $name $centre->getName();
  7273.             $city $centre->getCity();
  7274.             $postal $centre->getPostale();
  7275.             // Transformation en URL-friendly
  7276.             $nameSlug strtolower(preg_replace('/[^a-zA-Z0-9]+/''-'trim($name)));
  7277.             $citySlug strtolower(preg_replace('/[^a-zA-Z0-9]+/''-'trim($city)));
  7278.             // Construction de l'URL
  7279.             $urlRdv "{$baseClient}audioprothesiste/{$citySlug}/{$postal}/{$nameSlug}/prise-de-rdvaudioprothesiste-rapide/{$id}";
  7280.             // Mise à jour si l'URL est différente ou inexistante
  7281.             if (!$centre->getUrlRdv() || $centre->getUrlRdv() !== $urlRdv) {
  7282.                 $centre->setUrlRdv($urlRdv);
  7283.                 $entityManager->persist($centre);
  7284.                 $updatedCentres[] = $centre->getId(); // Ajoute l'ID des centres mis à jour
  7285.             }
  7286.         }
  7287.         // Sauvegarde des changements
  7288.         $entityManager->flush();
  7289.         // Retourne une réponse avec les centres mis à jour
  7290.         return new Response(json_encode([
  7291.             'message' => count($updatedCentres) . ' centres updated.',
  7292.             'updatedCentres' => $updatedCentres,
  7293.         ]), 200, ['Content-Type' => 'application/json']);
  7294.     }
  7295.     /**
  7296.      * @Route("/getlogin", name="getAssetsImage", methods={"GET"})
  7297.      */
  7298.     public function getAssetsImage(PublicFunction $publicFunction): Response
  7299.     {
  7300.         return $publicFunction->replyWithFile('images/'"login.png");
  7301.     }
  7302.     /**
  7303.      * @Route("/getloginImg", name="getAssetsImages", methods={"GET"})
  7304.      */
  7305.     public function getAssetsImages(PublicFunction $publicFunction): Response
  7306.     {
  7307.         return $publicFunction->replyWithFile('images/'"Logoblanc.png");
  7308.     }
  7309.     /**
  7310.      * @Route("/getloginImgpdf", name="getAssetsImagespdf", methods={"GET"})
  7311.      */
  7312.     public function getAssetsImagespdf(PublicFunction $publicFunction): Response
  7313.     {
  7314.         return $publicFunction->replyWithFile('images/'"pdflog.png");
  7315.     }
  7316.     /**
  7317.      * @Route("/send-password-email/{audio}", name="send-password-email-audio")
  7318.      */
  7319.     public function sendPassworEmail(Request $requestAudio $audioPublicFunction $publicFunction)
  7320.     {
  7321.         $randomPassword substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 08);
  7322.         $encodedPassword password_hash($randomPasswordPASSWORD_BCRYPT);
  7323.         $audio->setPassword($encodedPassword);
  7324.         $entityManager $this->getDoctrine()->getManager();
  7325.         $entityManager->persist($audio);
  7326.         $entityManager->flush();
  7327.         // send email notif to audio
  7328.         $params = [
  7329.             "nom" => $audio->getName(),
  7330.             "url" => $_ENV['BASE_logiciel'],
  7331.             "password" => $randomPassword,
  7332.             "email" => $audio->getMail(),
  7333.         ];
  7334.         $publicFunction->sendEmail($params$audio->getMail(), "Audioprothésiste""Bienvenue chez MyAudio, complétez vos informations"201);
  7335.         $referer $request->headers->get('referer');
  7336.         if (!$referer) {
  7337.             return $this->redirectToRoute('easyadmin', [
  7338.                 'controller' => 'CentreCrudController',
  7339.                 'action' => 'index',
  7340.             ]);
  7341.         }
  7342.         $this->addFlash('success'"L'audioprothésiste a bien reçu les mails d'activation et de génération de son compte MyAudio Pro.");
  7343.         return $this->redirect($referer);
  7344.     }
  7345.     private function getPostalCodes($entity): string
  7346. {
  7347.     $latitude $entity->getLatitude();
  7348.     $longitude $entity->getLongitude();
  7349.     $radius $entity->getZoneKm();
  7350.     if (empty($radius)) {
  7351.         return "zone de km est pas fournie ou manquante";
  7352.     }
  7353.     $postals $this->regionDepartmentRepository->findPostalsWithinRadius($latitude$longitude$radius);
  7354.     $postalCodes array_values(array_unique(array_column($postals'code_postal')));
  7355.     return implode(', '$postalCodes); 
  7356. }
  7357. private function getPostalCodesMarket($entity): array
  7358. {
  7359.     $latitude $entity->getLatitude();
  7360.     $longitude $entity->getLongitude();
  7361.     $radius $entity->getZoneKm();
  7362.     if (empty($radius)) {
  7363.         return []; 
  7364.     }
  7365.     $postals $this->regionDepartmentRepository->findPostalsWithinRadius($latitude$longitude$radius);
  7366.     $postalCodes array_values(array_unique(array_column($postals'code_postal')));
  7367.     return $postalCodes;  
  7368. }
  7369.   /**
  7370.  * @Route("/admin/cancel-subscription", name="admin_cancel_subscription", methods={"POST"})
  7371.  */
  7372. public function cancelSubscription(Request $request,PublicFunction $publicFunction)
  7373. {
  7374.     $data json_decode($request->getContent(), true);
  7375.     $id $data['id'] ?? null;
  7376.     $motif $data['motif'] ?? null;
  7377.     $status $data['status'] ?? null;
  7378.     $commentaire $data['commentaire'] ?? null;
  7379.     $entityManager $this->getDoctrine()->getManager();
  7380.     $center $entityManager->getRepository(Centre::class)->find($id);
  7381.     if (!$center) {
  7382.         return $this->json(['message' => 'Centre introuvable.'], 404);
  7383.     }
  7384.     if ($status === "blocked") {
  7385.         $existingRecord $entityManager->getRepository(CancellationRecord::class)
  7386.             ->findOneBy(['centre' => $center'status' => 'blocked']);
  7387.         if ($existingRecord) {
  7388.             $existingRecord->setMotif($motif);
  7389.             $existingRecord->setComment($commentaire);
  7390.             $existingRecord->setCreatedAt(new \DateTimeImmutable());
  7391.             $entityManager->flush();
  7392.             return $this->json([
  7393.                 'message' => 'Le centre était déjà bloqué. Les informations ont été mises à jour.',
  7394.                 'status' => 'updated'
  7395.             ]);
  7396.         }
  7397.         $cancellationRecord = new CancellationRecord();
  7398.         $cancellationRecord->setMotif($motif);
  7399.         $cancellationRecord->setComment($commentaire);
  7400.         $cancellationRecord->setCentre($center);
  7401.         $cancellationRecord->setStatus($status);
  7402.         $cancellationRecord->setCreatedAt(new \DateTimeImmutable());
  7403.         $center->setIsBlocked(true);
  7404.         $center->setIsValid(false);
  7405.         $entityManager->persist($cancellationRecord);
  7406.         $entityManager->persist($center);
  7407.         $entityManager->flush();
  7408.         return $this->json(['message' => 'Centre bloqué avec succès.''status' => 'success']);
  7409.     }
  7410. try {
  7411.      $privateKey $_ENV['APP_ENV'] === 'dev'
  7412.             $_ENV['STRIPE_SECRET_KEY_TEST']
  7413.             : $_ENV['STRIPE_SECRET_KEY_LIVE'];
  7414.         \Stripe\Stripe::setApiKey($privateKey);
  7415.         $subscription $entityManager->getRepository(Subscription::class)
  7416.             ->findOneBy(['audio' => $center->getIdGerant()]);
  7417.     
  7418.     if ($subscription) {
  7419.         \Stripe\Subscription::update($subscription->getStripeSubscriptionId(), [
  7420.             'metadata' => [
  7421.                 'cancellation_reason' => $motif,
  7422.                 'comment' => $commentaire,
  7423.             ]
  7424.         ]);
  7425.         \Stripe\Subscription::retrieve($subscription->getStripeSubscriptionId())->cancel();
  7426.     }
  7427. } catch (\Exception $e) {
  7428.     
  7429.     $this->addFlash('warning''Stripe non annulé : ' $e->getMessage());
  7430. }
  7431. $center->setIsResilied(true);
  7432. $center->setIsValid(false);
  7433. $entityManager->persist($center);
  7434. $entityManager->flush();
  7435. $params = [
  7436.     "fullName" => $center->getIdGerant()->getName() . " " $center->getIdGerant()->getLastname(),
  7437.     "date" => (new \DateTime())->format('d/m/Y'),
  7438. ];
  7439. $publicFunction->sendEmail(
  7440.     $params,
  7441.     $center->getIdGerant()->getMail(),
  7442.     "Audioprothésiste",
  7443.     "Confirmation de la résiliation de votre abonnement",
  7444.     227
  7445. );
  7446. return $this->json([
  7447.     'message' => 'L’abonnement a été résilié avec succès',
  7448.     'status' => 'partial_success'
  7449. ]);
  7450. }
  7451. }