src/Controller/CentreController.php line 804

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