src/Controller/RdvController.php line 8833

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use DateTime;
  4. use DateInterval;
  5. use DateTimeZone;
  6. use Dompdf\Dompdf;
  7. use App\Entity\Rdv;
  8. use Dompdf\Options;
  9. use App\Entity\Lieu;
  10. use App\Entity\Audio;
  11. use App\Entity\Motif;
  12. use App\Entity\Referral;
  13. use App\Entity\Token;
  14. use Twig\Environment;
  15. use App\Entity\Centre;
  16. use App\Entity\Client;
  17. use \IntlDateFormatter;
  18. use App\Entity\CallLog;
  19. use App\Entity\EtatRdv;
  20. use App\Entity\LeadRdv;
  21. use App\Entity\Proches;
  22. use App\Entity\LieuTier;
  23. use App\Entity\RdvEvent;
  24. use App\Entity\AudioMotif;
  25. use App\Entity\CentreTier;
  26. use App\Entity\ClientTemp;
  27. use App\Entity\LeadStatus;
  28. use App\Entity\Remplacant;
  29. use App\Entity\TestClient;
  30. use App\Entity\AudioCentre;
  31. use App\Service\SmsHandler;
  32. use App\Entity\AccessCentre;
  33. use App\Entity\ClientStatus;
  34. use Psr\Log\LoggerInterface;
  35. use App\Entity\ClientBlocked;
  36. use App\Entity\CentreMutuelle;
  37. use App\Entity\LieuPrestation;
  38. use App\Entity\AudioSpecialite;
  39. use App\Entity\CallInteraction;
  40. use App\Service\PublicFunction;
  41. use App\Entity\CentrePrestation;
  42. use App\Entity\RegionDepartment;
  43. use App\Repository\RdvRepository;
  44. use Symfony\Component\Mime\Email;
  45. use App\Entity\Device\ClientDevice;
  46. use App\Entity\Notification\RdvSms;
  47. use App\Service\Lead\TwilioService;
  48. use App\Service\Lead\WhatsappService;
  49. use App\Entity\SynchronisationSetting;
  50. use App\Service\Lead\SynthflowService;
  51. use App\Service\Lead\ElevenLabsService;
  52. use Doctrine\ORM\EntityManagerInterface;
  53. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  54. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  55. use Symfony\Contracts\Cache\ItemInterface;
  56. use App\Service\Cosium\ClientCosiumService;
  57. use App\Service\Notification\RdvSmsService;
  58. use App\Entity\SpecificSubscription;
  59. use Symfony\Contracts\Cache\CacheInterface;
  60. use App\Entity\Synchronisation\CosiumCenter;
  61. use App\Service\Lead\AppointmentCallService;
  62. use Symfony\Component\Filesystem\Filesystem;
  63. use Symfony\Component\HttpFoundation\Request;
  64. use Symfony\Component\Mailer\MailerInterface;
  65. use Symfony\Component\HttpFoundation\Response;
  66. use Symfony\Component\Routing\Annotation\Route;
  67. use Doctrine\Common\Collections\ArrayCollection;
  68. use App\EasyAdmin\Controller\DashboardController;
  69. use Symfony\Component\HttpKernel\KernelInterface;
  70. use Symfony\Component\HttpFoundation\JsonResponse;
  71. use App\EasyAdmin\Controller\LeadRdvCrudController;
  72. use App\Service\AdsCompany\RepresentativeCdaService;
  73. use App\Entity\Synchronisation\SynchronisationCosium;
  74. use App\Service\GoogleCalendar\GoogleCalendarService;
  75. use App\EasyAdmin\Controller\RdvMyAudioCrudController;
  76. use App\Service\Notification\EmailNotificationService;
  77. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  78. use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
  79. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  80. use Symfony\Component\Mercure\PublisherInterface;
  81. use Symfony\Component\Mercure\Update;
  82. use App\Service\Mercure\MercureService;
  83. class RdvController extends AbstractController
  84. {
  85.     private $emailNotificationService;
  86.     private $clientCosiumService;
  87.     private $rdvRepository;
  88.     private $entityManager;
  89.     private $cache;
  90.     private $mercure;
  91.     private $twig;
  92.     private AdminUrlGenerator $adminUrlGenerator;
  93.     private WhatsappService $whatsapp;
  94.     private LoggerInterface $logger;  // Service de journalisation
  95.     private RdvRepository $rdvRepo;
  96.     public function __construct(CacheInterface $cacheEntityManagerInterface $entityManagerRdvRepository $rdvRepoEmailNotificationService $emailNotificationServiceClientCosiumService $clientCosiumServiceRdvRepository $rdvRepositoryEnvironment $twigAdminUrlGenerator $adminUrlGeneratorWhatsappService $whatsappLoggerInterface $logger,MercureService $mercure)
  97.     {
  98.         $this->entityManager $entityManager;
  99.         $this->emailNotificationService $emailNotificationService;
  100.         $this->clientCosiumService $clientCosiumService;
  101.         $this->rdvRepository $rdvRepository;
  102.         $this->cache $cache;
  103.         $this->twig $twig;
  104.         $this->adminUrlGenerator $adminUrlGenerator;
  105.         $this->whatsapp $whatsapp;
  106.         $this->logger $logger;
  107.         $this->rdvRepo $rdvRepo;
  108.         $this->mercure $mercure;
  109.     }
  110.     /**
  111.      * @Route("/rdv/{id}", name="deleteRdvByID", methods={"DELETE"})
  112.      */
  113.     public function deleteRdvByID(Request $requestRdv $rdvGoogleCalendarService $googleCalendar)
  114.     {
  115.         if (!$request->query->get('token')) {
  116.             return new Response(json_encode([
  117.                 "message" => "Pas de token n'a été spécifié",
  118.                 "status" => 401,
  119.             ]), 401);
  120.         }
  121.         $entityManager $this->getDoctrine()->getManager();
  122.         /** @var Token */
  123.         $token $this->getDoctrine()
  124.             ->getRepository(Token::class)
  125.             ->findOneBy(['token' => $request->query->get('token')]);
  126.         if (!$token) {
  127.             return new Response(json_encode([
  128.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  129.                 "status" => 404,
  130.             ]), 404);
  131.         }
  132.         // get token age
  133.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  134.         // if the token if older than 7 days
  135.         if ($dateDiff->7) {
  136.             $entityManager->remove($token);
  137.             $entityManager->flush();
  138.             return $this->json([
  139.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  140.                 'path' => 'src/Controller/ClientController.php',
  141.                 "status" => 401,
  142.             ], 401);
  143.         }
  144.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  145.             return new Response(json_encode([
  146.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  147.                 "status" => 404,
  148.             ]), 404);
  149.         }
  150.         $entityManager->remove($rdv);
  151.         $entityManager->flush();
  152.         return new Response(json_encode(([
  153.             'message' => "Rdv has been successfully deleted",
  154.             "status" => 200,
  155.         ])));
  156.     }
  157.     /**
  158.      * @Route("/rdv/{id}", name="getRdvByID", methods={"GET","HEAD"})
  159.      */
  160.     public function getRdvByID(Request $requestRdv $rdvPublicFunction $publicFunction)
  161.     {
  162.         if (!$request->query->get('token')) {
  163.             return new Response(json_encode([
  164.                 "message" => "Pas de token n'a été spécifié",
  165.                 "status" => 401,
  166.             ]), 401);
  167.         }
  168.         $entityManager $this->getDoctrine()->getManager();
  169.         /** @var Token */
  170.         $token $this->getDoctrine()
  171.             ->getRepository(Token::class)
  172.             ->findOneBy(['token' => $request->query->get('token')]);
  173.         if (!$token) {
  174.             return new Response(json_encode([
  175.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  176.                 "status" => 404,
  177.             ]), 404);
  178.         }
  179.         // get token age
  180.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  181.         // if the token if older than 7 days
  182.         if ($dateDiff->7) {
  183.             $entityManager->remove($token);
  184.             $entityManager->flush();
  185.             return $this->json([
  186.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  187.                 'path' => 'src/Controller/ClientController.php',
  188.                 "status" => 401,
  189.             ], 401);
  190.         }
  191.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  192.             return new Response(json_encode([
  193.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  194.                 "status" => 404,
  195.             ]), 404);
  196.         }
  197.         /** @var AudioCentre */
  198.         $liaison $this->getDoctrine()->getRepository(AudioCentre::class)
  199.             ->findOneBy(array('id_audio' => $rdv->getIdAudio(), 'id_centre' => $rdv->getIdCentre(), 'isConfirmed' => true));
  200.         // Motif filter
  201.         /** @var AudioMotif[] */
  202.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  203.             ->findBy(array('id_audio' => $rdv->getIdAudio(), 'id_motif' => $rdv->getIdMotif()));
  204.         $resultMotif = new ArrayCollection();
  205.         foreach ($motifs as $motif) {
  206.             $resultMotif->add([
  207.                 "id" => $motif->getIdMotif()->getId(),
  208.                 "titre" => $motif->getIdMotif()->getTitre(),
  209.                 "consigne" => $motif->getConsigne(),
  210.                 "duration" => $motif->getDuration(),
  211.             ]);
  212.         }
  213.         // Specialities
  214.         /** @var AudioSpecialite[] */
  215.         $specialities $this->getDoctrine()->getRepository(AudioSpecialite::class)
  216.             ->findBy(array('id_audio' => $rdv->getIdAudio()));
  217.         $resultSpeciality = new ArrayCollection();
  218.         foreach ($specialities as $speciality) {
  219.             $resultSpeciality->add([
  220.                 "id" => $speciality->getIdSpecialite()->getId(),
  221.                 "titre" => $speciality->getIdSpecialite()->getLibelle(),
  222.             ]);
  223.         }
  224.         if ($rdv->getIdCentre())
  225.         /** @var AccessCentre*/
  226.         {
  227.             $accessCentre $this->getDoctrine()->getRepository(AccessCentre::class)
  228.                 ->findOneBy(array('id_centre' => $rdv->getIdCentre()));
  229.         } else
  230.         /** @var AccessCentre*/
  231.         {
  232.             $accessCentre $this->getDoctrine()->getRepository(AccessCentre::class)
  233.                 ->findOneBy(array('id_lieu' => $rdv->getIdLieu()));
  234.         }
  235.         if ($rdv->getIdCentre())
  236.         /** @var CentrePrestation[]*/
  237.         {
  238.             $prestations $this->getDoctrine()->getRepository(CentrePrestation::class)
  239.                 ->findBy(array('id_centre' => $liaison->getIdCentre()->getId()));
  240.         } else
  241.         /** @var LieuPrestation[]*/
  242.         {
  243.             $prestations $this->getDoctrine()->getRepository(LieuPrestation::class)
  244.                 ->findBy(array('id_lieu' => $rdv->getIdLieu()));
  245.         }
  246.         $resultPrestation = new ArrayCollection();
  247.         foreach ($prestations as $prestation) {
  248.             $resultPrestation->add([
  249.                 "id" => $prestation->getIdPrestation()->getId(),
  250.                 "titre" => $prestation->getIdPrestation()->getLibelle(),
  251.             ]);
  252.         }
  253.         $mutuelles $this->getDoctrine()->getRepository(CentreMutuelle::class)
  254.             ->findBy(array('id_centre' => $rdv->getIdCentre()));
  255.         $resultMutuelle = new ArrayCollection();
  256.         foreach ($mutuelles as $mutuelle) {
  257.             $resultMutuelle->add([
  258.                 "id" => $mutuelle->getIdMutuelle()->getId(),
  259.                 "titre" => $mutuelle->getIdMutuelle()->getLibelle(),
  260.             ]);
  261.         }
  262.         if ($rdv->getIdCentre())
  263.         /** @var CentreTier[]*/
  264.         {
  265.             $tiers $this->getDoctrine()->getRepository(CentreTier::class)
  266.                 ->findBy(array('id_centre' => $liaison->getIdCentre()->getId()));
  267.         } else
  268.         /** @var LieuTier[]*/
  269.         {
  270.             $tiers $this->getDoctrine()->getRepository(LieuTier::class)
  271.                 ->findBy(array('id_lieu' => $rdv->getIdLieu()));
  272.         }
  273.         $resultTier = new ArrayCollection();
  274.         foreach ($tiers as $tier) {
  275.             $resultTier->add([
  276.                 "id" => $tier->getIdTier()->getId(),
  277.                 "titre" => $tier->getIdTier()->getLibelle(),
  278.             ]);
  279.         }
  280.         $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  281.         /** @var Rdv[] */
  282.         $audioRdvs $this->getDoctrine()->getRepository(Rdv::class)
  283.             ->findAllReviewsAudio($rdv->getIdAudio()->getId());
  284.         /** @var Rdv[] */
  285.         $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  286.             ->findAllReviewsCentre($rdvCentre->getId());
  287.         // Comment
  288.         /** @var Rdv[] */
  289.         $rdvs $this->getDoctrine()->getRepository(Rdv::class)
  290.             ->findBy(array('id_audio' => $rdv->getIdAudio()));
  291.         $comments = [];
  292.         foreach ($rdvs as $rdv)
  293.             if ($rdv->getComment() && $rdv->getReview() && $rdv->getIdClient())
  294.                 array_push($comments, [
  295.                     "id" => $rdv->getIdClient()->getId(),
  296.                     "name" => $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname()[0] . ".",
  297.                     "comment" => $rdv->getComment(),
  298.                     "isMale" => $rdv->getIdClient()->getCivilite() == "Monsieur",
  299.                     "review" => $rdv->getReview(),
  300.                 ]);
  301.         return new Response(json_encode(([
  302.             "id" => $rdv->getId(),
  303.             "motif_id" => $rdv->getIdMotif()->getId(),
  304.             "motif_titre" => $rdv->getIdMotif()->getTitre(),
  305.             "audio_id" => $rdv->getIdAudio()->getId(),
  306.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  307.             "client_id" => $rdv->getIdClient()->getId(),
  308.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  309.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  310.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  311.             "etat_id" => $rdv->getIdEtat()->getId(),
  312.             "date" => $rdv->getDate(),
  313.             "comment" => $rdv->getComment(),
  314.             "review" => $rdv->getReview(),
  315.             "note" => $rdv->getNote(),
  316.             "testclient" => $rdv->getTestClient() ? [
  317.                 "result" => $rdv->getTestClient()->getResultTonal(),
  318.                 "date" => $rdv->getTestClient()->getDate(),
  319.                 "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  320.             ] : null,
  321.             "comments" => $comments,
  322.             "audio" => [
  323.                 "id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : $rdv->getIdAudio()->getId(),
  324.                 "civilite" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getCivilite() : $rdv->getIdAudio()->getCivilite(),
  325.                 "name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() : $rdv->getIdAudio()->getName(),
  326.                 "lastname" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getLastname(),
  327.                 "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  328.                 "mail" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getMail() : $rdv->getIdAudio()->getMail(),
  329.                 "phone" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getPhone() : $rdv->getIdAudio()->getPhone(),
  330.                 "adeli" => $rdv->getIdAudio()->getAdeli(),
  331.                 "pin" => $rdv->getIdAudio()->getPin(),
  332.                 "description" => $rdv->getIdAudio()->getDescription(),
  333.                 "averageRating" => $publicFunction->calculateRating($audioRdvs),
  334.                 "nbrReview" => count($audioRdvs),
  335.                 "motifs" => $resultMotif->toArray(),
  336.                 "specialities" => $resultSpeciality->toArray(),
  337.             ],
  338.             "centre" => [
  339.                 "id" => $rdvCentre->getId(),
  340.                 "audio_id" => $rdvCentre->getIdGerant()->getId(),
  341.                 "name" => $rdvCentre->getName(),
  342.                 "imgUrl" => $rdvCentre->getImgUrl(),
  343.                 "isRdvDomicile" => $rdv->getIdCentre() ? $rdvCentre->getIsRdvDomicile() : $rdv->getIdAudio()->getIsRdvDomicileIndie(),
  344.                 "address" => $rdvCentre->getAddress(),
  345.                 "postale" => $rdvCentre->getPostale(),
  346.                 "city" => $rdvCentre->getCity(),
  347.                 "finess" => $rdvCentre->getFiness(),
  348.                 "siret" => $rdvCentre->getSiret(),
  349.                 "website" => $rdvCentre->getWebsite(),
  350.                 "phone" => $rdvCentre->getPhone(),
  351.                 "isHandicap" => $rdvCentre->getIsHandicap(),
  352.                 "longitude" => $rdvCentre->getLongitude(),
  353.                 "latitude" => $rdvCentre->getLatitude(),
  354.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  355.                 "nbrReview" => count($centreRdvs),
  356.                 "tram" => $accessCentre->getTram(),
  357.                 "rer" => $accessCentre->getRer(),
  358.                 "metro" => $accessCentre->getMetro(),
  359.                 "bus" => $accessCentre->getBus(),
  360.                 "parking" => $accessCentre->getParkingPublic(),
  361.                 "description" => $rdv->getIdCentre()->getDescription(),
  362.                 "parkingPrivate" => $accessCentre->getParkingPrivate(),
  363.                 "other" => $accessCentre->getOther(),
  364.                 "prestations" => $resultPrestation->toArray(),
  365.                 "mutuelles" => $resultMutuelle->toArray(),
  366.                 "tiers" => $resultTier->toArray(),
  367.                 "isLieu" => false,
  368.                 "schedule" => $rdv->getIdAudio()->getIsIndie() == false $rdv->getIdCentre()->getHoraire() : ($rdv->getIdLieu() ? $rdv->getIdLieu()->getHoraire() : $liaison->getHoraire()),
  369.             ],
  370.             "status" => 200,
  371.         ])));
  372.     }
  373.     /**
  374.      * @Route("/rdvs/client/{id}", name="getRdvsByClientID", methods={"GET","HEAD"})
  375.      */
  376.     public function getRdvsByClientID(Request $requestClient $clientPublicFunction $publicFunction)
  377.     {
  378.         if (!$request->query->get('token')) {
  379.             return new Response(json_encode([
  380.                 "message" => "Pas de token n'a été spécifié",
  381.                 "status" => 401,
  382.             ]), 401);
  383.         }
  384.         $entityManager $this->getDoctrine()->getManager();
  385.         /** @var Token */
  386.         $token $this->getDoctrine()
  387.             ->getRepository(Token::class)
  388.             ->findOneBy(['token' => $request->query->get('token')]);
  389.         if (!$token) {
  390.             return new Response(json_encode([
  391.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  392.                 "status" => 404,
  393.             ]), 404);
  394.         }
  395.         // get token age
  396.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  397.         // if the token if older than 7 days
  398.         if ($dateDiff->7) {
  399.             $entityManager->remove($token);
  400.             $entityManager->flush();
  401.             return $this->json([
  402.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  403.                 'path' => 'src/Controller/ClientController.php',
  404.                 "status" => 401,
  405.             ], 401);
  406.         }
  407.         if ($token->getIdClient()) {
  408.             if ($client != $token->getIdClient()) {
  409.                 return new Response(json_encode([
  410.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  411.                     "status" => 404,
  412.                 ]), 404);
  413.             }
  414.         } else if ($token->getIdAudio()) {
  415.             /** @var Token */
  416.             $token $this->getDoctrine()
  417.                 ->getRepository(Rdv::class)
  418.                 ->findOneBy(['id_client' => $client'id_audio' => $token->getIdAudio()]);
  419.             if ($client != $token->getIdClient()) {
  420.                 return new Response(json_encode([
  421.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  422.                     "status" => 404,
  423.                 ]), 404);
  424.             }
  425.         } else {
  426.             return new Response(json_encode([
  427.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  428.                 "status" => 404,
  429.             ]), 404);
  430.         }
  431.         if ($request->query->get('audio')) {
  432.             /** @var Rdv[] */
  433.             $rdvs $this->getDoctrine()
  434.                 ->getRepository(Rdv::class)
  435.                 ->findBy(['id_client' => $client->getId(), 'id_audio' => $token->getIdAudio()]);
  436.             $rdvResult = new ArrayCollection();
  437.         } else {
  438.             /** @var Rdv[] */
  439.             $rdvs $this->getDoctrine()
  440.                 ->getRepository(Rdv::class)
  441.                 ->findBy(['id_client' => $client->getId()]);
  442.             $rdvResult = new ArrayCollection();
  443.         }
  444.         if ($request->query->get('old')) {
  445.             $oldRdvResult = new ArrayCollection();
  446.         }
  447.         foreach ($rdvs as $rdv) {
  448.             if ($rdv->getIdEtat()->getId() != 1) {
  449.                 continue;
  450.             }
  451.             /** @var AudioMotif */
  452.             $audioMotif $this->getDoctrine()
  453.                 ->getRepository(AudioMotif::class)
  454.                 ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  455.             if (!$audioMotif) {
  456.                 continue;
  457.             }
  458.             $duration '';
  459.             if (is_null($rdv->getDuration())) {
  460.                 $duration $audioMotif->getDuration();
  461.             } else {
  462.                 $duration $rdv->getDuration();
  463.             }
  464.             $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  465.             /** @var Rdv[] */
  466.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  467.                 ->findAllReviewsCentre($rdvCentre->getId());
  468.             $rdvItem = [
  469.                 "id" => $rdv->getId(),
  470.                 "motif_id" => $rdv->getIdMotif()->getId(),
  471.                 "duration" => $duration,
  472.                 "color" => $audioMotif->getColor(),
  473.                 "audio_id" => $rdv->getIdAudio()->getId(),
  474.                 "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  475.                 "audio_name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() . " " $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  476.                 "client_id" => $rdv->getIdClient()->getId(),
  477.                 "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  478.                 "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  479.                 "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  480.                 "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  481.                 "testclient" => $rdv->getTestClient() ? [
  482.                     "result" => $rdv->getTestClient()->getResultTonal(),
  483.                     "date" => $rdv->getTestClient()->getDate(),
  484.                     "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  485.                 ] : null,
  486.                 "name" => $rdvCentre->getName(),
  487.                 "phone" => $rdvCentre->getPhone(),
  488.                 "imgUrl" => $rdvCentre->getImgUrl(),
  489.                 "address" => $rdvCentre->getAddress(),
  490.                 "postale" => $rdvCentre->getPostale(),
  491.                 "city" => $rdvCentre->getCity(),
  492.                 "etat_id" => $rdvCentre->getId(),
  493.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  494.                 "nbrReview" => count($centreRdvs),
  495.                 "acceptedCurrency" => "CB Chèque",
  496.                 "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  497.                 "note" => $rdv->getNote(),
  498.                 "comment" => $rdv->getComment(),
  499.                 "review" => $rdv->getReview(),
  500.             ];
  501.             if ($rdv->getDate() >= new DateTime()) {
  502.                 $rdvResult->add($rdvItem);
  503.             } else if ($request->query->get('old')) {
  504.                 $oldRdvResult->add($rdvItem);
  505.             }
  506.         }
  507.         if ($request->query->get('old')) {
  508.             if ($request->query->get('onlyOld')) {
  509.                 if (count($rdvResult) > || count($oldRdvResult) > 0) {
  510.                     return new Response(json_encode(([
  511.                         "oldRdv" => $oldRdvResult->toArray(),
  512.                         "status" => 200,
  513.                     ])));
  514.                 } else {
  515.                     return new Response(json_encode(([
  516.                         "message" => "Aucun rendez-vous n'a été trouvé!",
  517.                         "test" => "count:" count($rdvs),
  518.                         'path' => 'src/Controller/RdvController.php',
  519.                         "rdv" => array(),
  520.                         "oldRdv" => array(),
  521.                         "status" => 404,
  522.                     ])));
  523.                 }
  524.             } else {
  525.                 if (count($rdvResult) > || count($oldRdvResult) > 0) {
  526.                     return new Response(json_encode(([
  527.                         "rdv" => $rdvResult->toArray(),
  528.                         "oldRdv" => $oldRdvResult->toArray(),
  529.                         "status" => 200,
  530.                     ])));
  531.                 } else {
  532.                     return new Response(json_encode(([
  533.                         "message" => "Aucun rendez-vous n'a été trouvé!",
  534.                         "test" => "count:" count($rdvs),
  535.                         'path' => 'src/Controller/RdvController.php',
  536.                         "rdv" => array(),
  537.                         "oldRdv" => array(),
  538.                         "status" => 404,
  539.                     ])));
  540.                 }
  541.             }
  542.         } else {
  543.             if (count($rdvResult) > 0) {
  544.                 return new Response(json_encode(([
  545.                     "content" => $rdvResult->toArray(),
  546.                     "status" => 200,
  547.                 ])));
  548.             } else {
  549.                 return new Response(json_encode(([
  550.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  551.                     "test" => "count2:" count($rdvs),
  552.                     'path' => 'src/Controller/RdvController.php',
  553.                     "status" => 404,
  554.                 ])));
  555.             }
  556.         }
  557.     }
  558.     /**
  559.      * @Route("/rdvs/client/{id}/centre", name="getRdvsByClientIDForCentre", methods={"GET","HEAD"})
  560.      */
  561.     public function getRdvsByClientIDForCentre(Request $requestClient $clientPublicFunction $publicFunction)
  562.     {
  563.         if (!$request->query->get('token')) {
  564.             return new Response(json_encode([
  565.                 "message" => "Pas de token n'a été spécifié",
  566.                 "status" => 401,
  567.             ]), 401);
  568.         }
  569.         $entityManager $this->getDoctrine()->getManager();
  570.         /** @var Token */
  571.         $token $this->getDoctrine()
  572.             ->getRepository(Token::class)
  573.             ->findOneBy(['token' => $request->query->get('token')]);
  574.         if (!$token) {
  575.             return new Response(json_encode([
  576.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  577.                 "status" => 404,
  578.             ]), 404);
  579.         }
  580.         $audio $this->getDoctrine()
  581.             ->getRepository(Audio::class)
  582.             ->findOneBy(['id' => $request->query->get('audio')]);
  583.         $audioCentre $this->getDoctrine()
  584.             ->getRepository(AudioCentre::class)
  585.             ->findOneBy(['id_audio' => $audio]);
  586.         // get token age
  587.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  588.         // if the token if older than 7 days
  589.         if ($dateDiff->7) {
  590.             $entityManager->remove($token);
  591.             $entityManager->flush();
  592.             return $this->json([
  593.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  594.                 'path' => 'src/Controller/ClientController.php',
  595.                 "status" => 401,
  596.             ], 401);
  597.         }
  598.         if ($token->getIdClient()) {
  599.             if ($client != $token->getIdClient()) {
  600.                 return new Response(json_encode([
  601.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  602.                     "status" => 404,
  603.                 ]), 404);
  604.             }
  605.         } else if ($token->getIdAudio()) {
  606.             /** @var Token */
  607.             if ($token->getIdAudio() != $audio) {
  608.                 return new Response(json_encode([
  609.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  610.                     "status" => 404,
  611.                 ]), 404);
  612.             }
  613.         } else {
  614.             return new Response(json_encode([
  615.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  616.                 "status" => 404,
  617.             ]), 404);
  618.         }
  619.         if ($request->query->get('centre')) {
  620.             /** @var Rdv[] */
  621.             $rdvs $this->getDoctrine()
  622.                 ->getRepository(Rdv::class)
  623.                 ->findBy(['id_client' => $client->getId(), 'id_centre' => $audioCentre->getIdCentre()]);
  624.             $rdvResult = new ArrayCollection();
  625.         } else {
  626.             /** @var Rdv[] */
  627.             $rdvs $this->getDoctrine()
  628.                 ->getRepository(Rdv::class)
  629.                 ->findBy(['id_client' => $client->getId()]);
  630.             $rdvResult = new ArrayCollection();
  631.         }
  632.         if ($request->query->get('old')) {
  633.             $oldRdvResult = new ArrayCollection();
  634.         }
  635.         foreach ($rdvs as $rdv) {
  636.             /*if ($rdv->getIdEtat()->getId() != 1) {
  637.                 continue;
  638.             }*/
  639.             /** @var AudioMotif */
  640.             $audioMotif $this->getDoctrine()
  641.                 ->getRepository(AudioMotif::class)
  642.                 ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  643.             if (!$audioMotif) {
  644.                 continue;
  645.             }
  646.             $duration '';
  647.             if (is_null($rdv->getDuration())) {
  648.                 $duration $audioMotif->getDuration();
  649.             } else {
  650.                 $duration $rdv->getDuration();
  651.             }
  652.             $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  653.             /** @var Rdv[] */
  654.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  655.                 ->findAllReviewsCentre($rdvCentre->getId());
  656.             $rdvItem = [
  657.                 "id" => $rdv->getId(),
  658.                 "motif_id" => $rdv->getIdMotif()->getId(),
  659.                 "duration" => $duration,
  660.                 "color" => $audioMotif->getColor(),
  661.                 "audio_id" => $rdv->getIdAudio()->getId(),
  662.                 "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  663.                 "audio_name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() . " " $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  664.                 "client_id" => $rdv->getIdClient()->getId(),
  665.                 "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  666.                 "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  667.                 "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  668.                 "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  669.                 "testclient" => $rdv->getTestClient() ? [
  670.                     "result" => $rdv->getTestClient()->getResultTonal(),
  671.                     "date" => $rdv->getTestClient()->getDate(),
  672.                     "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  673.                 ] : null,
  674.                 "name" => $rdvCentre->getName(),
  675.                 "phone" => $rdvCentre->getPhone(),
  676.                 "imgUrl" => $rdvCentre->getImgUrl(),
  677.                 "address" => $rdvCentre->getAddress(),
  678.                 "postale" => $rdvCentre->getPostale(),
  679.                 "city" => $rdvCentre->getCity(),
  680.                 "etat_id" => $rdvCentre->getId(),
  681.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  682.                 "nbrReview" => count($centreRdvs),
  683.                 "acceptedCurrency" => "CB Chèque",
  684.                 "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  685.                 "note" => $rdv->getNote(),
  686.                 "comment" => $rdv->getComment(),
  687.                 "review" => $rdv->getReview(),
  688.                 "status" => $rdv->getIdEtat()->getLibelle()
  689.             ];
  690.             // dd(new DateTime());
  691.             if ($rdv->getDate() >= new DateTime()) {
  692.                 $rdvResult->add($rdvItem);
  693.             } else if ($request->query->get('old')) {
  694.                 $oldRdvResult->add($rdvItem);
  695.             }
  696.         }
  697.         if ($request->query->get('old')) {
  698.             if (count($rdvResult) > || count($oldRdvResult) > 0) {
  699.                 return new Response(json_encode(([
  700.                     "rdv" => $rdvResult->toArray(),
  701.                     "oldRdv" => $oldRdvResult->toArray(),
  702.                     "status" => 200,
  703.                 ])));
  704.             } else {
  705.                 return new Response(json_encode(([
  706.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  707.                     "test" => "count:" count($rdvs),
  708.                     'path' => 'src/Controller/RdvController.php',
  709.                     "status" => 404,
  710.                 ])), 404);
  711.             }
  712.         } else {
  713.             if (count($rdvResult) > 0) {
  714.                 return new Response(json_encode(([
  715.                     "content" => $rdvResult->toArray(),
  716.                     "status" => 200,
  717.                 ])));
  718.             } else {
  719.                 return new Response(json_encode(([
  720.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  721.                     "test" => "count2:" count($rdvs),
  722.                     'path' => 'src/Controller/RdvController.php',
  723.                     "status" => 404,
  724.                 ])));
  725.             }
  726.         }
  727.     }
  728.     /////// CRON
  729.     /**
  730.      * @Route("/confirmRdvSms", name="confirmRdvSms", methods={"GET","HEAD"})
  731.      */
  732.     public function confirmRdvSms(PublicFunction $publicFunction): Response
  733.     {
  734.         $date = new DateTime();
  735.         $minutes_to_add 30;
  736.         $date->add(new DateInterval('PT' $minutes_to_add 'M'));
  737.         $date->setTimezone(new DateTimeZone('Europe/Paris'));
  738.         $currentDate $date->format('Y-m-d H:i:00');
  739.         $toSend $this->getDoctrine()->getRepository(Rdv::class)
  740.             ->findRdvsIn10Mins($currentDate);
  741.         $entityManager $this->getDoctrine()->getManager();
  742.         $rdvResult = new ArrayCollection();
  743.         foreach ($toSend as $rdv) {
  744.             $date $rdv->getDate();
  745.             // $smsDate = $date->format('d-m-Y H:i');
  746.             //$client = $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  747.             //$sms = "Vous avez votre RDV du " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15) . ", taper 1 si vous confirmer votre arrivé au centre auditif ou 2 si vous avez un empêchement.";
  748.             // // $publicFunction->sendEmail("MyAudio <noreply@myaudio.fr>", $client->getMail(), "My Audio: Testing CRON", "<p>Testing Cron.</p>");
  749.             //$response = $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone(), 4);
  750.             //$another_response = explode(" | ", $response);
  751.             // $idSms = trim($another_response[2]);
  752.             // $rdv->setIdSms($idSms);
  753.             //$entityManager->persist($rdv);
  754.             // $entityManager->flush();
  755.         }
  756.         return new Response(json_encode([
  757.             // "test" => $idSms,
  758.             "currentDate" => $currentDate
  759.         ]));
  760.     }
  761.     /////// CRON 
  762.     /**
  763.      * @Route("/validateRdvSms", name="validateRdvSms", methods={"GET","HEAD"})
  764.      */
  765.     public function validateRdvSms(Request $requestPublicFunction $publicFunction): Response
  766.     {
  767.         $entityManager $this->getDoctrine()->getManager();
  768.         $smsId $_GET['smsID'];
  769.         $message $_GET['message'];
  770.         $callLog $this->getDoctrine()
  771.             ->getRepository(CallLog::class)
  772.             ->findOneBy(['smsId' => $smsId]);
  773.         if ($callLog) {
  774.             $callLog->setAnsweredAt(new \DateTimeImmutable());
  775.             $interaction = new CallInteraction;
  776.             $interaction->setCallLog($callLog);
  777.             try {
  778.                 if ($message == "1") {
  779.                     $interaction->setStep('equipment_status');
  780.                     $interaction->setResponse('réponse_reçue');
  781.                     $interaction->setTimestamp(new \DateTimeImmutable());
  782.                     $interaction->setAdditionalData(['digit' => '1''status' => 'en_essai']);
  783.                     $entityManager->persist($interaction);
  784.                     $sms "Merci pour votre réponse. Nous notons que vous êtes actuellement en période d'essai. Merci et bonne journée avec MyAudio";
  785.                     $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  786.                 } else if ($message == "2") {
  787.                     $interaction->setStep('equipment_status');
  788.                     $interaction->setResponse('réponse_reçue');
  789.                     $interaction->setTimestamp(new \DateTimeImmutable());
  790.                     $interaction->setAdditionalData(['digit' => '2''status' => 'finalise']);
  791.                     $entityManager->persist($interaction);
  792.                     $sms "Félicitations pour votre appareillage ! Nous sommes ravis que vous ayez finalisé cet achat important. Bonne journée avec My Audio.";
  793.                     $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  794.                 } else if ($message == "3") {
  795.                     $interaction->setStep('equipment_status');
  796.                     $interaction->setResponse('réponse_reçue');
  797.                     $interaction->setTimestamp(new \DateTimeImmutable());
  798.                     $interaction->setAdditionalData(['digit' => '3''status' => 'abandonne']);
  799.                     $entityManager->persist($interaction);
  800.                     $sms "Nous avons bien noté que vous avez rendu les appareils sans finaliser l'achat. Bonne journée avec My Audio.";
  801.                     $result $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  802.                     error_log("Résultat envoi SMSSSSSSSSSSSSSSSSSSSSSSSSS: " json_encode($result));
  803.                 } else if ($message == "4") {
  804.                     $interaction->setStep('equipment_status');
  805.                     $interaction->setResponse('réponse_reçue');
  806.                     $interaction->setTimestamp(new \DateTimeImmutable());
  807.                     $interaction->setAdditionalData(['digit' => '4''status' => 'attente_rdv_orl']);
  808.                     $entityManager->persist($interaction);
  809.                     $sms "Nous avons bien noté que vous etes en attente d'un rendez-vous avec un ORL. Bonne journée avec My Audio.";
  810.                     $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  811.                 } else if ($message == "5") {
  812.                     $interaction->setStep('equipment_status');
  813.                     $interaction->setResponse('réponse_reçue');
  814.                     $interaction->setTimestamp(new \DateTimeImmutable());
  815.                     $interaction->setAdditionalData(['digit' => '5''status' => 'autre']);
  816.                     $entityManager->persist($interaction);
  817.                     $sms "Merci pour votre réponse. Un conseiller My Audio vous contactera dans les prochains jours. Bonne journée.";
  818.                     $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  819.                 } else {
  820.                     error_log("Message non reconnu: " $message);
  821.                     return new Response(json_encode([
  822.                         "message" => "La réponse spécifiée est incorrecte",
  823.                         "status" => 401,
  824.                         "réponse" => $message,
  825.                     ]), 401);
  826.                 }
  827.                 $entityManager->flush();
  828.                 return new Response(json_encode([
  829.                     "message" => "Réponse traitée avec succès",
  830.                     "status" => 200,
  831.                 ]));
  832.             } catch (\Exception $e) {
  833.                 return new Response(json_encode([
  834.                     "message" => "Erreur lors du traitement de la réponse: " $e->getMessage(),
  835.                     "status" => 500,
  836.                 ]), 500);
  837.             }
  838.         }
  839.         return new Response(json_encode([
  840.             "smsId" => $smsId,
  841.             "message" => $currentDate
  842.         ]));
  843.     }
  844.     /**
  845.      * @Route("/rdvs/old/client/{id}", name="getOldRdvsByClientId", methods={"GET","HEAD"})
  846.      */
  847.     public function getOldRdvsByClientId(Request $requestClient $clientPublicFunction $publicFunction)
  848.     {
  849.         if (!$request->query->get('token')) {
  850.             return new Response(json_encode([
  851.                 "message" => "Pas de token n'a été spécifié",
  852.                 "status" => 401,
  853.             ]), 401);
  854.         }
  855.         $entityManager $this->getDoctrine()->getManager();
  856.         /** @var Token */
  857.         $token $this->getDoctrine()
  858.             ->getRepository(Token::class)
  859.             ->findOneBy(['token' => $request->query->get('token')]);
  860.         if (!$token) {
  861.             return new Response(json_encode([
  862.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  863.                 "status" => 404,
  864.             ]), 404);
  865.         }
  866.         // get token age
  867.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  868.         // if the token if older than 7 days
  869.         if ($dateDiff->7) {
  870.             $entityManager->remove($token);
  871.             $entityManager->flush();
  872.             return $this->json([
  873.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  874.                 'path' => 'src/Controller/ClientController.php',
  875.                 "status" => 401,
  876.             ], 401);
  877.         }
  878.         if ($token->getIdClient()) {
  879.             if ($client != $token->getIdClient()) {
  880.                 return new Response(json_encode([
  881.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  882.                     "status" => 404,
  883.                 ]), 404);
  884.             }
  885.         } else if ($token->getIdAudio()) {
  886.             /** @var Token */
  887.             $token $this->getDoctrine()
  888.                 ->getRepository(Rdv::class)
  889.                 ->findOneBy(['id_client' => $client'id_audio' => $token->getIdAudio()]);
  890.             if ($client != $token->getIdClient()) {
  891.                 return new Response(json_encode([
  892.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  893.                     "status" => 404,
  894.                 ]), 404);
  895.             }
  896.         } else {
  897.             return new Response(json_encode([
  898.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  899.                 "status" => 404,
  900.             ]), 404);
  901.         }
  902.         if ($request->query->get('audio')) {
  903.             /** @var ActivityRepository */
  904.             $activityRepo $this->getDoctrine();
  905.             if ($request->query->get('limit')) {
  906.                 /** @var Rdv[] */
  907.                 $rdvs $activityRepo
  908.                     ->getRepository(Rdv::class)
  909.                     ->findLastsOldRdvsWithLimit($request->query->get('limit'), $client->getId(), $request->query->get('audio'), new DateTime());
  910.                 $rdvResult = new ArrayCollection();
  911.             } else {
  912.                 /** @var Rdv[] */
  913.                 $rdvs $activityRepo
  914.                     ->getRepository(Rdv::class)
  915.                     ->findOldRdvs($client->getId(), $request->query->get('audio'), new DateTime());
  916.                 $rdvResult = new ArrayCollection();
  917.             }
  918.             foreach ($rdvs as $rdv) {
  919.                 /*if ($rdv->getIdEtat()->getId() != 1) {
  920.                     continue;
  921.                 }*/
  922.                 /** @var AudioMotif */
  923.                 $audioMotif $this->getDoctrine()
  924.                     ->getRepository(AudioMotif::class)
  925.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  926.                 if (!$audioMotif) {
  927.                     continue;
  928.                 }
  929.                 $duration '';
  930.                 if (is_null($rdv->getDuration())) {
  931.                     $duration $audioMotif->getDuration();
  932.                 } else {
  933.                     $duration $rdv->getDuration();
  934.                 }
  935.                 $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  936.                 /** @var Rdv[] */
  937.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  938.                     ->findAllReviewsCentre($rdvCentre->getId());
  939.                 $rdvItem = [
  940.                     "id" => $rdv->getId(),
  941.                     "motif_id" => $rdv->getIdMotif()->getId(),
  942.                     "duration" => $duration,
  943.                     "color" => $audioMotif->getColor(),
  944.                     "audio_id" => $rdv->getIdAudio()->getId(),
  945.                     "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  946.                     "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  947.                     "client_id" => $rdv->getIdClient()->getId(),
  948.                     "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  949.                     "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  950.                     "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  951.                     "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  952.                     "testclient" => $rdv->getTestClient() ? [
  953.                         "result" => $rdv->getTestClient()->getResultTonal(),
  954.                         "date" => $rdv->getTestClient()->getDate(),
  955.                         "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  956.                     ] : null,
  957.                     "name" => $rdvCentre->getName(),
  958.                     "phone" => $rdvCentre->getPhone(),
  959.                     "imgUrl" => $rdvCentre->getImgUrl(),
  960.                     "address" => $rdvCentre->getAddress(),
  961.                     "postale" => $rdvCentre->getPostale(),
  962.                     "city" => $rdvCentre->getCity(),
  963.                     "etat_id" => $rdvCentre->getId(),
  964.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  965.                     "nbrReview" => count($centreRdvs),
  966.                     "acceptedCurrency" => "CB Chèque",
  967.                     "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  968.                     "note" => $rdv->getNote(),
  969.                     "comment" => $rdv->getComment(),
  970.                     "review" => $rdv->getReview(),
  971.                 ];
  972.                 $rdvResult->add($rdvItem);
  973.             }
  974.         }
  975.         if (count($rdvResult) > 0) {
  976.             return new Response(json_encode(([
  977.                 "rdv" => $rdvResult->toArray(),
  978.                 "status" => 200,
  979.             ])));
  980.         } else {
  981.             return new Response(json_encode(([
  982.                 "message" => "Aucun rendez-vous a venir!",
  983.                 'path' => 'src/Controller/RdvController.php',
  984.                 "status" => 404,
  985.             ])));
  986.         }
  987.     }
  988.     /**
  989.      * @Route("/rdvs/old/client/{id}/centre", name="getOldRdvsByClientIdForCentre", methods={"GET","HEAD"})
  990.      */
  991.     public function getOldRdvsByClientIdForCentre(Request $requestClient $clientPublicFunction $publicFunction)
  992.     {
  993.         if (!$request->query->get('token')) {
  994.             return new Response(json_encode([
  995.                 "message" => "Pas de token n'a été spécifié",
  996.                 "status" => 401,
  997.             ]), 401);
  998.         }
  999.         $entityManager $this->getDoctrine()->getManager();
  1000.         /** @var Token */
  1001.         $token $this->getDoctrine()
  1002.             ->getRepository(Token::class)
  1003.             ->findOneBy(['token' => $request->query->get('token')]);
  1004.         if (!$token) {
  1005.             return new Response(json_encode([
  1006.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1007.                 "status" => 404,
  1008.             ]), 404);
  1009.         }
  1010.         $audio $this->getDoctrine()
  1011.             ->getRepository(Audio::class)
  1012.             ->findOneBy(['id' => $request->query->get('audio')]);
  1013.         $audioCentre $this->getDoctrine()
  1014.             ->getRepository(AudioCentre::class)
  1015.             ->findOneBy(['id_audio' => $audio]);
  1016.         // get token age
  1017.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1018.         // if the token if older than 7 days
  1019.         if ($dateDiff->7) {
  1020.             $entityManager->remove($token);
  1021.             $entityManager->flush();
  1022.             return $this->json([
  1023.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1024.                 'path' => 'src/Controller/ClientController.php',
  1025.                 "status" => 401,
  1026.             ], 401);
  1027.         }
  1028.         if ($token->getIdClient()) {
  1029.             if ($client != $token->getIdClient()) {
  1030.                 return new Response(json_encode([
  1031.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  1032.                     "status" => 404,
  1033.                 ]), 404);
  1034.             }
  1035.         } else if ($token->getIdAudio()) {
  1036.             /** @var Token */
  1037.             if ($token->getIdAudio() != $audio) {
  1038.                 return new Response(json_encode([
  1039.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  1040.                     "status" => 404,
  1041.                 ]), 404);
  1042.             }
  1043.         } else {
  1044.             return new Response(json_encode([
  1045.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  1046.                 "status" => 404,
  1047.             ]), 404);
  1048.         }
  1049.         if ($request->query->get('audio')) {
  1050.             /** @var ActivityRepository */
  1051.             $activityRepo $this->getDoctrine();
  1052.             if ($request->query->get('limit')) {
  1053.                 /** @var Rdv[] */
  1054.                 $rdvs $activityRepo
  1055.                     ->getRepository(Rdv::class)
  1056.                     ->findLastsOldRdvCentresWithLimit($request->query->get('limit'), $client->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  1057.                 $rdvResult = new ArrayCollection();
  1058.             } else {
  1059.                 /** @var Rdv[] */
  1060.                 $rdvs $activityRepo
  1061.                     ->getRepository(Rdv::class)
  1062.                     ->findOldRdvsByCentre($client->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  1063.                 $rdvResult = new ArrayCollection();
  1064.             }
  1065.             //dd($rdvs);
  1066.             foreach ($rdvs as $rdv) {
  1067.                 // we comment this becoz it was just the validate , we implment other choice select
  1068.                 /* if ($rdv->getIdEtat()->getId() != 5) {
  1069.                     continue;
  1070.                 }*/
  1071.                 /** @var AudioMotif */
  1072.                 $audioMotif $this->getDoctrine()
  1073.                     ->getRepository(AudioMotif::class)
  1074.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  1075.                 if (!$audioMotif) {
  1076.                     continue;
  1077.                 }
  1078.                 $duration '';
  1079.                 if (is_null($rdv->getDuration())) {
  1080.                     $duration $audioMotif->getDuration();
  1081.                 } else {
  1082.                     $duration $rdv->getDuration();
  1083.                 }
  1084.                 $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  1085.                 /** @var Rdv[] */
  1086.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  1087.                     ->findAllReviewsCentre($rdvCentre->getId());
  1088.                 $rdvItem = [
  1089.                     "id" => $rdv->getId(),
  1090.                     "motif_id" => $rdv->getIdMotif()->getId(),
  1091.                     "duration" => $duration,
  1092.                     "color" => $audioMotif->getColor(),
  1093.                     "audio_id" => $rdv->getIdAudio()->getId(),
  1094.                     "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  1095.                     "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  1096.                     "client_id" => $rdv->getIdClient()->getId(),
  1097.                     "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  1098.                     "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  1099.                     "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  1100.                     "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  1101.                     "testclient" => $rdv->getTestClient() ? [
  1102.                         "result" => $rdv->getTestClient()->getResultTonal(),
  1103.                         "date" => $rdv->getTestClient()->getDate(),
  1104.                         "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  1105.                     ] : null,
  1106.                     "name" => $rdvCentre->getName(),
  1107.                     "phone" => $rdvCentre->getPhone(),
  1108.                     "imgUrl" => $rdvCentre->getImgUrl(),
  1109.                     "address" => $rdvCentre->getAddress(),
  1110.                     "postale" => $rdvCentre->getPostale(),
  1111.                     "city" => $rdvCentre->getCity(),
  1112.                     "etat_id" => $rdvCentre->getId(),
  1113.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  1114.                     "nbrReview" => count($centreRdvs),
  1115.                     "acceptedCurrency" => "CB Chèque",
  1116.                     "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  1117.                     "note" => $rdv->getNote(),
  1118.                     "comment" => $rdv->getComment(),
  1119.                     "review" => $rdv->getReview(),
  1120.                     "status" => $rdv->getIdEtat()->getLibelle()
  1121.                 ];
  1122.                 $rdvResult->add($rdvItem);
  1123.             }
  1124.         }
  1125.         if (count($rdvResult) > 0) {
  1126.             return new Response(json_encode(([
  1127.                 "rdv" => $rdvResult->toArray(),
  1128.                 "status" => 200,
  1129.             ])));
  1130.         } else {
  1131.             return new Response(json_encode(([
  1132.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  1133.                 'path' => 'src/Controller/RdvController.php',
  1134.                 "status" => 404,
  1135.             ])));
  1136.         }
  1137.     }
  1138.     private function getOpeningHours($centerId)
  1139.     {
  1140.         $center $this->getDoctrine()->getRepository(Centre::class)->find($centerId);
  1141.         $audioCentre $this->getDoctrine()->getRepository(AudioCentre::class)
  1142.             ->findOneBy(['id_centre' => $center->getId(), 'id_audio' => $center->getIdGerant()->getId()]);
  1143.         $schedule $audioCentre->getHoraire();
  1144.         $availableHours = [];
  1145.         if (isset($schedule['fixed'])) {
  1146.             foreach ($schedule['fixed'] as $day => $hours) {
  1147.                 $dayInFrench strtolower($day);
  1148.                 $slots = [];
  1149.                 foreach ($hours as $period) {
  1150.                     $start strtotime($period['open']);
  1151.                     $end strtotime($period['close']);
  1152.                     while ($start $end) {
  1153.                         $slots[] = date('H:i'$start);
  1154.                         $start strtotime('+30 minutes'$start);
  1155.                     }
  1156.                 }
  1157.                 $availableHours[$dayInFrench] = $slots;
  1158.             }
  1159.         }
  1160.         if (isset($schedule['exceptionalOpened'])) {
  1161.             foreach ($schedule['exceptionalOpened'] as $exception) {
  1162.                 $dayOfWeek strtolower(date('l'strtotime($exception['open'])));
  1163.                 $start strtotime($exception['open']);
  1164.                 $end strtotime($exception['close']);
  1165.                 $exceptionSlots = [];
  1166.                 while ($start $end) {
  1167.                     $exceptionSlots[] = date('H:i'$start);
  1168.                     $start strtotime('+30 minutes'$start);
  1169.                 }
  1170.                 $availableHours[$dayOfWeek] = array_merge(
  1171.                     $availableHours[$dayOfWeek] ?? [],
  1172.                     $exceptionSlots
  1173.                 );
  1174.             }
  1175.         }
  1176.         if (isset($schedule['exceptionalClosed'])) {
  1177.             foreach ($schedule['exceptionalClosed'] as $exception) {
  1178.                 $dayOfWeek strtolower(date('l'strtotime($exception['open'])));
  1179.                 unset($availableHours[$dayOfWeek]);
  1180.             }
  1181.         }
  1182.         return $availableHours;
  1183.     }
  1184.     private function getBookedSlotsForDate($centerId$date)
  1185.     {
  1186.         $bookedSlots $this->getDoctrine()
  1187.             ->getRepository(Rdv::class)
  1188.             ->getBookedSlotsForDate($centerId$date);
  1189.         return $bookedSlots;
  1190.     }
  1191.     private function getAvailableSlotsForDate($openingHours$centerId$date)
  1192.     {
  1193.         $dayOfWeek date('l'strtotime($date));
  1194.         $dayInFrench $this->convertDayToFrench($dayOfWeek);
  1195.         if (!$dayInFrench) {
  1196.             throw new \Exception("Invalid day of the week: $dayOfWeek");
  1197.         }
  1198.         $slots $openingHours[$dayInFrench] ?? [];
  1199.         $bookedSlots $this->getBookedSlotsForDate($centerId$date);
  1200.         $bookedTimes = [];
  1201.         foreach ($bookedSlots as $bookedSlot) {
  1202.             $startTime $bookedSlot['date'];
  1203.             $duration $bookedSlot['duration'];
  1204.             $endTime = (clone $startTime)->modify("+$duration minutes");
  1205.             $bookedTimes[] = ['start' => $startTime'end' => $endTime];
  1206.         }
  1207.         $availableSlots = [];
  1208.         foreach ($slots as $slot) {
  1209.             $slotTime \DateTime::createFromFormat('H:i'$slot);
  1210.             $slotTime->setDate(date('Y'strtotime($date)), date('m'strtotime($date)), date('d'strtotime($date)));
  1211.             if (!$slotTime) {
  1212.                 continue;
  1213.             }
  1214.             $isAvailable true;
  1215.             foreach ($bookedTimes as $bookedTime) {
  1216.                 if ($slotTime >= $bookedTime['start'] && $slotTime $bookedTime['end']) {
  1217.                     $isAvailable false;
  1218.                     break;
  1219.                 }
  1220.             }
  1221.             if ($isAvailable) {
  1222.                 $availableSlots[] = $slot;
  1223.             }
  1224.         }
  1225.         return $availableSlots;
  1226.     }
  1227.     private function convertDayToFrench($englishDay)
  1228.     {
  1229.         $daysMap = [
  1230.             'monday' => 'lundi',
  1231.             'tuesday' => 'mardi',
  1232.             'wednesday' => 'mercredi',
  1233.             'thursday' => 'jeudi',
  1234.             'friday' => 'vendredi',
  1235.             'saturday' => 'samedi',
  1236.             'sunday' => 'dimanche'
  1237.         ];
  1238.         return $daysMap[strtolower($englishDay)] ?? null;
  1239.     }
  1240.     /**
  1241.      * @Route("/audio/{id}/rdvs/", name="getAudioRdvs", methods={"GET","HEAD"})
  1242.      */
  1243.     public function getAudioRdvs(Request $requestAudio $audio)
  1244.     {
  1245.         if (!$request->query->get('token')) {
  1246.             return new Response(json_encode([
  1247.                 "message" => "Pas de token n'a été spécifié",
  1248.                 "status" => 401,
  1249.             ]), 401);
  1250.         }
  1251.         $entityManager $this->getDoctrine()->getManager();
  1252.         /** @var Token */
  1253.         $token $this->getDoctrine()
  1254.             ->getRepository(Token::class)
  1255.             ->findOneBy(['token' => $request->query->get('token')]);
  1256.         if (!$token) {
  1257.             return new Response(json_encode([
  1258.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1259.                 "status" => 404,
  1260.             ]), 404);
  1261.         }
  1262.         // get token age
  1263.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1264.         // if the token if older than 7 days
  1265.         if ($dateDiff->7) {
  1266.             $entityManager->remove($token);
  1267.             $entityManager->flush();
  1268.             return $this->json([
  1269.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1270.                 'path' => 'src/Controller/ClientController.php',
  1271.                 "status" => 401,
  1272.             ], 401);
  1273.         }
  1274.         if ($audio != $token->getIdAudio()) {
  1275.             return new Response(json_encode([
  1276.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1277.                 "status" => 404,
  1278.             ]), 404);
  1279.         }
  1280.         $centre = (int)$request->query->get('centre');
  1281.         if (($request->query->get('debut')) && ($request->query->get('fin'))) {
  1282.             $rdvs $this->getDoctrine()
  1283.                 ->getRepository(Rdv::class)
  1284.                 ->findBetweenDate(
  1285.                     $audio->getId(),
  1286.                     new DateTime($request->query->get('debut')),
  1287.                     new DateTime($request->query->get('fin')),
  1288.                     $centre // Le centre est maintenant un entier
  1289.                 );
  1290.         } else {
  1291.             $rdvs $this->getDoctrine()
  1292.                 ->getRepository(Rdv::class)
  1293.                 ->findBy(['id_audio' => $audio->getId()]);
  1294.         }
  1295.         $rdvResult = new ArrayCollection();
  1296.         $centerId $request->query->get('centre');
  1297.         // $openingHours = $this->getOpeningHours($centerId); 
  1298.         $centerId $request->query->get('centre');
  1299.         $dateCache = new \DateTime();
  1300.         $openingHours $this->cache->get('centre_' $centerId '_horaires_' $dateCache->format('Y-m-d'), function (ItemInterface $item) use ($centerId$dateCache) {
  1301.             $item->expiresAfter(7200);
  1302.             return $this->getOpeningHours($centerId);
  1303.         });
  1304.         //dd($openingHours);
  1305.         foreach ($rdvs as $rdv) {
  1306.             if ($rdv->getIdEtat()->getId() != null) {
  1307.                 if ($rdv->getIsAbsence() != 1) {
  1308.                     /** @var AudioMotif */
  1309.                     $audioMotif $this->getDoctrine()
  1310.                         ->getRepository(AudioMotif::class)
  1311.                         ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $audio->getId()]);
  1312.                     if (!isset($audioMotif)) {
  1313.                         continue;
  1314.                     }
  1315.                     $motif $this->getDoctrine()
  1316.                         ->getRepository(Motif::class)
  1317.                         ->findOneBy(['id' => $rdv->getIdMotif()->getId()]);
  1318.                     $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  1319.                     if ($rdv->getIdClientTemp()) {
  1320.                         $confiance "";
  1321.                     } else {
  1322.                         $confiance $client->getIdPersonneConfiance() ? $client->getIdPersonneConfiance()->getId() : null;
  1323.                     }
  1324.                 }
  1325.                 $duration '';
  1326.                 if (is_null($rdv->getDuration())) {
  1327.                     $duration $audioMotif->getDuration();
  1328.                 } else {
  1329.                     $duration $rdv->getDuration();
  1330.                 }
  1331.                 $dateFin = new DateTime($rdv->getDate()->format('Y-m-d\TH:i:s'));
  1332.                 $dateFin $dateFin->add(new DateInterval("PT" $duration "M"));
  1333.                 if ($rdv->getIdClientTemp()) {
  1334.                     $findNextRdv $this->getDoctrine()
  1335.                         ->getRepository(Rdv::class)
  1336.                         ->findBy([
  1337.                             "id_client_temp" => $rdv->getIdClientTemp(),
  1338.                             "id_motif" => ['106''107''108''109']
  1339.                         ]);
  1340.                 } else {
  1341.                     $findNextRdv $this->getDoctrine()
  1342.                         ->getRepository(Rdv::class)
  1343.                         ->findBy([
  1344.                             "id_client_temp" => $rdv->getIdClient(),
  1345.                             "id_motif" => ['106''107''108''109']
  1346.                         ]);
  1347.                 }
  1348.                 $finalRdv null;
  1349.                 /*if ($rdv->getRdvParent()) {
  1350.     $finalRdv = $this->getDoctrine()
  1351.         ->getRepository(Rdv::class)
  1352.         ->find($rdv->getRdvParent());
  1353. }*/
  1354.                 //if($client->getClientDevices())
  1355.                 //{
  1356.                 //if ($client->getClientDevices()->first()) {
  1357.                 /*$nextRdv = $this->getDoctrine()
  1358.                  ->getRepository(Rdv::class)
  1359.                  ->find($finalRdv->getClientDevice()->getRdv()->getId());*/
  1360.                 //  }
  1361.                 //}
  1362.                 if ($rdv->getIsAbsence() != 1) {
  1363.                     if ($rdv->getIdClientTemp()) {
  1364.                         $nextRdvs $this->getDoctrine()
  1365.                             ->getRepository(Rdv::class)
  1366.                             ->findBy([
  1367.                                 "id_client_temp" => $client,
  1368.                                 "id_motif" => ['106''107''108''109']
  1369.                             ]);
  1370.                     } else {
  1371.                         $nextRdvs $this->getDoctrine()
  1372.                             ->getRepository(Rdv::class)
  1373.                             ->findBy([
  1374.                                 "id_client" => $client,
  1375.                                 "id_motif" => ['106''107''108''109']
  1376.                             ]);
  1377.                     }
  1378.                     if ($client->getClientDevices()) {
  1379.                         if ($client->getClientDevices()->first()) {
  1380.                             if (empty($nextRdvs)) {
  1381.                                 $isNextRdv false;
  1382.                                 $initialRdvDate $rdv->getDate();
  1383.                                 $availableSlots = [
  1384.                                     'Suivi de l’essai' => $this->findFirstAvailableSlot($centerId$initialRdvDate7),
  1385.                                     'Confirmation de l’essai' => $this->findFirstAvailableSlot($centerId$initialRdvDate14),
  1386.                                     'Validation de l’appareillage' => $this->findFirstAvailableSlot($centerId$initialRdvDate21),
  1387.                                     'Facturation de l’appareillage' => $this->findFirstAvailableSlot($centerId$initialRdvDate30),
  1388.                                     'duration' => "30"
  1389.                                 ];
  1390.                                 $mappedNextRdvs = [
  1391.                                     'Suivi de l’essai' => $this->findAvailableDay($centerId$initialRdvDate7),
  1392.                                     'Confirmation de l’essai' => $this->findAvailableDay($centerId$initialRdvDate14),
  1393.                                     'Validation de l’appareillage' => $this->findAvailableDay($centerId$initialRdvDate21),
  1394.                                     'Facturation de l’appareillage' => $this->findAvailableDay($centerId$initialRdvDate30),
  1395.                                     'duration' => "30"
  1396.                                 ];
  1397.                             } else {
  1398.                                 $isNextRdv true;
  1399.                                 $initialRdvDate $rdv->getDate();
  1400.                                 // Available slots for each follow-up date
  1401.                                 $availableSlots = [];
  1402.                                 if (isset($nextRdvs[0])) {
  1403.                                     $availableSlots['Suivi de l’essai'] = $this->getAvailableSlotsForDate(
  1404.                                         $openingHours,
  1405.                                         $centerId,
  1406.                                         $nextRdvs[0]->getDate()->format('Y-m-d')
  1407.                                     );
  1408.                                 }
  1409.                                 if (isset($nextRdvs[1])) {
  1410.                                     $availableSlots['Confirmation de l’essai'] = $this->getAvailableSlotsForDate(
  1411.                                         $openingHours,
  1412.                                         $centerId,
  1413.                                         $nextRdvs[1]->getDate()->format('Y-m-d')
  1414.                                     );
  1415.                                 }
  1416.                                 if (isset($nextRdvs[2])) {
  1417.                                     $availableSlots['Validation de l’appareillage'] = $this->getAvailableSlotsForDate(
  1418.                                         $openingHours,
  1419.                                         $centerId,
  1420.                                         $nextRdvs[2]->getDate()->format('Y-m-d')
  1421.                                     );
  1422.                                 }
  1423.                                 if (isset($nextRdvs[3])) {
  1424.                                     $availableSlots['Facturation de l’appareillage'] = $this->getAvailableSlotsForDate(
  1425.                                         $openingHours,
  1426.                                         $centerId,
  1427.                                         $nextRdvs[3]->getDate()->format('Y-m-d')
  1428.                                     );
  1429.                                 }
  1430.                                 $mappedNextRdvs array_map(function ($rdv) {
  1431.                                     return [
  1432.                                         'id' => $rdv->getId(),
  1433.                                         'date' => $rdv->getDate()->format('d-m-Y'),
  1434.                                         'hours' => $rdv->getDate()->format('H:i'),
  1435.                                         'duration' => $rdv->getDuration(),
  1436.                                         "motif_id" => $rdv->getIdMotif()->getId(),
  1437.                                         "motif_titre" => $rdv->getIdMotif()->getTitre(),
  1438.                                     ];
  1439.                                 }, $nextRdvs);
  1440.                             }
  1441.                         }
  1442.                     }
  1443.                     $rdvItem = [
  1444.                         "id" => $rdv->getId(),
  1445.                         "motif_id" => $rdv->getIdMotif()->getId(),
  1446.                         "motif_titre" => $motif->getTitre(),
  1447.                         "duration" => $duration,
  1448.                         "color" => $audioMotif->getColor(),
  1449.                         "audio_id" => $rdv->getIdAudio()->getId(),
  1450.                         "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  1451.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  1452.                         "client_id" => $client->getId(),
  1453.                         "isClient" => ($client instanceof Client) ? 0,
  1454.                         "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() : $client->getName(),
  1455.                         "client_lastname" => $rdv->getIdProche() ? $rdv->getIdProche()->getLastname() : $client->getLastname(),
  1456.                         "client_mail" => $client->getMail(),
  1457.                         "client_tel" => $client->getPhone(),
  1458.                         "client_fixe" => $client->getPhoneFixe(),
  1459.                         "confiance" =>  $confiance,
  1460.                         "client_birthday" => $client->getBirthdate() ? $client->getBirthdate()->format("Y-m-d") : null,
  1461.                         "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  1462.                         "centre_id" => $rdv->getIdCentre()->getId(),
  1463.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  1464.                         "testclient" => $rdv->getTestClient() ? [
  1465.                             "result" => $rdv->getTestClient()->getResultTonal(),
  1466.                             "date" => $rdv->getTestClient()->getDate(),
  1467.                             "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  1468.                         ] : null,
  1469.                         "name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : $rdv->getIdLieu()->getName(),
  1470.                         "centerName" => $rdv->getIdCentre()->getName(),
  1471.                         "phone" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getPhone() : $rdv->getIdLieu()->getPhone(),
  1472.                         "etat_id" => $rdv->getIdEtat()->getId(),
  1473.                         "clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
  1474.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  1475.                         "dateFin" => $dateFin->format('Y-m-d\TH:i:s'),
  1476.                         "comment" => $rdv->getComment(),
  1477.                         "note" => $rdv->getNote(),
  1478.                         "isTemp" => $rdv->getIdClientTemp() ? 0,
  1479.                         "isAbsence" => $rdv->getIsAbsence(),
  1480.                         "device" => $client->getClientDevices()->first() ? [
  1481.                             "isDevice" => true,
  1482.                             "isNextRdv" => $isNextRdv,
  1483.                             "deviceID" => $client->getClientDevices()->first()->getDevice()->getId(),
  1484.                             "clientDeviceID" => $client->getClientDevices()->first()->getId(),
  1485.                             "deviceModel" => $client->getClientDevices()->first()->getDevice()->getModel(),
  1486.                             "settingDeviceId" => $client->getClientDevices()->first()->getSettingDevice()->getSlug(),
  1487.                             "settingName" => $client->getClientDevices()->first()->getSettingDevice()->getName(),
  1488.                             "settingSlug" => $client->getClientDevices()->first()->getSettingDevice()->getSlug(),
  1489.                             "nextRdvs" => $mappedNextRdvs,
  1490.                             "available_slots" => $availableSlots
  1491.                         ] : [
  1492.                             "isDevice" => false
  1493.                         ]
  1494.                     ];
  1495.                 } else {
  1496.                     // $clientDevice = $client->getClientDevices()->first();
  1497.                     $rdvItem = [
  1498.                         "id" => $rdv->getId(),
  1499.                         "duration" => $duration,
  1500.                         "color" => $rdv->getColor() ? $rdv->getColor() . '66' '#ffb2b266',
  1501.                         "audio_id" => $rdv->getIdAudio()->getId(),
  1502.                         "client_id" =>  "",
  1503.                         "isClient" => false,
  1504.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  1505.                         "centre_id" => $rdv->getIdCentre()->getId(),
  1506.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  1507.                         "name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : $rdv->getIdLieu()->getName(),
  1508.                         "phone" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getPhone() : $rdv->getIdLieu()->getPhone(),
  1509.                         "etat_id" => $rdv->getIdEtat()->getId(),
  1510.                         "clientEtatId" => "",
  1511.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  1512.                         "dateFin" => $dateFin->format('Y-m-d\TH:i:s'),
  1513.                         "note" => $rdv->getNote(),
  1514.                         "device" => "",
  1515.                         "centerName" => $rdv->getIdCentre()->getName(),
  1516.                         "isTemp" => $rdv->getIdClientTemp() ? 0,
  1517.                         "isAbsence" => $rdv->getIsAbsence(),
  1518.                         "motif_titre" => $rdv->getMotifAbsence() ? $rdv->getMotifAbsence() : "Absence",
  1519.                     ];
  1520.                 }
  1521.                 //  if ($rdv->getDate() >= new DateTime())
  1522.                 $rdvResult->add($rdvItem);
  1523.             }
  1524.         }
  1525.         $startDate = new \DateTime('2024-02-20');
  1526.         $rdvs $this->rdvRepo->findRdvsNeedingReminderByAudio($startDate$audio->getId());
  1527.         //dd($audio->getId());
  1528.         $reminders = [];
  1529.         //dd($rdvs);
  1530.         foreach ($rdvs as $rdv) {
  1531.             $info $this->checkRdvReminder($rdv);
  1532.             if ($info !== null) {
  1533.                 $reminders[] = $info;
  1534.             }
  1535.         }
  1536.         //dd($reminders);
  1537.         if (count($rdvResult) > 0) {
  1538.             return new Response(json_encode(([
  1539.                 "content" => $rdvResult->toArray(),
  1540.                 "status" => 200,
  1541.                 "reminders" => $reminders,
  1542.                 "datefin" => $dateFin
  1543.             ])));
  1544.         } else {
  1545.             $rdvItem = [];
  1546.             //$rdvResult->add($rdvItem);
  1547.             return new Response(json_encode(([
  1548.                 "content" => $rdvResult->toArray(),
  1549.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  1550.                 'path' => 'src/Controller/RdvController.php',
  1551.                 "reminders" => $reminders,
  1552.                 "status" => 404,
  1553.             ])));
  1554.         }
  1555.     }
  1556.     private function findAvailableDay(int $centerId\DateTime $initialRdvDateint $offset): string
  1557.     {
  1558.         $currentDate = (clone $initialRdvDate)->modify("+{$offset} days");
  1559.         while (true) {
  1560.             $formattedDate $currentDate->format('Y-m-d');
  1561.             $slots $this->getAvailableSlotsForDate(
  1562.                 $this->getOpeningHoursList($centerId$formattedDate),
  1563.                 $centerId,
  1564.                 $formattedDate
  1565.             );
  1566.             if (!empty($slots)) {
  1567.                 return $formattedDate;
  1568.             }
  1569.             $currentDate->modify('+1 day');
  1570.         }
  1571.     }
  1572.     private function findFirstAvailableSlot(int $centerId\DateTime $initialRdvDateint $offset): array
  1573.     {
  1574.         $currentDate = (clone $initialRdvDate)->modify("+{$offset} days");
  1575.         while (true) {
  1576.             $formattedDate $currentDate->format('Y-m-d');
  1577.             $slots $this->getAvailableSlotsForDate(
  1578.                 $this->getOpeningHoursList($centerId$formattedDate),
  1579.                 $centerId,
  1580.                 $formattedDate
  1581.             );
  1582.             if (!empty($slots)) {
  1583.                 return $slots;
  1584.             }
  1585.             $currentDate->modify('+1 day');
  1586.         }
  1587.     }
  1588.     private function getOpeningHoursList($centerId$date)
  1589.     {
  1590.         $center $this->getDoctrine()->getRepository(Centre::class)->find($centerId);
  1591.         $audioCentre $this->getDoctrine()->getRepository(AudioCentre::class)
  1592.             ->findOneBy(['id_centre' => $center->getId(), 'id_audio' => $center->getIdGerant()->getId()]);
  1593.         $schedule $audioCentre->getHoraire();
  1594.         $availableHours = [];
  1595.         $holidayDates = [
  1596.             'JourdelAn' => '01-01',
  1597.             'LundidePâques' => '21-04',
  1598.             'FêteduTravail' => '01-05',
  1599.             'Victoire1945' => '08-05',
  1600.             'Ascension' => '29-05',
  1601.             'LundidePentecôte' => '09-06',
  1602.             'FêteNationale' => '14-07',
  1603.             'Assomption' => '15-08',
  1604.             'Toussaint' => '01-11',
  1605.             'Armistice1918' => '11-11',
  1606.             'Noël' => '25-12',
  1607.         ];
  1608.         $holidays $center->getHorairesHoliday();
  1609.         $requestDate date('d-m'strtotime($date));
  1610.         $englishToFrenchDays = [
  1611.             'monday' => 'lundi',
  1612.             'tuesday' => 'mardi',
  1613.             'wednesday' => 'mercredi',
  1614.             'thursday' => 'jeudi',
  1615.             'friday' => 'vendredi',
  1616.             'saturday' => 'samedi',
  1617.             'sunday' => 'dimanche',
  1618.         ];
  1619.         $dayOfWeek strtolower(date('l'strtotime($date)));
  1620.         $dayInFrench $englishToFrenchDays[$dayOfWeek];
  1621.         if (isset($schedule['fixed'])) {
  1622.             foreach ($schedule['fixed'] as $day => $hours) {
  1623.                 $dayKey strtolower($day);
  1624.                 $slots = [];
  1625.                 foreach ($hours as $period) {
  1626.                     $start strtotime($period['open']);
  1627.                     $end strtotime($period['close']);
  1628.                     while ($start $end) {
  1629.                         $slots[] = date('H:i'$start);
  1630.                         $start strtotime('+30 minutes'$start);
  1631.                     }
  1632.                 }
  1633.                 $availableHours[$dayKey] = $slots;
  1634.             }
  1635.         }
  1636.         foreach ($holidays['fixed'] as $holiday => $hours) {
  1637.             if (isset($holidayDates[$holiday]) && $holidayDates[$holiday] === $requestDate) {
  1638.                 $holidaySlots = [];
  1639.                 if (!empty($hours)) {
  1640.                     foreach ($hours as $period) {
  1641.                         $start strtotime($period['open']);
  1642.                         $end strtotime($period['close']);
  1643.                         while ($start $end) {
  1644.                             $holidaySlots[] = date('H:i'$start);
  1645.                             $start strtotime('+30 minutes'$start);
  1646.                         }
  1647.                     }
  1648.                     $availableHours[$dayInFrench] = $holidaySlots;
  1649.                 } else {
  1650.                     $availableHours[$dayInFrench] = [];
  1651.                 }
  1652.                 break;
  1653.             }
  1654.         }
  1655.         return $availableHours;
  1656.     }
  1657.     /**
  1658.      * @Route("/audio/{id}/rdvsTest/", name="getAudioRdvsTest", methods={"GET","HEAD"})
  1659.      */
  1660.     public function getAudioRdvsTest(Request $requestAudio $audio)
  1661.     {
  1662.         if (!$request->query->get('token')) {
  1663.             return new Response(json_encode([
  1664.                 "message" => "Pas de token n'a été spécifié",
  1665.                 "status" => 401,
  1666.             ]), 401);
  1667.         }
  1668.         $entityManager $this->getDoctrine()->getManager();
  1669.         /** @var Token */
  1670.         $token $this->getDoctrine()
  1671.             ->getRepository(Token::class)
  1672.             ->findOneBy(['token' => $request->query->get('token')]);
  1673.         if (!$token) {
  1674.             return new Response(json_encode([
  1675.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1676.                 "status" => 404,
  1677.             ]), 404);
  1678.         }
  1679.         // get token age
  1680.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1681.         // if the token if older than 7 days
  1682.         if ($dateDiff->7) {
  1683.             $entityManager->remove($token);
  1684.             $entityManager->flush();
  1685.             return $this->json([
  1686.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1687.                 'path' => 'src/Controller/ClientController.php',
  1688.                 "status" => 401,
  1689.             ], 401);
  1690.         }
  1691.         if ($audio != $token->getIdAudio()) {
  1692.             return new Response(json_encode([
  1693.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1694.                 "status" => 404,
  1695.             ]), 404);
  1696.         }
  1697.         /** @var Rdv[] */
  1698.         if (($request->query->get('debut')) && ($request->query->get('fin'))) {
  1699.             $rdvs $this->getDoctrine()
  1700.                 ->getRepository(Rdv::class)
  1701.                 ->findBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1702.         } else {
  1703.             $rdvs $this->getDoctrine()
  1704.                 ->getRepository(Rdv::class)
  1705.                 ->findBy(['id_audio' => $audio->getId()]);
  1706.         }
  1707.         $rdvResult = new ArrayCollection();
  1708.         foreach ($rdvs as $rdv) {
  1709.             if ($rdv->getIdEtat()->getId() != null) {
  1710.                 /** @var AudioMotif */
  1711.                 $audioMotif $this->getDoctrine()
  1712.                     ->getRepository(AudioMotif::class)
  1713.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $audio->getId()]);
  1714.                 if (!isset($audioMotif)) {
  1715.                     continue;
  1716.                 }
  1717.                 $motif $this->getDoctrine()
  1718.                     ->getRepository(Motif::class)
  1719.                     ->findOneBy(['id' => $rdv->getIdMotif()->getId()]);
  1720.                 $dateFin = new DateTime($rdv->getDate()->format('Y-m-d H:i:s'));
  1721.                 $dateFin $dateFin->add(new DateInterval("PT" $audioMotif->getDuration() . "M"));
  1722.                 $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  1723.                 $name $rdv->getIdProche() ? $rdv->getIdProche()->getName() : $client->getName();
  1724.                 $lastName $rdv->getIdProche() ? $rdv->getIdProche()->getLastname() : $client->getLastname();
  1725.                 $rdvItem = [
  1726.                     "id" => $rdv->getId(),
  1727.                     "title" => $lastName ' ' $name,
  1728.                     "start" => $rdv->getDate()->format('Y-m-d H:i:s'),
  1729.                     "end"   => $dateFin->format('Y-m-d H:i:s'),
  1730.                     "backgroundColor" => $audioMotif->getColor(),
  1731.                     "editable" => true,
  1732.                     "durationEditable" => false,
  1733.                     "resourceEditable" => true,
  1734.                     "cache" => false,
  1735.                     "motif_id" => $rdv->getIdMotif()->getId(),
  1736.                     "motif" => $motif->getTitre(),
  1737.                     "duree" => $audioMotif->getDuration(),
  1738.                     "color" => $audioMotif->getColor(),
  1739.                     "color_motif" => $audioMotif->getColor(),
  1740.                     "client_id" => $client->getId(),
  1741.                     "clientName" => $name,
  1742.                     "clientLastName" => $lastName,
  1743.                     "mail" => $client->getMail(),
  1744.                     "telephone" => $client->getPhone(),
  1745.                     "birthday" => $client->getBirthdate(),
  1746.                     "etat_id" => $rdv->getIdEtat()->getId(),
  1747.                     "dateDeb" => $rdv->getDate()->format('Y-m-d H:i:s'),
  1748.                     "dateFin" => $dateFin->format('Y-m-d H:i:s'),
  1749.                     "commentaire" => $rdv->getNote(),
  1750.                     "event_title" => "<b>" $lastName "</b> " $name,
  1751.                 ];
  1752.                 //  if ($rdv->getDate() >= new DateTime())
  1753.                 $rdvResult->add($rdvItem);
  1754.             }
  1755.         }
  1756.         if (count($rdvResult) > 0) {
  1757.             return new Response(json_encode(
  1758.                 $rdvResult->toArray(),
  1759.             ));
  1760.         } else {
  1761.             $rdvItem = [];
  1762.             //$rdvResult->add($rdvItem);
  1763.             return new Response(json_encode(
  1764.                 $rdvResult->toArray(),
  1765.             ));
  1766.         }
  1767.     }
  1768.     /**
  1769.      * @Route("/audio/{id}/rdvs/count", name="getCountAudioRdvs", methods={"GET","HEAD"})
  1770.      */
  1771.     public function getCountAudioRdvs(Request $requestAudio $audio)
  1772.     {
  1773.         if (!$request->query->get('token')) {
  1774.             return new Response(json_encode([
  1775.                 "message" => "Pas de token n'a été spécifié",
  1776.                 "status" => 401,
  1777.             ]), 401);
  1778.         }
  1779.         $entityManager $this->getDoctrine()->getManager();
  1780.         /** @var Token */
  1781.         $token $this->getDoctrine()
  1782.             ->getRepository(Token::class)
  1783.             ->findOneBy(['token' => $request->query->get('token')]);
  1784.         if (!$token) {
  1785.             return new Response(json_encode([
  1786.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1787.                 "status" => 404,
  1788.             ]), 404);
  1789.         }
  1790.         // get token age
  1791.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1792.         // if the token if older than 7 days
  1793.         if ($dateDiff->7) {
  1794.             $entityManager->remove($token);
  1795.             $entityManager->flush();
  1796.             return $this->json([
  1797.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1798.                 'path' => 'src/Controller/ClientController.php',
  1799.                 "status" => 401,
  1800.             ], 401);
  1801.         }
  1802.         if ($audio != $token->getIdAudio()) {
  1803.             return new Response(json_encode([
  1804.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1805.                 "status" => 404,
  1806.             ]), 404);
  1807.         }
  1808.         /** @var Rdv[] */
  1809.         $rdvs $this->getDoctrine()
  1810.             ->getRepository(Rdv::class)
  1811.             ->findBy(['id_audio' => $audio->getId()]);
  1812.         return new Response(json_encode(([
  1813.             "content" => count($rdvs),
  1814.             "status" => 200,
  1815.         ])));
  1816.     }
  1817.     /**
  1818.      * @Route("/audio/{id}/rdvsDate/count", name="getCountAudioRdvsBetweenDate", methods={"GET","HEAD"})
  1819.      */
  1820.     public function getCountAudioRdvsBetweenDate(Request $requestAudio $audio)
  1821.     {
  1822.         if (!$request->query->get('token')) {
  1823.             return new Response(json_encode([
  1824.                 "message" => "Pas de token n'a été spécifié",
  1825.                 "status" => 401,
  1826.             ]), 401);
  1827.         }
  1828.         $entityManager $this->getDoctrine()->getManager();
  1829.         /** @var Token */
  1830.         $token $this->getDoctrine()
  1831.             ->getRepository(Token::class)
  1832.             ->findOneBy(['token' => $request->query->get('token')]);
  1833.         if (!$token) {
  1834.             return new Response(json_encode([
  1835.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1836.                 "status" => 404,
  1837.             ]), 404);
  1838.         }
  1839.         // get token age
  1840.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1841.         // if the token if older than 7 days
  1842.         if ($dateDiff->7) {
  1843.             $entityManager->remove($token);
  1844.             $entityManager->flush();
  1845.             return $this->json([
  1846.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1847.                 'path' => 'src/Controller/ClientController.php',
  1848.                 "status" => 401,
  1849.             ], 401);
  1850.         }
  1851.         if ($audio != $token->getIdAudio()) {
  1852.             return new Response(json_encode([
  1853.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1854.                 "status" => 404,
  1855.             ]), 404);
  1856.         }
  1857.         /** @var Rdv[] */
  1858.         $allRdvs $this->getDoctrine()
  1859.             ->getRepository(Rdv::class)
  1860.             ->findOnlyRdvAudioBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1861.         /** @var Rdv[] */
  1862.         $rdvs $this->getDoctrine()
  1863.             ->getRepository(Rdv::class)
  1864.             ->findOnlyRdvAudioWithoutTestBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1865.         /** @var Rdv[] */
  1866.         $rdvsWithTest $this->getDoctrine()
  1867.             ->getRepository(Rdv::class)
  1868.             ->findOnlyRdvAudioWithTestBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1869.         /** @var Rdv[] */
  1870.         $allRdvsCanceled $this->getDoctrine()
  1871.             ->getRepository(Rdv::class)
  1872.             ->findCanceledRdvAudioBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1873.         /** @var Rdv[] */
  1874.         $allRdvsCanceledCentre $this->getDoctrine()
  1875.             ->getRepository(Rdv::class)
  1876.             ->findCanceledRdvCentreBetweenDate(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1877.         /** @var Rdv[] */
  1878.         $rdvsClosed $this->getDoctrine()
  1879.             ->getRepository(Rdv::class)
  1880.             ->findClosedRdvBetweenDate(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1881.         $myLead 0;
  1882.         $rdvsCanceled $this->getDoctrine()
  1883.             ->getRepository(Rdv::class)
  1884.             ->findCanceledRdvAudioBetweenDateWithoutTest($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1885.         foreach ($rdvsCanceled as $rdvc) {
  1886.             if (!is_null($rdvc->getIdClient())) {
  1887.                 $rdvClient $this->getDoctrine()
  1888.                     ->getRepository(Rdv::class)
  1889.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1890.                 if (count($rdvClient) == 0) {
  1891.                     $myLead $myLead 1;
  1892.                 }
  1893.             }
  1894.         }
  1895.         $myLeadAdvanced 0;
  1896.         $rdvsCanceledA $this->getDoctrine()
  1897.             ->getRepository(Rdv::class)
  1898.             ->findCanceledRdvAudioBetweenDateWithTest($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1899.         foreach ($rdvsCanceledA as $rdvc) {
  1900.             if (!is_null($rdvc->getIdClient())) {
  1901.                 $rdvClient $this->getDoctrine()
  1902.                     ->getRepository(Rdv::class)
  1903.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1904.                 if (count($rdvClient) == 0) {
  1905.                     $myLeadAdvanced $myLeadAdvanced 1;
  1906.                 }
  1907.             }
  1908.         }
  1909.         /**** MY RDV Centre****/
  1910.         $myrdvCentre 0;
  1911.         $rdvs $this->getDoctrine()
  1912.             ->getRepository(Rdv::class)
  1913.             ->findRDVCentreBetweenDateWithoutTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1914.         $myrdvCentre count($rdvs);
  1915.         /**** MY RDV ADVANCED ****/
  1916.         $myRdvAdvancedCentre 0;
  1917.         $rdvsA $this->getDoctrine()
  1918.             ->getRepository(Rdv::class)
  1919.             ->findRDVCentreBetweenDateWithTestId(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1920.         $myRdvAdvancedCentre count($rdvsA);
  1921.         /**** FIRST RDV BY MOTIF PREMIER RDV ****/
  1922.         $myFirstRdv 0;
  1923.         $rdvsFirst $this->getDoctrine()
  1924.             ->getRepository(Rdv::class)
  1925.             ->findFirstRdv(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1926.         $myFirstRdv count($rdvsFirst);
  1927.         /****  RDV BY RECHERCHE RESULT VIA MYAUDIO ****/
  1928.         $myAudioRdv 0;
  1929.         $audioRdv $this->getDoctrine()
  1930.             ->getRepository(Rdv::class)
  1931.             ->findRdvMyAudio(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1932.         $myAudioRdv count($audioRdv);
  1933.         /****  RDV BY GENDER ****/
  1934.         $myRdvByGender 0;
  1935.         $audioRdvGender $this->getDoctrine()
  1936.             ->getRepository(Rdv::class)
  1937.             ->countMaleAndFemalePatient(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1938.         $myRdvByGender $audioRdvGender;
  1939.         /****  RDV BY AGE ****/
  1940.         $myRdvByAge 0;
  1941.         $audioRdvAge $this->getDoctrine()
  1942.             ->getRepository(Rdv::class)
  1943.             ->countClientsByAgeGroupsPatient(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1944.         $myRdvByAge $audioRdvAge;
  1945.         //  dd($myRdvByAge);
  1946.         /**** MY LEAD ****/
  1947.         $myLeadCentre 0;
  1948.         $rdvsCanceled $this->getDoctrine()
  1949.             ->getRepository(Rdv::class)
  1950.             ->findCanceledRdvCentreBetweenDateWithoutTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1951.         foreach ($rdvsCanceled as $rdvc) {
  1952.             if (!is_null($rdvc->getIdClient())) {
  1953.                 $rdvClient $this->getDoctrine()
  1954.                     ->getRepository(Rdv::class)
  1955.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1956.                 if (count($rdvClient) == 0) {
  1957.                     $myLeadCentre $myLeadCentre 1;
  1958.                 }
  1959.             }
  1960.         }
  1961.         /**** MY LEAD ADVANCED****/
  1962.         $myLeadAdvancedCentre 0;
  1963.         $rdvsCanceledA $this->getDoctrine()
  1964.             ->getRepository(Rdv::class)
  1965.             ->findCanceledRdvCentreBetweenDateWithTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1966.         foreach ($rdvsCanceledA as $rdvc) {
  1967.             if (!is_null($rdvc->getIdClient())) {
  1968.                 $rdvClient $this->getDoctrine()
  1969.                     ->getRepository(Rdv::class)
  1970.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1971.                 if (count($rdvClient) == 0) {
  1972.                     $myLeadAdvancedCentre $myLeadAdvancedCentre 1;
  1973.                 }
  1974.             }
  1975.         }
  1976.         return $this->json([
  1977.             "rdvs" => count($rdvs),
  1978.             "rdvsFromTest" => count($rdvsWithTest),
  1979.             "allRdvs" => count($allRdvs),
  1980.             "rdvsCanceled" => count($allRdvsCanceled),
  1981.             "rdvsClosed" => $rdvsClosed,
  1982.             "myRdvByGender" => $myRdvByGender,
  1983.             "myLead" => $myLead,
  1984.             "myRdvByAge" => $myRdvByAge,
  1985.             "myAudioRdv" => $myAudioRdv,
  1986.             "myLeadAdvanced" => $myLeadAdvanced,
  1987.             "myRDVCentre" => $myrdvCentre,
  1988.             "myRDVAdancedCentre" => $myRdvAdvancedCentre,
  1989.             "myLeadCentre" => $myLeadCentre,
  1990.             "myLeadAdvancedCentre" => $myLeadAdvancedCentre,
  1991.             "rdvsCanceledCentre" => count($allRdvsCanceledCentre),
  1992.             "myFirstRdv" => $myFirstRdv,
  1993.             "status" => 200,
  1994.         ]);
  1995.     }
  1996.     /**
  1997.      * @Route("/rdvs/old/clientTemp/{id}", name="getOldRdvsByClientTempId", methods={"GET","HEAD"})
  1998.      */
  1999.     public function getOldRdvsByClientTempId(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2000.     {
  2001.         if (!$request->query->get('token')) {
  2002.             return new Response(json_encode([
  2003.                 "message" => "Pas de token n'a été spécifié",
  2004.                 "status" => 401,
  2005.             ]), 401);
  2006.         }
  2007.         $entityManager $this->getDoctrine()->getManager();
  2008.         /** @var Token */
  2009.         $token $this->getDoctrine()
  2010.             ->getRepository(Token::class)
  2011.             ->findOneBy(['token' => $request->query->get('token')]);
  2012.         if (!$token) {
  2013.             return new Response(json_encode([
  2014.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2015.                 "status" => 404,
  2016.             ]), 404);
  2017.         }
  2018.         // get token age
  2019.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2020.         // if the token if older than 7 days
  2021.         if ($dateDiff->7) {
  2022.             $entityManager->remove($token);
  2023.             $entityManager->flush();
  2024.             return $this->json([
  2025.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2026.                 'path' => 'src/Controller/ClientController.php',
  2027.                 "status" => 401,
  2028.             ], 401);
  2029.         }
  2030.         if ($clientTemp->getIdAudio() != $token->getIdAudio()) {
  2031.             return new Response(json_encode([
  2032.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2033.                 "status" => 404,
  2034.             ]), 404);
  2035.         }
  2036.         if ($request->query->get('audio')) {
  2037.             /** @var ActivityRepository */
  2038.             $activityRepo $this->getDoctrine()->getRepository(Rdv::class);
  2039.             if ($request->query->get('limit')) {
  2040.                 /** @var Rdv[] */
  2041.                 $rdvs $activityRepo
  2042.                     ->findLastsOldRdvsWithLimitTemp($request->query->get('limit'), $clientTemp->getId(), $request->query->get('audio'), new DateTime());
  2043.                 $rdvResult = new ArrayCollection();
  2044.             } else {
  2045.                 /** @var Rdv[] */
  2046.                 $rdvs $activityRepo
  2047.                     ->findOldRdvsTemp($clientTemp->getId(), $request->query->get('audio'), new DateTime());
  2048.                 $rdvResult = new ArrayCollection();
  2049.             }
  2050.             foreach ($rdvs as $rdv) {
  2051.                 if ($rdv->getIdEtat()->getId() != 1) {
  2052.                     continue;
  2053.                 }
  2054.                 /** @var AudioMotif */
  2055.                 $audioMotif $this->getDoctrine()
  2056.                     ->getRepository(AudioMotif::class)
  2057.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  2058.                 if (!$audioMotif) {
  2059.                     continue;
  2060.                 }
  2061.                 $duration '';
  2062.                 if (is_null($rdv->getDuration())) {
  2063.                     $duration $audioMotif->getDuration();
  2064.                 } else {
  2065.                     $duration $rdv->getDuration();
  2066.                 }
  2067.                 $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  2068.                 /** @var Rdv[] */
  2069.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2070.                     ->findAllReviewsCentre($rdvCentre->getId());
  2071.                 $rdvItem = [
  2072.                     "id" => $rdv->getId(),
  2073.                     "motif_id" => $rdv->getIdMotif()->getId(),
  2074.                     "duration" => $duration,
  2075.                     "color" => $audioMotif->getColor(),
  2076.                     "audio_id" => $rdv->getIdAudio()->getId(),
  2077.                     "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2078.                     "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2079.                     "client_id_temp" => $rdv->getIdClientTemp()->getId(),
  2080.                     "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2081.                     "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2082.                     "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2083.                     "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2084.                     "testclient" => $rdv->getTestClient() ? [
  2085.                         "result" => $rdv->getTestClient()->getResultTonal(),
  2086.                         "date" => $rdv->getTestClient()->getDate(),
  2087.                         "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  2088.                     ] : null,
  2089.                     "name" => $rdvCentre->getName(),
  2090.                     "phone" => $rdvCentre->getPhone(),
  2091.                     "imgUrl" => $rdvCentre->getImgUrl(),
  2092.                     "address" => $rdvCentre->getAddress(),
  2093.                     "postale" => $rdvCentre->getPostale(),
  2094.                     "city" => $rdvCentre->getCity(),
  2095.                     "etat_id" => $rdvCentre->getId(),
  2096.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2097.                     "nbrReview" => count($centreRdvs),
  2098.                     "acceptedCurrency" => "CB Chèque",
  2099.                     "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2100.                     "note" => $rdv->getNote(),
  2101.                     "comment" => $rdv->getComment(),
  2102.                     "review" => $rdv->getReview(),
  2103.                 ];
  2104.                 $rdvResult->add($rdvItem);
  2105.             }
  2106.         }
  2107.         if (count($rdvResult) > 0) {
  2108.             return new Response(json_encode(([
  2109.                 "rdv" => $rdvResult->toArray(),
  2110.                 "status" => 200,
  2111.             ])));
  2112.         } else {
  2113.             return new Response(json_encode(([
  2114.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  2115.                 'path' => 'src/Controller/RdvController.php',
  2116.                 "status" => 404,
  2117.             ])));
  2118.         }
  2119.     }
  2120.     /**
  2121.      * @Route("/rdvs/old/clientTemp/{id}/centre", name="getOldRdvsByClientTempIdByCentre", methods={"GET","HEAD"})
  2122.      */
  2123.     public function getOldRdvsByClientTempIdByCentre(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2124.     {
  2125.         if (!$request->query->get('token')) {
  2126.             return new Response(json_encode([
  2127.                 "message" => "Pas de token n'a été spécifié",
  2128.                 "status" => 401,
  2129.             ]), 401);
  2130.         }
  2131.         $entityManager $this->getDoctrine()->getManager();
  2132.         /** @var Token */
  2133.         $token $this->getDoctrine()
  2134.             ->getRepository(Token::class)
  2135.             ->findOneBy(['token' => $request->query->get('token')]);
  2136.         if (!$token) {
  2137.             return new Response(json_encode([
  2138.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2139.                 "status" => 404,
  2140.             ]), 404);
  2141.         }
  2142.         // get token age
  2143.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2144.         // if the token if older than 7 days
  2145.         if ($dateDiff->7) {
  2146.             $entityManager->remove($token);
  2147.             $entityManager->flush();
  2148.             return $this->json([
  2149.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2150.                 'path' => 'src/Controller/ClientController.php',
  2151.                 "status" => 401,
  2152.             ], 401);
  2153.         }
  2154.         $audioCentre $this->getDoctrine()
  2155.             ->getRepository(AudioCentre::class)
  2156.             ->findOneBy(['id_audio' => $token->getIdAudio()]);
  2157.         // we add the multi-centre so we wil desable the autorisation 
  2158.         /*
  2159.         if ($clientTemp->getIdCentre() != $audioCentre->getIdCentre()) {
  2160.             return new Response(json_encode([
  2161.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2162.                 "status" => 404,
  2163.             ]), 404);
  2164.         }
  2165. */
  2166.         /** @var ActivityRepository */
  2167.         $activityRepo $this->getDoctrine()->getRepository(Rdv::class);
  2168.         if ($request->query->get('limit')) {
  2169.             /** @var Rdv[] */
  2170.             $rdvs $activityRepo
  2171.                 ->findLastsOldRdvsWithLimitTempByCentre($request->query->get('limit'), $clientTemp->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  2172.             $rdvResult = new ArrayCollection();
  2173.         } else {
  2174.             /** @var Rdv[] */
  2175.             $rdvs $activityRepo
  2176.                 ->findOldRdvsTempByCentre($clientTemp->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  2177.             $rdvResult = new ArrayCollection();
  2178.         }
  2179.         foreach ($rdvs as $rdv) {
  2180.             /*if ($rdv->getIdEtat()->getId() != 1) {
  2181.                 continue;
  2182.             }*/
  2183.             /** @var AudioMotif */
  2184.             $audioMotif $this->getDoctrine()
  2185.                 ->getRepository(AudioMotif::class)
  2186.                 ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  2187.             if (!$audioMotif) {
  2188.                 continue;
  2189.             }
  2190.             $duration '';
  2191.             if (is_null($rdv->getDuration())) {
  2192.                 $duration $audioMotif->getDuration();
  2193.             } else {
  2194.                 $duration $rdv->getDuration();
  2195.             }
  2196.             $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  2197.             /** @var Rdv[] */
  2198.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2199.                 ->findAllReviewsCentre($rdvCentre->getId());
  2200.             $rdvItem = [
  2201.                 "id" => $rdv->getId(),
  2202.                 "motif_id" => $rdv->getIdMotif()->getId(),
  2203.                 "duration" => $duration,
  2204.                 "color" => $audioMotif->getColor(),
  2205.                 "audio_id" => $rdv->getIdAudio()->getId(),
  2206.                 "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2207.                 "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2208.                 "client_id_temp" => $rdv->getIdClientTemp()->getId(),
  2209.                 "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2210.                 "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2211.                 "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2212.                 "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2213.                 "testclient" => $rdv->getTestClient() ? [
  2214.                     "result" => $rdv->getTestClient()->getResultTonal(),
  2215.                     "date" => $rdv->getTestClient()->getDate(),
  2216.                     "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  2217.                 ] : null,
  2218.                 "name" => $rdvCentre->getName(),
  2219.                 "phone" => $rdvCentre->getPhone(),
  2220.                 "imgUrl" => $rdvCentre->getImgUrl(),
  2221.                 "address" => $rdvCentre->getAddress(),
  2222.                 "postale" => $rdvCentre->getPostale(),
  2223.                 "city" => $rdvCentre->getCity(),
  2224.                 "etat_id" => $rdvCentre->getId(),
  2225.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2226.                 "nbrReview" => count($centreRdvs),
  2227.                 "acceptedCurrency" => "CB Chèque",
  2228.                 "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2229.                 "note" => $rdv->getNote(),
  2230.                 "comment" => $rdv->getComment(),
  2231.                 "review" => $rdv->getReview(),
  2232.                 "status" => $rdv->getIdEtat()->getLibelle()
  2233.             ];
  2234.             $rdvResult->add($rdvItem);
  2235.         }
  2236.         if (count($rdvResult) > 0) {
  2237.             return new Response(json_encode(([
  2238.                 "rdv" => $rdvResult->toArray(),
  2239.                 "status" => 200,
  2240.             ])));
  2241.         } else {
  2242.             return new Response(json_encode(([
  2243.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  2244.                 'path' => 'src/Controller/RdvController.php',
  2245.                 "status" => 404,
  2246.             ])));
  2247.         }
  2248.     }
  2249.     /**
  2250.      * @Route("/rdvs/clientTemp/{id}", name="getRdvsByClientTempID", methods={"GET","HEAD"})
  2251.      */
  2252.     public function getRdvsByClientTempID(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2253.     {
  2254.         if (!$request->query->get('token')) {
  2255.             return new Response(json_encode([
  2256.                 "message" => "Pas de token n'a été spécifié",
  2257.                 "status" => 401,
  2258.             ]), 401);
  2259.         }
  2260.         $entityManager $this->getDoctrine()->getManager();
  2261.         /** @var Token */
  2262.         $token $this->getDoctrine()
  2263.             ->getRepository(Token::class)
  2264.             ->findOneBy(['token' => $request->query->get('token')]);
  2265.         if (!$token) {
  2266.             return new Response(json_encode([
  2267.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2268.                 "status" => 404,
  2269.             ]), 404);
  2270.         }
  2271.         // get token age
  2272.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2273.         // if the token if older than 7 days
  2274.         if ($dateDiff->7) {
  2275.             $entityManager->remove($token);
  2276.             $entityManager->flush();
  2277.             return $this->json([
  2278.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2279.                 'path' => 'src/Controller/ClientController.php',
  2280.                 "status" => 401,
  2281.             ], 401);
  2282.         }
  2283.         if ($clientTemp->getIdAudio() != $token->getIdAudio()) {
  2284.             return new Response(json_encode([
  2285.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2286.                 "status" => 404,
  2287.             ]), 404);
  2288.         }
  2289.         /** @var Rdv[] */
  2290.         $rdvs $this->getDoctrine()
  2291.             ->getRepository(Rdv::class)
  2292.             ->findBy(['id_client_temp' => $clientTemp->getId(), 'id_audio' => $token->getIdAudio()]);
  2293.         $rdvResult = new ArrayCollection();
  2294.         if ($request->query->get('old')) {
  2295.             $oldRdvResult = new ArrayCollection();
  2296.         }
  2297.         foreach ($rdvs as $rdv) {
  2298.             if ($rdv->getIdEtat()->getId() != null) {
  2299.                 if ($rdv->getIdEtat()->getId() == 1) {
  2300.                     /** @var AudioMotif */
  2301.                     $audioMotif $this->getDoctrine()
  2302.                         ->getRepository(AudioMotif::class)
  2303.                         ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $token->getIdAudio()]);
  2304.                     /** @var Rdv[] */
  2305.                     $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2306.                         ->findAllReviewsCentre($rdv->getIdCentre()->getId());
  2307.                     $duration '';
  2308.                     if (is_null($rdv->getDuration())) {
  2309.                         $duration $audioMotif->getDuration();
  2310.                     } else {
  2311.                         $duration $rdv->getDuration();
  2312.                     }
  2313.                     $rdvItem = [
  2314.                         "id" => $rdv->getId(),
  2315.                         "motif_id" => $rdv->getIdMotif()->getId(),
  2316.                         "duration" => $duration,
  2317.                         "color" => $audioMotif->getColor(),
  2318.                         "audio_id" => $rdv->getIdAudio()->getId(),
  2319.                         "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2320.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2321.                         "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  2322.                         "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2323.                         "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2324.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2325.                         "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2326.                         "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2327.                         "nbrReview" => count($centreRdvs),
  2328.                         "acceptedCurrency" => "CB Chèque",
  2329.                         "name" => $rdv->getIdCentre()->getName(),
  2330.                         "imgUrl" => $rdv->getIdCentre()->getImgUrl(),
  2331.                         "address" => $rdv->getIdCentre()->getAddress(),
  2332.                         "phone" => $rdv->getIdCentre()->getPhone(),
  2333.                         "etat_id" => $rdv->getIdEtat()->getId(),
  2334.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2335.                         "comment" => $rdv->getComment(),
  2336.                         "note" => $rdv->getNote(),
  2337.                         "review" => $rdv->getReview(),
  2338.                     ];
  2339.                     if ($rdv->getDate() >= new DateTime()) {
  2340.                         $rdvResult->add($rdvItem);
  2341.                     } else if ($request->query->get('old')) {
  2342.                         $oldRdvResult->add($rdvItem);
  2343.                     }
  2344.                 }
  2345.             }
  2346.         }
  2347.         if ($request->query->get('old')) {
  2348.             if (count($rdvResult) > || count($oldRdvResult) > 0) {
  2349.                 return new Response(json_encode(([
  2350.                     "rdv" => $rdvResult->toArray(),
  2351.                     "oldRdv" => $oldRdvResult->toArray(),
  2352.                     "status" => 200,
  2353.                 ])));
  2354.             } else {
  2355.                 return new Response(json_encode(([
  2356.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2357.                     'path' => 'src/Controller/RdvController.php',
  2358.                     "status" => 404,
  2359.                 ])));
  2360.             }
  2361.         } else {
  2362.             if (count($rdvResult) > 0) {
  2363.                 return new Response(json_encode(([
  2364.                     "content" => $rdvResult->toArray(),
  2365.                     "status" => 200,
  2366.                 ])));
  2367.             } else {
  2368.                 return new Response(json_encode(([
  2369.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2370.                     'path' => 'src/Controller/RdvController.php',
  2371.                     "status" => 404,
  2372.                 ])));
  2373.             }
  2374.         }
  2375.     }
  2376.     /**
  2377.      * @Route("/rdvs/clientTemp/{id}/centre", name="getRdvsByClientTempIDByCentre", methods={"GET","HEAD"})
  2378.      */
  2379.     public function getRdvsByClientTempIDByCentre(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2380.     {
  2381.         if (!$request->query->get('token')) {
  2382.             return new Response(json_encode([
  2383.                 "message" => "Pas de token n'a été spécifié",
  2384.                 "status" => 401,
  2385.             ]), 401);
  2386.         }
  2387.         $entityManager $this->getDoctrine()->getManager();
  2388.         /** @var Token */
  2389.         $token $this->getDoctrine()
  2390.             ->getRepository(Token::class)
  2391.             ->findOneBy(['token' => $request->query->get('token')]);
  2392.         if (!$token) {
  2393.             return new Response(json_encode([
  2394.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2395.                 "status" => 404,
  2396.             ]), 404);
  2397.         }
  2398.         // get token age
  2399.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2400.         // if the token if older than 7 days
  2401.         if ($dateDiff->7) {
  2402.             $entityManager->remove($token);
  2403.             $entityManager->flush();
  2404.             return $this->json([
  2405.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2406.                 'path' => 'src/Controller/ClientController.php',
  2407.                 "status" => 401,
  2408.             ], 401);
  2409.         }
  2410.         $audioCentre $this->getDoctrine()
  2411.             ->getRepository(AudioCentre::class)
  2412.             ->findOneBy(['id_audio' => $token->getIdAudio()]);
  2413.         // we add the multi-centre so we wil desable the autorisation 
  2414.         /*    
  2415.         if ($clientTemp->getIdCentre() != $audioCentre->getIdCentre()) {
  2416.             return new Response(json_encode([
  2417.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2418.                 "status" => 404,
  2419.             ]), 404);
  2420.         }*/
  2421.         /** @var Rdv[] */
  2422.         $rdvs $this->getDoctrine()
  2423.             ->getRepository(Rdv::class)
  2424.             ->findBy(['id_client_temp' => $clientTemp->getId(), 'id_centre' => $audioCentre->getIdCentre()]);
  2425.         $rdvResult = new ArrayCollection();
  2426.         if ($request->query->get('old')) {
  2427.             $oldRdvResult = new ArrayCollection();
  2428.         }
  2429.         foreach ($rdvs as $rdv) {
  2430.             if ($rdv->getIdEtat()->getId() != null) {
  2431.                 if ($rdv->getIdEtat()->getId() != 6) {
  2432.                     // if ($rdv->getIdEtat()->getId() == 1) {
  2433.                     /** @var AudioMotif */
  2434.                     $audioMotif $this->getDoctrine()
  2435.                         ->getRepository(AudioMotif::class)
  2436.                         ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  2437.                     /** @var Rdv[] */
  2438.                     $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2439.                         ->findAllReviewsCentre($rdv->getIdCentre()->getId());
  2440.                     $duration '';
  2441.                     if (is_null($rdv->getDuration())) {
  2442.                         $duration $audioMotif->getDuration();
  2443.                     } else {
  2444.                         $duration $rdv->getDuration();
  2445.                     }
  2446.                     $rdvItem = [
  2447.                         "id" => $rdv->getId(),
  2448.                         "motif_id" => $rdv->getIdMotif()->getId(),
  2449.                         "duration" => $duration,
  2450.                         "color" => $audioMotif->getColor(),
  2451.                         "audio_id" => $rdv->getIdAudio()->getId(),
  2452.                         "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2453.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2454.                         "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  2455.                         "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2456.                         "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2457.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2458.                         "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2459.                         "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2460.                         "nbrReview" => count($centreRdvs),
  2461.                         "acceptedCurrency" => "CB Chèque",
  2462.                         "name" => $rdv->getIdCentre()->getName(),
  2463.                         "imgUrl" => $rdv->getIdCentre()->getImgUrl(),
  2464.                         "address" => $rdv->getIdCentre()->getAddress(),
  2465.                         "phone" => $rdv->getIdCentre()->getPhone(),
  2466.                         "etat_id" => $rdv->getIdEtat()->getId(),
  2467.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2468.                         "comment" => $rdv->getComment(),
  2469.                         "note" => $rdv->getNote(),
  2470.                         "review" => $rdv->getReview(),
  2471.                         "status" => $rdv->getIdEtat()->getLibelle()
  2472.                     ];
  2473.                     if ($rdv->getDate() >= new DateTime()) {
  2474.                         $rdvResult->add($rdvItem);
  2475.                     } else if ($request->query->get('old')) {
  2476.                         $oldRdvResult->add($rdvItem);
  2477.                     }
  2478.                 }
  2479.             }
  2480.         }
  2481.         if ($request->query->get('old')) {
  2482.             if (count($rdvResult) > || count($oldRdvResult) > 0) {
  2483.                 return new Response(json_encode(([
  2484.                     "rdv" => $rdvResult->toArray(),
  2485.                     "oldRdv" => $oldRdvResult->toArray(),
  2486.                     "status" => 200,
  2487.                 ])));
  2488.             } else {
  2489.                 return new Response(json_encode(([
  2490.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2491.                     'path' => 'src/Controller/RdvController.php',
  2492.                     "status" => 404,
  2493.                 ])));
  2494.             }
  2495.         } else {
  2496.             if (count($rdvResult) > 0) {
  2497.                 return new Response(json_encode(([
  2498.                     "content" => $rdvResult->toArray(),
  2499.                     "status" => 200,
  2500.                 ])));
  2501.             } else {
  2502.                 return new Response(json_encode(([
  2503.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2504.                     'path' => 'src/Controller/RdvController.php',
  2505.                     "status" => 404,
  2506.                 ])));
  2507.             }
  2508.         }
  2509.     }
  2510.     /**
  2511.      * @Route("/rdv", name="postRdv", methods={"POST"})
  2512.      */
  2513.     public function postRdv(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSmsAppointmentCallService $Callservice): Response
  2514.     {
  2515.         $data json_decode($request->getContent(), true);
  2516.         if (!isset($data["token"])) {
  2517.             return new Response(json_encode([
  2518.                 "message" => "Pas de token n'a été spécifié",
  2519.                 "status" => 401,
  2520.             ]), 401);
  2521.         }
  2522.         $entityManager $this->getDoctrine()->getManager();
  2523.         /** @var Token */
  2524.         $token $this->getDoctrine()
  2525.             ->getRepository(Token::class)
  2526.             ->findOneBy(['token' => $data["token"]]);
  2527.         if (!$token) {
  2528.             return new Response(json_encode([
  2529.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2530.                 "status" => 404,
  2531.             ]), 404);
  2532.         }
  2533.         // get token age
  2534.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2535.         // if the token if older than 7 days
  2536.         if ($dateDiff->7) {
  2537.             $entityManager->remove($token);
  2538.             $entityManager->flush();
  2539.             return $this->json([
  2540.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2541.                 'path' => 'src/Controller/ClientController.php',
  2542.                 "status" => 401,
  2543.             ], 401);
  2544.         }
  2545.         // makes the rdv
  2546.         $rdv = new Rdv();
  2547.         if ($token->getIdAudio()) {
  2548.             //if the token if for an audio
  2549.             $audio $token->getIdAudio();
  2550.             if ((isset($data["client_id"]))) {
  2551.                 $client $this->getDoctrine()
  2552.                     ->getRepository(Client::class)
  2553.                     ->findOneBy(['id' => $data["client_id"]]);
  2554.             } else {
  2555.                 $client $this->getDoctrine()
  2556.                     ->getRepository(ClientTemp::class)
  2557.                     ->findOneBy(['id' => $data["client_id_temp"]]);
  2558.             }
  2559.             if ($client == null) {
  2560.                 return new Response(json_encode(([
  2561.                     'message' => 'Error, no client found at this id',
  2562.                     'path' => 'src/Controller/RdvController.php',
  2563.                     "status" => 400,
  2564.                 ])), 400);
  2565.             }
  2566.         } elseif ($token->getIdClient()) {
  2567.             //if the token if for a client
  2568.             $client $token->getIdClient();
  2569.             /** @var ActivityRepository */
  2570.             $activityRepo $this->getDoctrine();
  2571.             /** @var TestClient */
  2572.             $testClient $activityRepo
  2573.                 ->getRepository(TestClient::class)
  2574.                 ->getLatestTestClient($client);
  2575.             // add the test to the rdv if the client had one
  2576.             if ($testClient)
  2577.             // add the test to the rdv if the test isn't already on another rdv
  2578.             {
  2579.                 if (!$testClient->getRdv()) {
  2580.                     $rdv->setTestClient($testClient);
  2581.                 }
  2582.             }
  2583.             /** @var Audio */
  2584.             $audio $this->getDoctrine()
  2585.                 ->getRepository(Audio::class)
  2586.                 ->findOneBy(['id' => $data["audio_id"]]);
  2587.             if (isset($data["proche_id"])) {
  2588.                 $proche $this->getDoctrine()
  2589.                     ->getRepository(Proches::class)
  2590.                     ->findOneBy(['id' => $data["proche_id"], "id_client" => $client]);
  2591.             }
  2592.             if (!$audio) {
  2593.                 return new Response(json_encode(([
  2594.                     'message' => "Erreur, pas d'audio n'a été trouvé à cette id.",
  2595.                     'path' => 'src/Controller/RdvController.php',
  2596.                 ])), 400);
  2597.             }
  2598.             /** @var ClientBlocked */
  2599.             $clientBlocked $this->getDoctrine()
  2600.                 ->getRepository(ClientBlocked::class)
  2601.                 ->findOneBy(["id_audio" => $audio"id_client" => $client]);
  2602.             if ($clientBlocked) {
  2603.                 return new Response(json_encode(([
  2604.                     'message' => 'Erreur, vous avez été bloqué par cette audioprothésiste.',
  2605.                     'path' => 'src/Controller/RdvController.php',
  2606.                 ])), 400);
  2607.             }
  2608.             // set the rdv test
  2609.         } else {
  2610.             return new Response(json_encode(([
  2611.                 'message' => "Erreur, ce token n'est pas celui d'un client ou audioprothèsiste.",
  2612.                 'path' => 'src/Controller/RdvController.php',
  2613.             ])), 400);
  2614.         }
  2615.         $rdv->setIdAudio($audio);
  2616.         if (isset($proche)) {
  2617.             $rdv->setIdProche($proche);
  2618.         }
  2619.         if (isset($data["client_id_temp"])) {
  2620.             $rdv->setIdClientTemp($client);
  2621.         } else {
  2622.             $rdv->setIdClient($client);
  2623.         }
  2624.         if (isset($data["isMyaudio"])) {
  2625.             $rdv->setIsMyaudio(true);
  2626.         }
  2627.         if (isset($data["isRdvLead"])) {
  2628.             $rdv->setIsRdvLp(true);
  2629.         }
  2630.         if (isset($data["isRdvRapide"])) {
  2631.             $rdv->setIsRdvRapide(true);
  2632.         }
  2633.         if (isset($data["duree"])) {
  2634.             $rdv->setDuration($data["duree"]);
  2635.         }
  2636.         if (isset($data["color"])) {
  2637.             $rdv->setColor($data["color"]);
  2638.         }
  2639.         if (isset($data["lead"])) {
  2640.             $lead $this->getDoctrine()
  2641.                 ->getRepository(LeadRdv::class)
  2642.                 ->find($data["lead"]);
  2643.             $lead->setRdv($rdv);
  2644.             $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
  2645.             if ($leadStatus) {
  2646.                 $lead->setLeadStatus($leadStatus);
  2647.             }
  2648.         }
  2649.         /** @var Centre */
  2650.         if (isset($data["centre_id"])) {
  2651.             $centre $this->getDoctrine()
  2652.                 ->getRepository(Centre::class)
  2653.                 ->findOneBy(['id' => $data["centre_id"]]);
  2654.             if ($centre == null) {
  2655.                 return new Response(json_encode(([
  2656.                     'message' => 'Error, no centre found at this id',
  2657.                     'path' => 'src/Controller/RdvController.php',
  2658.                     "status" => 400,
  2659.                 ])), 400);
  2660.             }
  2661.             /** @var AudioCentre */
  2662.             $liaison $this->getDoctrine()
  2663.                 ->getRepository(AudioCentre::class)
  2664.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  2665.             if ($liaison == null) {
  2666.                 return new Response(json_encode(([
  2667.                     'message' => 'Error, audio isnt part of the centre',
  2668.                     'path' => 'src/Controller/RdvController.php',
  2669.                     "status" => 400,
  2670.                 ])), 400);
  2671.             }
  2672.             $rdv->setIdCentre($centre);
  2673.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  2674.             // tries to set the lieu if it's an audio indie
  2675.             $lieu $this->getDoctrine()
  2676.                 ->getRepository(Lieu::class)
  2677.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  2678.             if ($lieu == null) {
  2679.                 return new Response(json_encode(([
  2680.                     'message' => 'Error, no lieu found at this id',
  2681.                     'path' => 'src/Controller/RdvController.php',
  2682.                     "status" => 400,
  2683.                 ])), 400);
  2684.             }
  2685.             $rdv->setIdLieu($lieu);
  2686.         } else {
  2687.             return new Response(json_encode(([
  2688.                 'message' => 'Error, no lieu/centre id',
  2689.                 'path' => 'src/Controller/RdvController.php',
  2690.                 "status" => 400,
  2691.             ])), 400);
  2692.         }
  2693.         /** @var Motif */
  2694.         $motif $this->getDoctrine()
  2695.             ->getRepository(Motif::class)
  2696.             ->find($data["motif_id"]);
  2697.         if ($motif == null) {
  2698.             return new Response(json_encode(([
  2699.                 'message' => 'Error, no motif found at this id',
  2700.                 'path' => 'src/Controller/RdvController.php',
  2701.                 "status" => 400,
  2702.             ])), 400);
  2703.         }
  2704.         /** @var AudioMotif */
  2705.         $audioMotif $this->getDoctrine()
  2706.             ->getRepository(AudioMotif::class)
  2707.             ->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
  2708.         if ($audioMotif == null) {
  2709.             return new Response(json_encode(([
  2710.                 'message' => 'Error, no motif of this id found at this audio',
  2711.                 'path' => 'src/Controller/RdvController.php',
  2712.                 "status" => 400,
  2713.             ])), 400);
  2714.         }
  2715.         // remove the taken schedule by rdv to make sure there is no overlap
  2716.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  2717.         if (isset($data["note"])) {
  2718.             $rdv->setNote($data["note"]);
  2719.         }
  2720.         // test if the audio is available
  2721.         if ($audio->getIsIndie()) {
  2722.             if (isset($data["centre_id"])) {
  2723.                 if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  2724.                     return new Response(json_encode(([
  2725.                         'message' => 'Error, no horaire found for this audio',
  2726.                         'path' => 'src/Controller/RdvController.php',
  2727.                         "status" => 400,
  2728.                     ])), 400);
  2729.                 }
  2730.                 if ($publicFunction->calculScheduleFitDate($audio\DateTime::createFromFormat("d/m/Y H:i"$data["date"]), $audioMotif->getDuration(), $centre) == false) {
  2731.                     return new Response(json_encode(([
  2732.                         'message' => 'Error, no timestamp found at this time. Line n°' __LINE__,
  2733.                         'path' => 'src/Controller/RdvController.php',
  2734.                         "status" => 400,
  2735.                     ])), 400);
  2736.                 }
  2737.                 $remplacant_id $publicFunction->checkIfRemplacant($liaison->getHoraire(), $date);
  2738.             } else {
  2739.                 if ($lieu->getHoraire() == null || $lieu->getHoraire() == []) {
  2740.                     return new Response(json_encode(([
  2741.                         'message' => 'Error, no horaire found for this audio',
  2742.                         'path' => 'src/Controller/RdvController.php',
  2743.                         "status" => 400,
  2744.                     ])), 400);
  2745.                 }
  2746.                 if ($publicFunction->calculScheduleFitDate($audio\DateTime::createFromFormat("d/m/Y H:i"$data["date"]), $audioMotif->getDuration(), null$lieu) == false) {
  2747.                     return new Response(json_encode(([
  2748.                         'message' => 'Error, no timestamp found at this time. Line n°' __LINE__,
  2749.                         'path' => 'src/Controller/RdvController.php',
  2750.                         "status" => 400,
  2751.                     ])), 400);
  2752.                 }
  2753.                 $remplacant_id $publicFunction->checkIfRemplacant($lieu->getHoraire(), $date);
  2754.             }
  2755.         } else {
  2756.             if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  2757.                 return new Response(json_encode(([
  2758.                     'message' => 'Error, no horaire found for this audio',
  2759.                     'path' => 'src/Controller/RdvController.php',
  2760.                     "status" => 400,
  2761.                 ])), 400);
  2762.             }
  2763.             /*  if (!$publicFunction->calculScheduleFitDate($audio, \DateTime::createFromFormat("d/m/Y H:i", $data["date"]), $audioMotif->getDuration(), $centre))
  2764.                 return new Response(json_encode(([
  2765.                     'message' => "Error, no timestamp found at this time. Motif size: {$audioMotif->getDuration()} Line n°" . __LINE__,
  2766.                     'path' => 'src/Controller/RdvController.php',
  2767.                     "status" => 400,
  2768.                 ])), 400);*/
  2769.             $remplacant_id $publicFunction->checkIfRemplacant($liaison->getHoraire(), \DateTime::createFromFormat("d/m/Y H:i"$data["date"]));
  2770.         }
  2771.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  2772.         $existingRdv $this->getDoctrine()
  2773.             ->getRepository(Rdv::class)
  2774.             ->findOneBy([
  2775.                 'date' => $date,
  2776.                 'id_audio' => $audio,
  2777.                 'id_centre' => $rdv->getIdCentre() ?? null,
  2778.                 'id_lieu' => $rdv->getIdLieu()   ?? null,
  2779.             ]);
  2780.         if ($existingRdv) {
  2781.             return new Response(json_encode([
  2782.                 'message' => 'Un rendez-vous est déjà pris pour cette date et ce créneau.',
  2783.                 'status' => 400,
  2784.             ]), 400);
  2785.         }
  2786.         $rdv->setDate($date);
  2787.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  2788.         /** @var EtatRdv */
  2789.         $etat $this->getDoctrine()
  2790.             ->getRepository(EtatRdv::class)
  2791.             ->findOneBy(['id' => $data["etat_id"]]);
  2792.         if ($etat == null) {
  2793.             return new Response(json_encode(([
  2794.                 'message' => 'Error, no etat found at this id',
  2795.                 'path' => 'src/Controller/RdvController.php',
  2796.                 "status" => 400,
  2797.             ])), 400);
  2798.         }
  2799.         $rdv->setIdEtat($etat);
  2800.         $rdv->setIdMotif($motif);
  2801.         $rdv->setIsAbsence(0);
  2802.         $rdv->setCacher(0);
  2803.         if ($remplacant_id != -1) {
  2804.             $remplacant $this->getDoctrine()
  2805.                 ->getRepository(Remplacant::class)
  2806.                 ->find($remplacant_id);
  2807.             $rdv->setRemplacant($remplacant);
  2808.         }
  2809.         $entityManager $this->getDoctrine()->getManager();
  2810.         $entityManager->persist($rdv);
  2811.         $entityManager->flush();
  2812.         /// SMSEMAIL A décommenter pour autoriser l'envoi de sms / email à la création de rdv par l'audio / le client SMSEMAIL ///
  2813.         $date $rdv->getDate();
  2814.         $smsDate $date->format('d-m-Y H:i');
  2815.         $locale 'fr_FR';
  2816.         $formatter = new IntlDateFormatter(
  2817.             $locale,
  2818.             IntlDateFormatter::FULL,
  2819.             IntlDateFormatter::SHORT,
  2820.             null,
  2821.             IntlDateFormatter::GREGORIAN,
  2822.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  2823.         );
  2824.         $smsDateLongFormat $formatter->format($date);
  2825.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  2826.         $client->setIdCentre($rdv->getIdCentre());
  2827.         $client->setIdAudio($rdv->getIdAudio());
  2828.         $entityManager->persist($client);
  2829.         $entityManager->flush();
  2830.         // client notif mail Sms
  2831.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  2832.         $frenchDate ucfirst($frenchDate);
  2833.         $responses = [
  2834.             'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
  2835.             'situations' => (isset($data['situations']) && !empty($data['situations'])) ? implode(", "$data['situations']) : null,
  2836.             'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
  2837.             'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
  2838.             'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
  2839.             'ordonance' => isset($data['ordonnance']) ? $data['ordonnance'] : null,
  2840.             'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
  2841.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  2842.         ];
  2843.         $paramsSourceLead = [
  2844.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  2845.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  2846.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  2847.         ];
  2848.         $params = array(
  2849.             "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  2850.             "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  2851.             "date" => $smsDateLongFormat,
  2852.             "RdvDate" => $smsDateLongFormat,
  2853.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  2854.             "centerName" => $rdv->getIdCentre()->getName(),
  2855.             "prenom" => $client->getName(),
  2856.             "centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  2857.             "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  2858.             'motif' => $rdv->getIdMotif()->getTitre(),
  2859.             "centerCity" => $rdv->getIdCentre()->getCity(),
  2860.             "audioName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  2861.             'titre' => "Votre rendez-vous est validé le " substr($smsDate010) . " à "  substr($smsDate1115),
  2862.             "position" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  2863.             "address" => $rdv->getIdCentre()->getAddress(),
  2864.             "postal" => $rdv->getIdCentre()->getPostale(),
  2865.             "city" => $rdv->getIdCentre()->getCity(),
  2866.             "clientEmail" => $client->getMail(),
  2867.             "clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
  2868.             "clientAddress" => $client->getAddress(),
  2869.             "clientPostal" => $client->getPostal(),
  2870.             "clientCity" => $client->getCity(),
  2871.             "audioName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  2872.             "frenchDate" => $frenchDate,
  2873.             "heure" => substr($smsDate1115),
  2874.             "centerName" => $rdv->getIdCentre()->getName(),
  2875.             "audioMail" => $rdv->getIdAudio()->getMail(),
  2876.             "modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
  2877.         );
  2878.         $paramsPatient $params;
  2879.         $isNew false;
  2880.         if (isset($data["isLead"]) && isset($data["passwordGenerated"]) != null) {
  2881.             $subject "✅Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  2882.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject189);
  2883.             $isNew true;
  2884.         } else {
  2885.             $subject "Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  2886.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject181);
  2887.         }
  2888.         $sms "Votre RDV est validé le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  2889.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  2890.         // audio Notif mail SMS
  2891.         $birthday $rdv->getIdClient()->getBirthdate();
  2892.         $params = array(
  2893.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  2894.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  2895.             "date" => substr($smsDate010),
  2896.             "heure" => substr($smsDate1115),
  2897.             "mail" => $client->getMail(),
  2898.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  2899.             'telClient' => $client->getPhone(),
  2900.             'phone' => $client->getPhone(),
  2901.             'clientCivilite' => $client->getCivilite(),
  2902.             'clientNom' => $client->getLastname(),
  2903.             'clientPrenom' => $client->getName(),
  2904.             'clientPostal' => $client->getPostal(),
  2905.             'clientMail' => $client->getMail(),
  2906.             'clientPhone' => $client->getPhone(),
  2907.             'motif' => $rdv->getIdMotif()->getTitre(),
  2908.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  2909.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  2910.             'centerName' => $rdv->getIdCentre()->getName(),
  2911.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  2912.             'centerCity' => $rdv->getIdCentre()->getCity(),
  2913.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  2914.             'idPatient' => $client->getId(),
  2915.             'proUrl' => "{$_ENV['BASE_logiciel']}",
  2916.             'frenchDate' => $frenchDate,
  2917.             'responses' => $responses,
  2918.         );
  2919.         $templateEmail 182;
  2920.         if (!empty($data['canMove'])) {
  2921.             $templateEmail 197;
  2922.         }
  2923.         $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  2924.         $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  2925.         if ($rdv->getIdAudio()->getConfirmRdvMail()) {
  2926.             $subject "✅Nouveau Rendez-vous My Audio le " $frenchDate " à " substr($smsDate1115);
  2927.             $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject$templateEmail);
  2928.         }
  2929.         if ($rdv->getIdAudio()->getConfirmRdvSms()) {
  2930.             $sms "Vous avez un nouveau RDV le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'aléas contactez votre patient " $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  2931.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  2932.         }
  2933.         // send notif to admin
  2934.         $paramsAdmin = array(
  2935.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  2936.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  2937.             "RdvDate" => substr($smsDate010),
  2938.             "heure" => substr($smsDate1115),
  2939.             "clientMail" => $client->getMail(),
  2940.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  2941.             'telClient' => $client->getPhone(),
  2942.             'clientNom' => $client->getLastname(),
  2943.             'clientPrenom' => $client->getName(),
  2944.             'clientCivilite' => $client->getCivilite(),
  2945.             'clientPostal' => $client->getPostal(),
  2946.             'clientPhone' => $client->getPhone(),
  2947.             'motif' => $rdv->getIdMotif()->getTitre(),
  2948.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  2949.             'centerName' => $rdv->getIdCentre()->getName(),
  2950.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  2951.             'centerCity' => $rdv->getIdCentre()->getCity(),
  2952.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  2953.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  2954.             'date' => substr($smsDate010),
  2955.             'urlApi' => "{$_ENV['BASE_API']}",
  2956.             'clientId' => $client->getId(),
  2957.             'centerId' => $rdv->getIdCentre()->getId(),
  2958.             'frenchDate' => $frenchDate,
  2959.             'responses' => $responses,
  2960.             'paramsSourceLead' => $paramsSourceLead
  2961.         );
  2962.         $subject "Nouveau RDV MA | RR - " $rdv->getIdCentre()->getName();
  2963.         $templateEmail 183;
  2964.         if (!empty($data['canMove'])) {
  2965.             $templateEmail 190;
  2966.         }
  2967.         if (!isset($data["isLead"])) {
  2968.             $publicFunction->sendEmail($paramsAdmin"lead.myaudio@gmail.com""my audio"$subject$templateEmail);
  2969.         }
  2970.         //$publicFunction->sendEmail($paramsAdmin,"testpation1254@myaudio.fr","my audio", 'Nouveau RDV à My Audio Pro', $templateEmail);
  2971.         $publicFunction->sendEmail($paramsAdmin"contact@myaudio.fr""my audio"$subject$templateEmail);
  2972.         $publicFunction->sendEmail($paramsAdmin"lead.myaudio@gmail.com""my audio"$subject$templateEmail);
  2973.         // google calendar post
  2974.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  2975.             ->findBy(array('audio' => $audio->getId()));
  2976.         $data['rdv'] = $rdv->getId();
  2977.         if (isset($data['clientRdvLp']) && !empty($data['clientRdvLp'])) {
  2978.             $rdvLead $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
  2979.             if ($rdvLead) {
  2980.                 $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
  2981.                 if ($leadStatus) {
  2982.                     $rdvLead->setLeadStatus($leadStatus);
  2983.                     $rdvLead->setRdv($rdv);
  2984.                     $this->entityManager->flush();
  2985.                 }
  2986.             }
  2987.         }
  2988.         foreach ($synchronisations as $synchronisation) {
  2989.             if (!$synchronisation->getIsDeleted()) {
  2990.                 $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  2991.                 $googleCalendar->createEvent($synchronisation$data);
  2992.             }
  2993.         }
  2994.         if (isset($data["isMyaudio"]) || isset($data["isRdvLead"]) || isset($data["isRdvRapide"])) {
  2995.             try {
  2996.                 $Callservice->handleCallCenterAfterRdv(
  2997.                     $rdv
  2998.                 );
  2999.                 $rdv->setIsNotificationRdvCallSent(1);
  3000.                 $this->entityManager->flush();
  3001.             } catch (\Exception $e) {
  3002.                 $this->logger->error("Erreur lors de l'appel de notification pour le RDV #{$rdv->getId()}: " $e->getMessage());
  3003.             }
  3004.         }
  3005.         $token $this->entityManager
  3006.              ->getRepository(Token::class)
  3007.              ->findOneBy(['token' => $data['token']]);
  3008.         $tokenAudioId $token->getIdAudio()->getId();
  3009.         $requestAudioId $data['audio_id'] ?? null;
  3010.         if ($requestAudioId && $requestAudioId == $tokenAudioId) {
  3011.         // Only publish for this audio
  3012.         $this->mercure->publishRdvUpdate($rdv'created');
  3013.         }
  3014.          // Find the audio/user who owns the referral code
  3015.     $referrer $client// the user who shared the code
  3016.     // Make sure key exists
  3017.     $codeParrain $data['codeParrain'] ?? null;  // null if not provided
  3018.     if ($codeParrain) {
  3019.       // Find the new user/referee who is using the code 
  3020.       $referee $entityManager->getRepository(Client::class)->findOneBy([
  3021.           'referralCode' => $codeParrain
  3022.       ]);
  3023.     if ($referee) {
  3024.         $referral = new Referral();
  3025.         $referral->setReferrerType('patient'); 
  3026.         $referral->setReferrerId($referrer->getId()); 
  3027.         $referral->setRefereeType('patient'); 
  3028.         $referral->setRefereeId($referee->getId()); 
  3029.         $referral->setCodeUsed($codeParrain); 
  3030.         $referral->setStatus('pending');
  3031.         $referral->setRewardAmount(100); 
  3032.         $referral->setCreatedAt(new \DateTime());
  3033.         $entityManager->persist($referral);
  3034.         $entityManager->flush();
  3035.     }
  3036.     }
  3037.         return new Response(json_encode(([
  3038.             "id" => $rdv->getId(),
  3039.             "motif_id" => $rdv->getIdMotif()->getId(),
  3040.             "audio_id" => $rdv->getIdAudio()->getId(),
  3041.             "remplacant_id" => $remplacant_id == -null $remplacant_id,
  3042.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  3043.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  3044.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  3045.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  3046.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  3047.             "testclient" => $rdv->getTestClient() ? [
  3048.                 "result" => $rdv->getTestClient()->getResultTonal(),
  3049.                 "date" => $rdv->getTestClient()->getDate(),
  3050.                 "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  3051.             ] : null,
  3052.             "duration" => $audioMotif->getDuration(),
  3053.             "consigne" => $audioMotif->getConsigne(),
  3054.             "etat_id" => $rdv->getIdEtat()->getId(),
  3055.             "date" => $rdv->getDate(),
  3056.             "comment" => $rdv->getComment(),
  3057.             "centerName" => $rdv->getIdCentre()->getName(),
  3058.             "review" => $rdv->getReview(),
  3059.             "note" => $rdv->getNote(),
  3060.             "status" => 200,
  3061.             "paramsPatient" => $paramsPatient,
  3062.             "isNew" => $isNew,
  3063.         ])));
  3064.     }
  3065.     /**
  3066.      * @Route("/rdv/v2", name="postRdvV2", methods={"POST"})
  3067.      *
  3068.      * Version optimisée de la prise de rendez-vous pour les clients via le site
  3069.      * Gestion complète: validation, création RDV, notifications email/SMS
  3070.      */
  3071.     public function postRdvV2(
  3072.         Request $request,
  3073.         PublicFunction $publicFunction,
  3074.         GoogleCalendarService $googleCalendar,
  3075.         AppointmentCallService $callService
  3076.     ): JsonResponse {
  3077.         try {
  3078.             $data json_decode($request->getContent(), true);
  3079.             // Validation du token et récupération du client
  3080.             $validationResult $this->validateTokenAndGetClient($data);
  3081.             if ($validationResult instanceof Response) {
  3082.                 return new JsonResponse(json_decode($validationResult->getContent(), true), $validationResult->getStatusCode());
  3083.             }
  3084.             ['client' => $client'token' => $token] = $validationResult;
  3085.             // Récupération et validation de l'audio
  3086.             $audio $this->entityManager->getRepository(Audio::class)->find($data['audio_id'] ?? null);
  3087.             if (!$audio) {
  3088.                 return new JsonResponse([
  3089.                     'message' => "Aucun audioprothésiste trouvé avec cet ID.",
  3090.                     'status' => 404
  3091.                 ], 404);
  3092.             }
  3093.             // Vérification du blocage client
  3094.             $clientBlocked $this->entityManager->getRepository(ClientBlocked::class)
  3095.                 ->findOneBy(['id_audio' => $audio'id_client' => $client]);
  3096.             if ($clientBlocked) {
  3097.                 return new JsonResponse([
  3098.                     'message' => 'Vous avez été bloqué par cet audioprothésiste.',
  3099.                     'status' => 403
  3100.                 ], 403);
  3101.             }
  3102.             // Validation du centre/lieu
  3103.             $locationResult $this->validateLocation($data$audio);
  3104.             if ($locationResult instanceof Response) {
  3105.                 return new JsonResponse(json_decode($locationResult->getContent(), true), $locationResult->getStatusCode());
  3106.             }
  3107.             ['centre' => $centre'lieu' => $lieu'liaison' => $liaison] = $locationResult;
  3108.             // Validation du motif
  3109.             $motifResult $this->validateMotif($data$audio);
  3110.             if ($motifResult instanceof Response) {
  3111.                 return new JsonResponse(json_decode($motifResult->getContent(), true), $motifResult->getStatusCode());
  3112.             }
  3113.             ['motif' => $motif'audioMotif' => $audioMotif] = $motifResult;
  3114.             // Validation de la disponibilité
  3115.             $date \DateTime::createFromFormat("d/m/Y H:i"$data['date']);
  3116.             if (!$date) {
  3117.                 return new JsonResponse([
  3118.                     'message' => 'Format de date invalide. Utilisez le format: d/m/Y H:i',
  3119.                     'status' => 400
  3120.                 ], 400);
  3121.             }
  3122.             $availabilityResult $this->validateAvailability(
  3123.                 $audio,
  3124.                 $date,
  3125.                 $audioMotif->getDuration(),
  3126.                 $centre,
  3127.                 $lieu,
  3128.                 $liaison,
  3129.                 $publicFunction
  3130.             );
  3131.             if ($availabilityResult instanceof Response) {
  3132.                 return new JsonResponse(json_decode($availabilityResult->getContent(), true), $availabilityResult->getStatusCode());
  3133.             }
  3134.             $remplacant_id $availabilityResult;
  3135.             // Création du rendez-vous
  3136.             $rdv $this->createAppointment($data$client$audio$centre$lieu$motif$audioMotif$date$remplacant_id);
  3137.             // Envoi des notifications
  3138.             $this->sendNotifications($rdv$client$audio$publicFunction$data);
  3139.             // Synchronisation Google Calendar
  3140.             $this->syncGoogleCalendar($audio$rdv$googleCalendar$data);
  3141.             // Notification call center si nécessaire
  3142.             if (isset($data['isMyaudio']) || isset($data['isRdvLead']) || isset($data['isRdvRapide'])) {
  3143.                 try {
  3144.                     $callService->handleCallCenterAfterRdv($rdv);
  3145.                     $rdv->setIsNotificationRdvCallSent(1);
  3146.                     $this->entityManager->flush();
  3147.                 } catch (\Exception $e) {
  3148.                     $this->logger->error("Erreur notification call center RDV #{$rdv->getId()}: " $e->getMessage());
  3149.                 }
  3150.             }
  3151.             // Réponse finale
  3152.             return new JsonResponse([
  3153.                 'success' => true,
  3154.                 'message' => 'Rendez-vous créé avec succès',
  3155.                 'rdv' => [
  3156.                     'id' => $rdv->getId(),
  3157.                     'date' => $rdv->getDate()->format('d/m/Y H:i'),
  3158.                     'motif' => $motif->getTitre(),
  3159.                     'duration' => $audioMotif->getDuration(),
  3160.                     'centre' => $centre $centre->getName() : null,
  3161.                     'lieu' => $lieu $lieu->getName() : null,
  3162.                     'audio' => $audio->getName() . ' ' $audio->getLastName(),
  3163.                 ],
  3164.                 'status' => 201
  3165.             ], 201);
  3166.         } catch (\Exception $e) {
  3167.             $this->logger->error("Erreur lors de la création du RDV: " $e->getMessage());
  3168.             return new JsonResponse([
  3169.                 'success' => false,
  3170.                 'message' => 'Une erreur est survenue lors de la création du rendez-vous.',
  3171.                 'error' => $e->getMessage(),
  3172.                 'status' => 500
  3173.             ], 500);
  3174.         }
  3175.     }
  3176.     /**
  3177.      * Valide le token et récupère le client associé
  3178.      */
  3179.     private function validateTokenAndGetClient(array $data)
  3180.     {
  3181.         if (!isset($data['token'])) {
  3182.             return new Response(json_encode([
  3183.                 'message' => "Aucun token n'a été spécifié",
  3184.                 'status' => 401
  3185.             ]), 401);
  3186.         }
  3187.         $token $this->entityManager->getRepository(Token::class)
  3188.             ->findOneBy(['token' => $data['token']]);
  3189.         if (!$token) {
  3190.             return new Response(json_encode([
  3191.                 'message' => "Token invalide. Veuillez vous reconnecter.",
  3192.                 'status' => 404
  3193.             ]), 404);
  3194.         }
  3195.         // Vérification de l'âge du token
  3196.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  3197.         if ($dateDiff->7) {
  3198.             $this->entityManager->remove($token);
  3199.             $this->entityManager->flush();
  3200.             return new Response(json_encode([
  3201.                 'message' => 'Token expiré. Veuillez vous reconnecter.',
  3202.                 'status' => 401
  3203.             ]), 401);
  3204.         }
  3205.         // Récupération du client
  3206.         $client $token->getIdClient();
  3207.         if (!$client) {
  3208.             return new Response(json_encode([
  3209.                 'message' => "Ce token n'est pas associé à un client.",
  3210.                 'status' => 400
  3211.             ]), 400);
  3212.         }
  3213.         return ['client' => $client'token' => $token];
  3214.     }
  3215.     /**
  3216.      * Valide le centre ou lieu du rendez-vous
  3217.      */
  3218.     private function validateLocation(array $dataAudio $audio)
  3219.     {
  3220.         $centre null;
  3221.         $lieu null;
  3222.         $liaison null;
  3223.         if (isset($data['centre_id'])) {
  3224.             $centre $this->entityManager->getRepository(Centre::class)->find($data['centre_id']);
  3225.             if (!$centre) {
  3226.                 return new Response(json_encode([
  3227.                     'message' => 'Aucun centre trouvé avec cet ID',
  3228.                     'status' => 404
  3229.                 ]), 404);
  3230.             }
  3231.             $liaison $this->entityManager->getRepository(AudioCentre::class)
  3232.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  3233.             if (!$liaison) {
  3234.                 return new Response(json_encode([
  3235.                     'message' => "L'audioprothésiste n'est pas rattaché à ce centre",
  3236.                     'status' => 400
  3237.                 ]), 400);
  3238.             }
  3239.         } elseif (isset($data['lieu_id']) && $audio->getIsIndie()) {
  3240.             $lieu $this->entityManager->getRepository(Lieu::class)
  3241.                 ->findOneBy(['id' => $data['lieu_id'], 'id_gerant' => $audio->getId()]);
  3242.             if (!$lieu) {
  3243.                 return new Response(json_encode([
  3244.                     'message' => 'Aucun lieu trouvé avec cet ID',
  3245.                     'status' => 404
  3246.                 ]), 404);
  3247.             }
  3248.         } else {
  3249.             return new Response(json_encode([
  3250.                 'message' => 'Veuillez spécifier un centre ou un lieu',
  3251.                 'status' => 400
  3252.             ]), 400);
  3253.         }
  3254.         return ['centre' => $centre'lieu' => $lieu'liaison' => $liaison];
  3255.     }
  3256.     /**
  3257.      * Valide le motif du rendez-vous
  3258.      */
  3259.     private function validateMotif(array $dataAudio $audio)
  3260.     {
  3261.         if (!isset($data['motif_id'])) {
  3262.             return new Response(json_encode([
  3263.                 'message' => 'Aucun motif spécifié',
  3264.                 'status' => 400
  3265.             ]), 400);
  3266.         }
  3267.         $motif $this->entityManager->getRepository(Motif::class)->find($data['motif_id']);
  3268.         if (!$motif) {
  3269.             return new Response(json_encode([
  3270.                 'message' => 'Aucun motif trouvé avec cet ID',
  3271.                 'status' => 404
  3272.             ]), 404);
  3273.         }
  3274.         $audioMotif $this->entityManager->getRepository(AudioMotif::class)
  3275.             ->findOneBy(['id_audio' => $audio->getId(), 'id_motif' => $data['motif_id']]);
  3276.         if (!$audioMotif) {
  3277.             return new Response(json_encode([
  3278.                 'message' => "Ce motif n'est pas disponible pour cet audioprothésiste",
  3279.                 'status' => 400
  3280.             ]), 400);
  3281.         }
  3282.         return ['motif' => $motif'audioMotif' => $audioMotif];
  3283.     }
  3284.     /**
  3285.      * Valide la disponibilité du créneau
  3286.      */
  3287.     private function validateAvailability(
  3288.         Audio $audio,
  3289.         \DateTime $date,
  3290.         int $duration,
  3291.         ?Centre $centre,
  3292.         ?Lieu $lieu,
  3293.         ?AudioCentre $liaison,
  3294.         PublicFunction $publicFunction
  3295.     ) {
  3296.         // Vérification qu'il n'y a pas déjà un RDV à cette date
  3297.         $existingRdv $this->entityManager->getRepository(Rdv::class)
  3298.             ->findOneBy([
  3299.                 'date' => $date,
  3300.                 'id_audio' => $audio,
  3301.                 'id_centre' => $centre,
  3302.                 'id_lieu' => $lieu,
  3303.             ]);
  3304.         if ($existingRdv) {
  3305.             return new Response(json_encode([
  3306.                 'message' => 'Un rendez-vous existe déjà à ce créneau',
  3307.                 'status' => 409
  3308.             ]), 409);
  3309.         }
  3310.         // Vérification de la disponibilité selon le type d'audio
  3311.         if ($audio->getIsIndie()) {
  3312.             if ($centre && $liaison) {
  3313.                 if (!$liaison->getHoraire() || $liaison->getHoraire() == []) {
  3314.                     return new Response(json_encode([
  3315.                         'message' => 'Aucun horaire configuré pour cet audioprothésiste',
  3316.                         'status' => 400
  3317.                     ]), 400);
  3318.                 }
  3319.                 if (!$publicFunction->calculScheduleFitDate($audio$date$duration$centre)) {
  3320.                     return new Response(json_encode([
  3321.                         'message' => 'Créneau non disponible',
  3322.                         'status' => 400
  3323.                     ]), 400);
  3324.                 }
  3325.                 return $publicFunction->checkIfRemplacant($liaison->getHoraire(), $date);
  3326.             } else {
  3327.                 if (!$lieu->getHoraire() || $lieu->getHoraire() == []) {
  3328.                     return new Response(json_encode([
  3329.                         'message' => 'Aucun horaire configuré pour ce lieu',
  3330.                         'status' => 400
  3331.                     ]), 400);
  3332.                 }
  3333.                 if (!$publicFunction->calculScheduleFitDate($audio$date$durationnull$lieu)) {
  3334.                     return new Response(json_encode([
  3335.                         'message' => 'Créneau non disponible',
  3336.                         'status' => 400
  3337.                     ]), 400);
  3338.                 }
  3339.                 return $publicFunction->checkIfRemplacant($lieu->getHoraire(), $date);
  3340.             }
  3341.         } else {
  3342.             if (!$liaison || !$liaison->getHoraire() || $liaison->getHoraire() == []) {
  3343.                 return new Response(json_encode([
  3344.                     'message' => 'Aucun horaire configuré',
  3345.                     'status' => 400
  3346.                 ]), 400);
  3347.             }
  3348.             return $publicFunction->checkIfRemplacant($liaison->getHoraire(), $date);
  3349.         }
  3350.     }
  3351.     /**
  3352.      * Crée le rendez-vous en base de données
  3353.      */
  3354.     private function createAppointment(
  3355.         array $data,
  3356.         Client $client,
  3357.         Audio $audio,
  3358.         ?Centre $centre,
  3359.         ?Lieu $lieu,
  3360.         Motif $motif,
  3361.         AudioMotif $audioMotif,
  3362.         \DateTime $date,
  3363.         int $remplacant_id
  3364.     ): Rdv {
  3365.         $rdv = new Rdv();
  3366.         $rdv->setIdClient($client);
  3367.         $rdv->setIdAudio($audio);
  3368.         $rdv->setIdCentre($centre);
  3369.         $rdv->setIdLieu($lieu);
  3370.         $rdv->setIdMotif($motif);
  3371.         $rdv->setDate($date);
  3372.         $rdv->setDateCreation(new \DateTime());
  3373.         // Toujours mettre isMyaudio à true pour les RDV clients via le site
  3374.         $rdv->setIsMyaudio(true);
  3375.         $rdv->setIsRdvLp(isset($data['isRdvLead']));
  3376.         $rdv->setIsRdvRapide(isset($data['isRdvRapide']));
  3377.         $rdv->setIsAbsence(0);
  3378.         $rdv->setCacher(0);
  3379.         // Récupération du dernier test client si disponible
  3380.         $testClient $this->entityManager->getRepository(TestClient::class)
  3381.             ->getLatestTestClient($client);
  3382.         if ($testClient && !$testClient->getRdv()) {
  3383.             $rdv->setTestClient($testClient);
  3384.         }
  3385.         // Gestion proche si spécifié
  3386.         if (isset($data['proche_id'])) {
  3387.             $proche $this->entityManager->getRepository(Proches::class)
  3388.                 ->findOneBy(['id' => $data['proche_id'], 'id_client' => $client]);
  3389.             if ($proche) {
  3390.                 $rdv->setIdProche($proche);
  3391.             }
  3392.         }
  3393.         // Durée : utilise celle du motif par défaut ou celle fournie dans les données
  3394.         $rdv->setDuration($data['duree'] ?? $audioMotif->getDuration());
  3395.         // Couleur personnalisée
  3396.         if (isset($data['color'])) {
  3397.             $rdv->setColor($data['color']);
  3398.         }
  3399.         // Note
  3400.         if (isset($data['note'])) {
  3401.             $rdv->setNote($data['note']);
  3402.         }
  3403.         // État du rendez-vous
  3404.         $etat $this->entityManager->getRepository(EtatRdv::class)
  3405.             ->find($data['etat_id'] ?? 1); // État par défaut : 1
  3406.         if ($etat) {
  3407.             $rdv->setIdEtat($etat);
  3408.         }
  3409.         // Remplaçant si applicable
  3410.         if ($remplacant_id != -1) {
  3411.             $remplacant $this->entityManager->getRepository(Remplacant::class)->find($remplacant_id);
  3412.             if ($remplacant) {
  3413.                 $rdv->setRemplacant($remplacant);
  3414.             }
  3415.         }
  3416.         // Gestion lead
  3417.         if (isset($data['lead'])) {
  3418.             $lead $this->entityManager->getRepository(LeadRdv::class)->find($data['lead']);
  3419.             if ($lead) {
  3420.                 $lead->setRdv($rdv);
  3421.                 $leadStatus $this->entityManager->getRepository(LeadStatus::class)
  3422.                     ->findOneBy(['slug' => 'rdv_valider']);
  3423.                 if ($leadStatus) {
  3424.                     $lead->setLeadStatus($leadStatus);
  3425.                 }
  3426.             }
  3427.         }
  3428.         // Mise à jour du client avec centre et audio
  3429.         $client->setIdCentre($centre);
  3430.         $client->setIdAudio($audio);
  3431.         $this->entityManager->persist($client);
  3432.         $this->entityManager->persist($rdv);
  3433.         $this->entityManager->flush();
  3434.         return $rdv;
  3435.     }
  3436.     /**
  3437.      * Envoie toutes les notifications (email + SMS) au client, audio et admin
  3438.      */
  3439.     private function sendNotifications(Rdv $rdvClient $clientAudio $audioPublicFunction $publicFunction, array $data): void
  3440.     {
  3441.         $date $rdv->getDate();
  3442.         $smsDate $date->format('d-m-Y H:i');
  3443.         $formatter = new IntlDateFormatter(
  3444.             'fr_FR',
  3445.             IntlDateFormatter::FULL,
  3446.             IntlDateFormatter::SHORT,
  3447.             null,
  3448.             IntlDateFormatter::GREGORIAN,
  3449.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  3450.         );
  3451.         $smsDateLongFormat $formatter->format($date);
  3452.         $frenchDate ucfirst(preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat));
  3453.         // === Notification CLIENT ===
  3454.         $this->sendClientNotification($rdv$client$smsDate$smsDateLongFormat$frenchDate$publicFunction$data);
  3455.     
  3456.         // === Notification AUDIO ===
  3457.         if ($audio->getConfirmRdvMail() || $audio->getConfirmRdvSms()) {
  3458.             $this->sendAudioNotification($rdv$client$audio$smsDate$frenchDate$publicFunction$data);
  3459.         }
  3460.         // === Notification ADMIN ===
  3461.         $this->sendAdminNotification($rdv$client$smsDate$frenchDate$publicFunction$data);
  3462.     }
  3463.     /**
  3464.      * Envoie les notifications au client (email + SMS)
  3465.      */
  3466.     private function sendClientNotification(
  3467.         Rdv $rdv,
  3468.         Client $client,
  3469.         string $smsDate,
  3470.         string $smsDateLongFormat,
  3471.         string $frenchDate,
  3472.         PublicFunction $publicFunction,
  3473.         array $data
  3474.     ): void {
  3475.         $centre $rdv->getIdCentre();
  3476.         $params = [
  3477.             'lienModifer' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  3478.             'lienAnnule' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  3479.             'date' => $smsDateLongFormat,
  3480.             'RdvDate' => $smsDateLongFormat,
  3481.             'telCentre' => $centre->getPhone(),
  3482.             'centerName' => $centre->getName(),
  3483.             'prenom' => $client->getName(),
  3484.             'centerAddress' => $centre->getAddress() . ' ' $centre->getPostale() . ' ' $centre->getCity(),
  3485.             'centerPostalCode' => $centre->getPostale(),
  3486.             'motif' => $rdv->getIdMotif()->getTitre(),
  3487.             'centerCity' => $centre->getCity(),
  3488.             'audioName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3489.             'titre' => 'Votre rendez-vous est validé le ' substr($smsDate010) . ' à ' substr($smsDate1115),
  3490.             'frenchDate' => $frenchDate,
  3491.             'heure' => substr($smsDate1115),
  3492.             'clientEmail' => $client->getMail(),
  3493.             'clientPassword' => $data['passwordGenerated'] ?? null,
  3494.             'modifUrl' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  3495.         ];
  3496.         // Email client
  3497.         $templateId = (isset($data['isLead']) && isset($data['passwordGenerated'])) ? 189 181;
  3498.         $subject '✅ Rendez-vous My Audio confirmé le ' $smsDateLongFormat;
  3499.         $publicFunction->sendEmail(
  3500.             $params,
  3501.             $client->getMail(),
  3502.             $client->getName() . ' ' $client->getLastName(),
  3503.             $subject,
  3504.             $templateId
  3505.         );
  3506.         // envoie au personne de confiance si existe
  3507.         $trustedUser $client->getIdPersonneConfiance();
  3508.         if ($trustedUser !== null && $trustedUser->getMail()) {
  3509.           $trustedEmail $trustedUser->getMail();
  3510.           $publicFunction->sendEmail(
  3511.            $params,
  3512.            $trustedEmail,
  3513.            $trustedUser->getName(),
  3514.            $subject,
  3515.            $templateId
  3516.            );
  3517.         }
  3518.         // Envoie au proche aussi si existe
  3519.         if ($rdv->getIdProche() !== null && $rdv->getIdProche()->getMail()) {
  3520.              $proche $rdv->getIdProche();
  3521.              $procheEmail $proche->getMail();
  3522.           $publicFunction->sendEmail(
  3523.              $params,
  3524.              $procheEmail,
  3525.              $proche->getName(),
  3526.              $subject,
  3527.              $templateId
  3528.           );
  3529.         }
  3530.         // SMS client
  3531.         $smsMessage "Votre RDV est validé le " substr($smsDate010) . " à " substr($smsDate1115) .
  3532.                       ", en cas d'imprévu contactez votre centre " $centre->getPhone() .
  3533.                       " pour modifier votre consultation.\nNe pas répondre.";
  3534.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$smsMessage$client->getPhone());
  3535.     }
  3536.     /**
  3537.      * Envoie les notifications à l'audioprothésiste (email + SMS)
  3538.      */
  3539.     private function sendAudioNotification(
  3540.         Rdv $rdv,
  3541.         Client $client,
  3542.         Audio $audio,
  3543.         string $smsDate,
  3544.         string $frenchDate,
  3545.         PublicFunction $publicFunction,
  3546.         array $data
  3547.     ): void {
  3548.         $responses = [
  3549.             'rangeAge' => $data['rangeAge'] ?? null,
  3550.             'situations' => (isset($data['situations']) && !empty($data['situations'])) ? implode(", "$data['situations']) : null,
  3551.             'equipeAppareil' => $data['equipe'] ?? null,
  3552.             'durationEquipe' => $data['durationEquipe'] ?? null,
  3553.             'bilanAuditif' => $data['bilanAuditif'] ?? null,
  3554.             'ordonance' => $data['ordonnance'] ?? null,
  3555.             'dateOrdonance' => $data['dateOrdonance'] ?? null,
  3556.             'canMove' => $data['canMove'] ?? null,
  3557.         ];
  3558.         $params = [
  3559.             'lienModifer' => $_ENV['BASE_logiciel'] . 'rdv',
  3560.             'lienAnnule' => $_ENV['BASE_logiciel'] . 'rdv',
  3561.             'date' => substr($smsDate010),
  3562.             'heure' => substr($smsDate1115),
  3563.             'audioproName' => $audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastName(),
  3564.             'phone' => $client->getPhone(),
  3565.             'clientCivilite' => $client->getCivilite(),
  3566.             'clientNom' => $client->getLastname(),
  3567.             'clientPrenom' => $client->getName(),
  3568.             'clientPostal' => $client->getPostal(),
  3569.             'clientMail' => $client->getMail(),
  3570.             'clientPhone' => $client->getPhone(),
  3571.             'motif' => $rdv->getIdMotif()->getTitre(),
  3572.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  3573.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  3574.             'centerName' => $rdv->getIdCentre()->getName(),
  3575.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  3576.             'centerCity' => $rdv->getIdCentre()->getCity(),
  3577.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  3578.             'idPatient' => $client->getId(),
  3579.             'proUrl' => $_ENV['BASE_logiciel'],
  3580.             'frenchDate' => $frenchDate,
  3581.             'responses' => $responses,
  3582.         ];
  3583.         $templateEmail = !empty($data['canMove']) ? 197 182;
  3584.         $mailAudio $audio->getMailNotif() ?? $audio->getMail();
  3585.         $phoneAudio $audio->getPhoneNotif() ?? $audio->getPhone();
  3586.         // Email audio
  3587.         if ($audio->getConfirmRdvMail()) {
  3588.             $subject '✅ Nouveau Rendez-vous My Audio le ' $frenchDate ' à ' substr($smsDate1115);
  3589.             $publicFunction->sendEmail($params$mailAudio$audio->getName() . ' ' $audio->getLastName(), $subject$templateEmail);
  3590.         }
  3591.         // SMS audio
  3592.         if ($audio->getConfirmRdvSms()) {
  3593.             $smsMessage "Vous avez un nouveau RDV le " substr($smsDate010) . " à " substr($smsDate1115) .
  3594.                           ", en cas d'aléas contactez votre patient " $client->getPhone() .
  3595.                           " pour modifier votre consultation.\nNe pas répondre.";
  3596.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$smsMessage$phoneAudio);
  3597.         }
  3598.     }
  3599.     /**
  3600.      * Envoie les notifications à l'admin
  3601.      */
  3602.     private function sendAdminNotification(
  3603.         Rdv $rdv,
  3604.         Client $client,
  3605.         string $smsDate,
  3606.         string $frenchDate,
  3607.         PublicFunction $publicFunction,
  3608.         array $data
  3609.     ): void {
  3610.         $responses = [
  3611.             'rangeAge' => $data['rangeAge'] ?? null,
  3612.             'situations' => (isset($data['situations']) && !empty($data['situations'])) ? implode(", "$data['situations']) : null,
  3613.             'equipeAppareil' => $data['equipe'] ?? null,
  3614.             'durationEquipe' => $data['durationEquipe'] ?? null,
  3615.             'bilanAuditif' => $data['bilanAuditif'] ?? null,
  3616.             'ordonance' => $data['ordonnance'] ?? null,
  3617.             'dateOrdonance' => $data['dateOrdonance'] ?? null,
  3618.             'canMove' => $data['canMove'] ?? null,
  3619.         ];
  3620.         $paramsSourceLead = [
  3621.             'trafficSource' => $data['traffic_source'] ?? null,
  3622.             'articleName' => $data['article_name'] ?? null,
  3623.             'lpVersion' => $data['lp_version'] ?? null,
  3624.         ];
  3625.         $paramsAdmin = [
  3626.             'lienModifer' => $_ENV['BASE_logiciel'] . 'rdv',
  3627.             'lienAnnule' => $_ENV['BASE_logiciel'] . 'rdv',
  3628.             'RdvDate' => substr($smsDate010),
  3629.             'heure' => substr($smsDate1115),
  3630.             'clientMail' => $client->getMail(),
  3631.             'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3632.             'telClient' => $client->getPhone(),
  3633.             'clientNom' => $client->getLastname(),
  3634.             'clientPrenom' => $client->getName(),
  3635.             'clientCivilite' => $client->getCivilite(),
  3636.             'clientPostal' => $client->getPostal(),
  3637.             'clientPhone' => $client->getPhone(),
  3638.             'motif' => $rdv->getIdMotif()->getTitre(),
  3639.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  3640.             'centerName' => $rdv->getIdCentre()->getName(),
  3641.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  3642.             'centerCity' => $rdv->getIdCentre()->getCity(),
  3643.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  3644.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  3645.             'date' => substr($smsDate010),
  3646.             'urlApi' => $_ENV['BASE_API'],
  3647.             'clientId' => $client->getId(),
  3648.             'centerId' => $rdv->getIdCentre()->getId(),
  3649.             'frenchDate' => $frenchDate,
  3650.             'responses' => $responses,
  3651.             'paramsSourceLead' => $paramsSourceLead,
  3652.         ];
  3653.         $subject 'Nouveau RDV MA | RR - ' $rdv->getIdCentre()->getName();
  3654.         $templateEmail = !empty($data['canMove']) ? 190 183;
  3655.         if (!isset($data['isLead'])) {
  3656.             $publicFunction->sendEmail($paramsAdmin'lead.myaudio@gmail.com''my audio'$subject$templateEmail);
  3657.         }
  3658.         $publicFunction->sendEmail($paramsAdmin'contact@myaudio.fr''my audio'$subject$templateEmail);
  3659.     }
  3660.     /**
  3661.      * Synchronise le rendez-vous avec Google Calendar
  3662.      */
  3663.     private function syncGoogleCalendar(Audio $audioRdv $rdvGoogleCalendarService $googleCalendar, array $data): void
  3664.     {
  3665.         try {
  3666.             $synchronisations $this->entityManager->getRepository(SynchronisationSetting::class)
  3667.                 ->findBy(['audio' => $audio->getId()]);
  3668.             $data['rdv'] = $rdv->getId();
  3669.             foreach ($synchronisations as $synchronisation) {
  3670.                 if (!$synchronisation->getIsDeleted()) {
  3671.                     $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  3672.                     $googleCalendar->createEvent($synchronisation$data);
  3673.                 }
  3674.             }
  3675.         } catch (\Exception $e) {
  3676.             $this->logger->error("Erreur synchronisation Google Calendar pour RDV #{$rdv->getId()}: " $e->getMessage());
  3677.         }
  3678.     }
  3679.     /**
  3680.      * @Route("/rdv/{id}/v2", name="getRdvByIDV2", methods={"GET"})
  3681.      *
  3682.      * Version optimisée de getRdvByID
  3683.      * Retourne les informations complètes d'un rendez-vous
  3684.      */
  3685.     public function getRdvByIDV2(int $idRequest $requestPublicFunction $publicFunction): JsonResponse
  3686.     {
  3687.         try {
  3688.             // Validation du token
  3689.             $token $request->query->get('token');
  3690.             if (!$token) {
  3691.                 return new JsonResponse([
  3692.                     'message' => "Aucun token n'a été spécifié",
  3693.                     'status' => 401
  3694.                 ], 401);
  3695.             }
  3696.             $tokenEntity $this->entityManager->getRepository(Token::class)
  3697.                 ->findOneBy(['token' => $token]);
  3698.             if (!$tokenEntity) {
  3699.                 return new JsonResponse([
  3700.                     'message' => "Token invalide. Veuillez vous reconnecter.",
  3701.                     'status' => 404
  3702.                 ], 404);
  3703.             }
  3704.             // Vérification de l'âge du token
  3705.             $dateDiff $tokenEntity->getCreationDate()->diff(new DateTime());
  3706.             if ($dateDiff->7) {
  3707.                 $this->entityManager->remove($tokenEntity);
  3708.                 $this->entityManager->flush();
  3709.                 return new JsonResponse([
  3710.                     'message' => 'Token expiré. Veuillez vous reconnecter.',
  3711.                     'status' => 401
  3712.                 ], 401);
  3713.             }
  3714.             // Récupération du RDV
  3715.             $rdv $this->entityManager->getRepository(Rdv::class)->find($id);
  3716.             if (!$rdv) {
  3717.                 return new JsonResponse([
  3718.                     'message' => "Aucun rendez-vous trouvé avec cet ID",
  3719.                     'status' => 404
  3720.                 ], 404);
  3721.             }
  3722.             // Vérification des droits d'accès
  3723.             $client $tokenEntity->getIdClient();
  3724.             $audio $tokenEntity->getIdAudio();
  3725.             if ($rdv->getIdClient() != $client && $rdv->getIdAudio() != $audio) {
  3726.                 return new JsonResponse([
  3727.                     'message' => "Vous n'êtes pas autorisé à consulter ce rendez-vous",
  3728.                     'status' => 403
  3729.                 ], 403);
  3730.             }
  3731.             // Construction de la réponse
  3732.             $response $this->buildRdvResponse($rdv$publicFunction);
  3733.             return new JsonResponse([
  3734.                 'success' => true,
  3735.                 'rdv' => $response,
  3736.                 'status' => 200
  3737.             ], 200);
  3738.         } catch (\Exception $e) {
  3739.             $this->logger->error("Erreur lors de la récupération du RDV #{$id}: " $e->getMessage());
  3740.             return new JsonResponse([
  3741.                 'success' => false,
  3742.                 'message' => 'Une erreur est survenue lors de la récupération du rendez-vous.',
  3743.                 'error' => $e->getMessage(),
  3744.                 'status' => 500
  3745.             ], 500);
  3746.         }
  3747.     }
  3748.     /**
  3749.      * Construit la réponse complète pour un rendez-vous
  3750.      */
  3751.     private function buildRdvResponse(Rdv $rdvPublicFunction $publicFunction): array
  3752.     {
  3753.         $rdvCentre $rdv->getIdLieu() ?: $rdv->getIdCentre();
  3754.         $audio $rdv->getIdAudio();
  3755.         $centre $rdv->getIdCentre();
  3756.         // Récupération de la liaison audio-centre
  3757.         $liaison null;
  3758.         if ($centre) {
  3759.             $liaison $this->entityManager->getRepository(AudioCentre::class)
  3760.                 ->findOneBy(['id_audio' => $audio'id_centre' => $centre'isConfirmed' => true]);
  3761.         }
  3762.         // Informations de base du RDV
  3763.         $rdvData = [
  3764.             'id' => $rdv->getId(),
  3765.             'date' => $rdv->getDate()->format('Y-m-d H:i:s'),
  3766.             'dateCreation' => $rdv->getDateCreation() ? $rdv->getDateCreation()->format('Y-m-d H:i:s') : null,
  3767.             'duration' => $rdv->getDuration(),
  3768.             'note' => $rdv->getNote(),
  3769.             'comment' => $rdv->getComment(),
  3770.             'review' => $rdv->getReview(),
  3771.             'isMyaudio' => $rdv->getIsMyaudio(),
  3772.             'isRdvLp' => $rdv->getIsRdvLp(),
  3773.             'isRdvRapide' => $rdv->getIsRdvRapide(),
  3774.             'isAbsence' => $rdv->getIsAbsence(),
  3775.             'motif' => [
  3776.                 'id' => $rdv->getIdMotif()->getId(),
  3777.                 'titre' => $rdv->getIdMotif()->getTitre(),
  3778.             ],
  3779.             'etat' => [
  3780.                 'id' => $rdv->getIdEtat()->getId(),
  3781.                 'libelle' => $rdv->getIdEtat()->getLibelle(),
  3782.             ],
  3783.             'client' => $this->buildClientData($rdv),
  3784.             'proche' => $rdv->getIdProche() ? [
  3785.                 'id' => $rdv->getIdProche()->getId(),
  3786.                 'name' => $rdv->getIdProche()->getName(),
  3787.                 'lastname' => $rdv->getIdProche()->getLastname(),
  3788.             ] : null,
  3789.             'testClient' => $rdv->getTestClient() ? [
  3790.                 'result' => $rdv->getTestClient()->getResultTonal(),
  3791.                 'date' => $rdv->getTestClient()->getDate()->format('Y-m-d H:i:s'),
  3792.                 'device' => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  3793.             ] : null,
  3794.             'audio' => $this->buildAudioData($rdv$publicFunction),
  3795.             'centre' => $this->buildCentreData($rdv$rdvCentre$liaison$publicFunction),
  3796.             'remplacant' => $rdv->getRemplacant() ? [
  3797.                 'id' => $rdv->getRemplacant()->getId(),
  3798.                 'civilite' => $rdv->getRemplacant()->getCivilite(),
  3799.                 'name' => $rdv->getRemplacant()->getName(),
  3800.                 'lastname' => $rdv->getRemplacant()->getLastname(),
  3801.                 'imgUrl' => $rdv->getRemplacant()->getImgUrl(),
  3802.             ] : null,
  3803.         ];
  3804.         return $rdvData;
  3805.     }
  3806.     /**
  3807.      * Construit les données du client
  3808.      */
  3809.     private function buildClientData(Rdv $rdv): ?array
  3810.     {
  3811.         $client $rdv->getIdClient() ?: $rdv->getIdClientTemp();
  3812.         if (!$client) {
  3813.             return null;
  3814.         }
  3815.         return [
  3816.             'id' => $client->getId(),
  3817.             'civilite' => $client->getCivilite(),
  3818.             'name' => $client->getName(),
  3819.             'lastname' => $client->getLastname(),
  3820.             'mail' => $client->getMail(),
  3821.             'phone' => $client->getPhone(),
  3822.             'address' => $client->getAddress(),
  3823.             'postal' => $client->getPostal(),
  3824.             'city' => $client->getCity(),
  3825.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format('Y-m-d') : null,
  3826.         ];
  3827.     }
  3828.     /**
  3829.      * Construit les données de l'audio
  3830.      */
  3831.     private function buildAudioData(Rdv $rdvPublicFunction $publicFunction): array
  3832.     {
  3833.         $audio $rdv->getIdAudio();
  3834.         $remplacant $rdv->getRemplacant();
  3835.         // Récupération des reviews audio
  3836.         $audioRdvs $this->entityManager->getRepository(Rdv::class)
  3837.             ->findBy(['id_audio' => $audio->getId()]);
  3838.         $reviewsAudio array_filter($audioRdvs, function($r) {
  3839.             return $r->getReview() !== null && $r->getComment() !== null;
  3840.         });
  3841.         // Motifs
  3842.         $motifs $this->entityManager->getRepository(AudioMotif::class)
  3843.             ->findBy(['id_audio' => $audio->getId()]);
  3844.         $motifsData array_map(function($motif) {
  3845.             return [
  3846.                 'id' => $motif->getIdMotif()->getId(),
  3847.                 'titre' => $motif->getIdMotif()->getTitre(),
  3848.                 'consigne' => $motif->getConsigne(),
  3849.                 'duration' => $motif->getDuration(),
  3850.             ];
  3851.         }, $motifs);
  3852.         // Spécialités
  3853.         $specialities $this->entityManager->getRepository(AudioSpecialite::class)
  3854.             ->findBy(['id_audio' => $audio->getId()]);
  3855.         $specialitiesData array_map(function($spec) {
  3856.             return [
  3857.                 'id' => $spec->getIdSpecialite()->getId(),
  3858.                 'titre' => $spec->getIdSpecialite()->getLibelle(),
  3859.             ];
  3860.         }, $specialities);
  3861.         return [
  3862.             'id' => $remplacant $remplacant->getId() : $audio->getId(),
  3863.             'civilite' => $remplacant $remplacant->getCivilite() : $audio->getCivilite(),
  3864.             'name' => $remplacant $remplacant->getName() : $audio->getName(),
  3865.             'lastname' => $remplacant $remplacant->getLastname() : $audio->getLastname(),
  3866.             'imgUrl' => $remplacant $remplacant->getImgUrl() : $audio->getImgUrl(),
  3867.             'mail' => $remplacant $remplacant->getMail() : $audio->getMail(),
  3868.             'phone' => $remplacant $remplacant->getPhone() : $audio->getPhone(),
  3869.             'adeli' => $audio->getAdeli(),
  3870.             'pin' => $audio->getPin(),
  3871.             'description' => $audio->getDescription(),
  3872.             'averageRating' => $publicFunction->calculateRating($reviewsAudio),
  3873.             'nbrReview' => count($reviewsAudio),
  3874.             'motifs' => array_values($motifsData),
  3875.             'specialities' => array_values($specialitiesData),
  3876.         ];
  3877.     }
  3878.     /**
  3879.      * Construit les données du centre
  3880.      */
  3881.     private function buildCentreData(Rdv $rdv$rdvCentre, ?AudioCentre $liaisonPublicFunction $publicFunction): array
  3882.     {
  3883.         // Récupération des reviews centre
  3884.         $centreRdvs $this->entityManager->getRepository(Rdv::class)
  3885.             ->findBy($rdv->getIdCentre() ? ['id_centre' => $rdvCentre->getId()] : ['id_lieu' => $rdvCentre->getId()]);
  3886.         $reviewsCentre array_filter($centreRdvs, function($r) {
  3887.             return $r->getReview() !== null && $r->getComment() !== null;
  3888.         });
  3889.         // Accès centre
  3890.         $accessCentre $this->entityManager->getRepository(AccessCentre::class)
  3891.             ->findOneBy($rdv->getIdCentre() ? ['id_centre' => $rdvCentre] : ['id_lieu' => $rdvCentre]);
  3892.         // Prestations
  3893.         if ($rdv->getIdCentre()) {
  3894.             $prestations $this->entityManager->getRepository(CentrePrestation::class)
  3895.                 ->findBy(['id_centre' => $rdvCentre->getId()]);
  3896.         } else {
  3897.             $prestations $this->entityManager->getRepository(LieuPrestation::class)
  3898.                 ->findBy(['id_lieu' => $rdvCentre]);
  3899.         }
  3900.         $prestationsData array_map(function($prest) {
  3901.             return [
  3902.                 'id' => $prest->getIdPrestation()->getId(),
  3903.                 'titre' => $prest->getIdPrestation()->getLibelle(),
  3904.             ];
  3905.         }, $prestations);
  3906.         // Mutuelles (uniquement pour centres)
  3907.         $mutuellesData = [];
  3908.         if ($rdv->getIdCentre()) {
  3909.             $mutuelles $this->entityManager->getRepository(CentreMutuelle::class)
  3910.                 ->findBy(['id_centre' => $rdvCentre]);
  3911.             $mutuellesData array_map(function($mut) {
  3912.                 return [
  3913.                     'id' => $mut->getIdMutuelle()->getId(),
  3914.                     'titre' => $mut->getIdMutuelle()->getLibelle(),
  3915.                 ];
  3916.             }, $mutuelles);
  3917.         }
  3918.         // Tiers
  3919.         if ($rdv->getIdCentre()) {
  3920.             $tiers $this->entityManager->getRepository(CentreTier::class)
  3921.                 ->findBy(['id_centre' => $rdvCentre->getId()]);
  3922.         } else {
  3923.             $tiers $this->entityManager->getRepository(LieuTier::class)
  3924.                 ->findBy(['id_lieu' => $rdvCentre]);
  3925.         }
  3926.         $tiersData array_map(function($tier) {
  3927.             return [
  3928.                 'id' => $tier->getIdTier()->getId(),
  3929.                 'titre' => $tier->getIdTier()->getLibelle(),
  3930.             ];
  3931.         }, $tiers);
  3932.         // Horaire
  3933.         $schedule null;
  3934.         if ($rdv->getIdAudio()->getIsIndie() == false) {
  3935.             $schedule $rdv->getIdCentre() ? $rdv->getIdCentre()->getHoraire() : null;
  3936.         } else {
  3937.             $schedule $rdv->getIdLieu() ? $rdv->getIdLieu()->getHoraire() : ($liaison $liaison->getHoraire() : null);
  3938.         }
  3939.         return [
  3940.             'id' => $rdvCentre->getId(),
  3941.             'audio_id' => $rdvCentre->getIdGerant()->getId(),
  3942.             'name' => $rdvCentre->getName(),
  3943.             'imgUrl' => $rdvCentre->getImgUrl(),
  3944.             'isRdvDomicile' => $rdv->getIdCentre() ? $rdvCentre->getIsRdvDomicile() : $rdv->getIdAudio()->getIsRdvDomicileIndie(),
  3945.             'address' => $rdvCentre->getAddress(),
  3946.             'postal' => $rdvCentre->getPostale(),
  3947.             'city' => $rdvCentre->getCity(),
  3948.             'finess' => $rdvCentre->getFiness(),
  3949.             'siret' => $rdvCentre->getSiret(),
  3950.             'website' => $rdvCentre->getWebsite(),
  3951.             'phone' => $rdvCentre->getPhone(),
  3952.             'isHandicap' => $rdvCentre->getIsHandicap(),
  3953.             'longitude' => $rdvCentre->getLongitude(),
  3954.             'latitude' => $rdvCentre->getLatitude(),
  3955.             'description' => $rdv->getIdCentre() ? $rdv->getIdCentre()->getDescription() : null,
  3956.             'averageRating' => $publicFunction->calculateRating($reviewsCentre),
  3957.             'nbrReview' => count($reviewsCentre),
  3958.             'isLieu' => $rdv->getIdLieu() !== null,
  3959.             'schedule' => $schedule,
  3960.             'access' => $accessCentre ? [
  3961.                 'tram' => $accessCentre->getTram(),
  3962.                 'rer' => $accessCentre->getRer(),
  3963.                 'metro' => $accessCentre->getMetro(),
  3964.                 'bus' => $accessCentre->getBus(),
  3965.                 'parkingPublic' => $accessCentre->getParkingPublic(),
  3966.                 'parkingPrivate' => $accessCentre->getParkingPrivate(),
  3967.                 'other' => $accessCentre->getOther(),
  3968.             ] : null,
  3969.             'prestations' => array_values($prestationsData),
  3970.             'mutuelles' => array_values($mutuellesData),
  3971.             'tiers' => array_values($tiersData),
  3972.         ];
  3973.     }
  3974.     /**
  3975.      * @Route("/rdv/{id}/v2", name="editRdvByIDV2", methods={"PUT", "PATCH"})
  3976.      *
  3977.      * Version optimisée de editRdvByID pour les clients
  3978.      * Gestion complète: modification RDV, notifications email/SMS, Google Calendar
  3979.      */
  3980.     public function editRdvByIDV2(
  3981.         int $id,
  3982.         Request $request,
  3983.         PublicFunction $publicFunction,
  3984.         GoogleCalendarService $googleCalendar
  3985.     ): JsonResponse {
  3986.         try {
  3987.             $data json_decode($request->getContent(), true);
  3988.             // Validation du token et récupération du client
  3989.             $validationResult $this->validateTokenAndGetClient($data);
  3990.             if ($validationResult instanceof Response) {
  3991.                 return new JsonResponse(json_decode($validationResult->getContent(), true), $validationResult->getStatusCode());
  3992.             }
  3993.             ['client' => $client] = $validationResult;
  3994.             // Récupération du RDV
  3995.             $rdv $this->entityManager->getRepository(Rdv::class)->find($id);
  3996.             if (!$rdv) {
  3997.                 return new JsonResponse([
  3998.                     'message' => "Aucun rendez-vous trouvé avec cet ID",
  3999.                     'status' => 404
  4000.                 ], 404);
  4001.             }
  4002.             // Vérification des droits (seulement le client peut modifier son RDV)
  4003.             if ($rdv->getIdClient() != $client) {
  4004.                 return new JsonResponse([
  4005.                     'message' => "Vous n'êtes pas autorisé à modifier ce rendez-vous",
  4006.                     'status' => 403
  4007.                 ], 403);
  4008.             }
  4009.             // Sauvegarde des anciennes valeurs pour les notifications
  4010.             $oldDate $rdv->getDate();
  4011.             $oldDuration $rdv->getDuration();
  4012.             // Traitement de la modification
  4013.             $isModified false;
  4014.             $isCancelled false;
  4015.             // Modification de la date
  4016.             if (isset($data['date'])) {
  4017.                 $newDate \DateTime::createFromFormat("d/m/Y H:i"$data['date']);
  4018.                 if (!$newDate) {
  4019.                     return new JsonResponse([
  4020.                         'message' => 'Format de date invalide. Utilisez le format: d/m/Y H:i',
  4021.                         'status' => 400
  4022.                     ], 400);
  4023.                 }
  4024.                 // Vérification de la disponibilité
  4025.                 $audioMotif $this->entityManager->getRepository(AudioMotif::class)
  4026.                     ->findOneBy(['id_audio' => $rdv->getIdAudio(), 'id_motif' => $rdv->getIdMotif()]);
  4027.                 if (!$audioMotif) {
  4028.                     return new JsonResponse([
  4029.                         'message' => "Le motif n'est plus disponible pour cet audioprothésiste",
  4030.                         'status' => 400
  4031.                     ], 400);
  4032.                 }
  4033.                 // Vérification qu'il n'y a pas déjà un RDV à cette nouvelle date
  4034.                 $existingRdv $this->entityManager->getRepository(Rdv::class)
  4035.                     ->findOneBy([
  4036.                         'date' => $newDate,
  4037.                         'id_audio' => $rdv->getIdAudio(),
  4038.                         'id_centre' => $rdv->getIdCentre(),
  4039.                         'id_lieu' => $rdv->getIdLieu(),
  4040.                     ]);
  4041.                 if ($existingRdv && $existingRdv->getId() !== $rdv->getId()) {
  4042.                     return new JsonResponse([
  4043.                         'message' => 'Un rendez-vous existe déjà à ce créneau',
  4044.                         'status' => 409
  4045.                     ], 409);
  4046.                 }
  4047.                 $rdv->setDateOldRdv($oldDate);
  4048.                 $rdv->setDate($newDate);
  4049.                 $isModified true;
  4050.             }
  4051.             // Modification de la durée
  4052.             if (isset($data['duree']) && $data['duree'] !== $oldDuration) {
  4053.                 $rdv->setDuration($data['duree']);
  4054.                 $isModified true;
  4055.             }
  4056.             // Modification de la note
  4057.             if (isset($data['note'])) {
  4058.                 $rdv->setNote($data['note']);
  4059.             }
  4060.             // Gestion de l'annulation (état 2 = annulé)
  4061.             if (isset($data['etat_id']) && $data['etat_id'] == 2) {
  4062.                 $etat $this->entityManager->getRepository(EtatRdv::class)->find(2);
  4063.                 if ($etat) {
  4064.                     $rdv->setIdEtat($etat);
  4065.                     $isCancelled true;
  4066.                     // Suppression des événements Google Calendar
  4067.                     $this->deleteGoogleCalendarEvents($rdv$googleCalendar);
  4068.                 }
  4069.             }
  4070.             // Persistance des modifications
  4071.             $rdv->setGoogleAgendaImported(false);
  4072.             $this->entityManager->flush();
  4073.             // Envoi des notifications
  4074.             if ($isModified && !$isCancelled) {
  4075.                 $this->sendModificationNotifications($rdv$client$oldDate$publicFunction$data);
  4076.                 $this->updateGoogleCalendarEvents($rdv$googleCalendar$data);
  4077.             } elseif ($isCancelled) {
  4078.                 $this->sendCancellationNotifications($rdv$client$publicFunction$data);
  4079.             }
  4080.             // Réponse
  4081.             return new JsonResponse([
  4082.                 'success' => true,
  4083.                 'message' => $isCancelled 'Rendez-vous annulé avec succès' 'Rendez-vous modifié avec succès',
  4084.                 'rdv' => [
  4085.                     'id' => $rdv->getId(),
  4086.                     'date' => $rdv->getDate()->format('Y-m-d H:i:s'),
  4087.                     'duration' => $rdv->getDuration(),
  4088.                     'note' => $rdv->getNote(),
  4089.                     'etat' => [
  4090.                         'id' => $rdv->getIdEtat()->getId(),
  4091.                         'libelle' => $rdv->getIdEtat()->getLibelle(),
  4092.                     ],
  4093.                 ],
  4094.                 'status' => 200
  4095.             ], 200);
  4096.         } catch (\Exception $e) {
  4097.             $this->logger->error("Erreur lors de la modification du RDV #{$id}: " $e->getMessage());
  4098.             return new JsonResponse([
  4099.                 'success' => false,
  4100.                 'message' => 'Une erreur est survenue lors de la modification du rendez-vous.',
  4101.                 'error' => $e->getMessage(),
  4102.                 'status' => 500
  4103.             ], 500);
  4104.         }
  4105.     }
  4106.     /**
  4107.      * Envoie les notifications de modification de RDV
  4108.      */
  4109.     private function sendModificationNotifications(
  4110.         Rdv $rdv,
  4111.         Client $client,
  4112.         \DateTime $oldDate,
  4113.         PublicFunction $publicFunction,
  4114.         array $data
  4115.     ): void {
  4116.         $date $rdv->getDate();
  4117.         $smsDate $date->format('d-m-Y H:i');
  4118.         $formatter = new IntlDateFormatter(
  4119.             'fr_FR',
  4120.             IntlDateFormatter::FULL,
  4121.             IntlDateFormatter::SHORT,
  4122.             null,
  4123.             IntlDateFormatter::GREGORIAN,
  4124.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  4125.         );
  4126.         $smsDateLongFormat $formatter->format($date);
  4127.         $frenchDate ucfirst(preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat));
  4128.         // Notification CLIENT
  4129.         $paramsClient = [
  4130.             'lienModifer' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  4131.             'lienAnnule' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  4132.             'date' => $smsDateLongFormat,
  4133.             'heure' => substr($smsDate1115),
  4134.             'motif' => $rdv->getIdMotif()->getTitre(),
  4135.             'centerName' => $rdv->getIdCentre()->getName(),
  4136.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4137.             'centerPostalCode' => $rdv->getIdCentre()->getPostale(),
  4138.             'audioMail' => $rdv->getIdAudio()->getMail(),
  4139.             'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4140.             'centerCity' => $rdv->getIdCentre()->getCity(),
  4141.             'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4142.             'titre' => 'Votre rendez-vous est modifié pour le',
  4143.             'frenchDate' => $frenchDate,
  4144.         ];
  4145.         $subject "🔀 Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  4146.         $publicFunction->sendEmail(
  4147.             $paramsClient,
  4148.             $client->getMail(),
  4149.             $client->getName() . ' ' $client->getLastName(),
  4150.             $subject,
  4151.             184
  4152.         );
  4153.         // envoie au personne de confiance si existe
  4154.         $trustedUser $client->getIdPersonneConfiance();
  4155.         if ($trustedUser !== null && $trustedUser->getMail()) {
  4156.           $trustedEmail $trustedUser->getMail();
  4157.           $publicFunction->sendEmail(
  4158.            $paramsClient,
  4159.            $trustedEmail,
  4160.            $trustedUser->getName(),
  4161.            $subject,
  4162.            184
  4163.            );
  4164.         }
  4165.         // Envoie au proche aussi si existe
  4166.         if ($rdv->getIdProche() !== null && $rdv->getIdProche()->getMail()) {
  4167.              $proche $rdv->getIdProche();
  4168.              $procheEmail $proche->getMail();
  4169.           $publicFunction->sendEmail(
  4170.              $paramsClient,
  4171.              $procheEmail,
  4172.              $proche->getName(),
  4173.              $subject,
  4174.              184
  4175.           );
  4176.         }
  4177.         // SMS client si demandé
  4178.         //if (isset($data['sms']) && $data['sms']) {
  4179.             $smsMessage "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) .
  4180.                           ", en cas d'imprévu contactez votre centre " $rdv->getIdCentre()->getPhone() .
  4181.                           " pour modifier votre consultation.\nNe pas répondre.";
  4182.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$smsMessage$client->getPhone());
  4183.         //}
  4184.         // Notification AUDIO
  4185.         $audio $rdv->getIdAudio();
  4186.         if ($audio->getModifRdvMail() || $audio->getModifRdvSms()) {
  4187.             $paramsAudio = [
  4188.                 'lienModifer' => $_ENV['BASE_logiciel'] . 'rdv',
  4189.                 'lienAnnule' => $_ENV['BASE_logiciel'] . 'rdv',
  4190.                 'date' => substr($smsDate010),
  4191.                 'frenchDate' => $frenchDate,
  4192.                 'heure' => substr($smsDate1115),
  4193.                 'motif' => $rdv->getIdMotif()->getTitre(),
  4194.                 'clientPhone' => $client->getPhone(),
  4195.                 'clientNom' => $client->getLastname(),
  4196.                 'clientPrenom' => $client->getName(),
  4197.                 'clientCivilite' => $client->getCivilite(),
  4198.                 'clientPostal' => $client->getPostal(),
  4199.                 'clientMail' => $client->getMail(),
  4200.                 'centerName' => $rdv->getIdCentre()->getName(),
  4201.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4202.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  4203.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4204.                 'idPatient' => $client->getId(),
  4205.                 'proUrl' => $_ENV['BASE_logiciel'],
  4206.                 'audioproName' => $audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastName(),
  4207.                 'titre' => 'Votre rendez-vous est modifié pour le :'
  4208.             ];
  4209.             $mailAudio $audio->getMailNotif() ?? $audio->getMail();
  4210.             if ($audio->getModifRdvMail()) {
  4211.                 $subjectAudio "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  4212.                 $publicFunction->sendEmail($paramsAudio$mailAudio$audio->getName() . ' ' $audio->getLastName(), $subjectAudio186);
  4213.             }
  4214.         }
  4215.     }
  4216.     /**
  4217.      * Envoie les notifications d'annulation de RDV
  4218.      */
  4219.     private function sendCancellationNotifications(
  4220.         Rdv $rdv,
  4221.         Client $client,
  4222.         PublicFunction $publicFunction,
  4223.         array $data
  4224.     ): void {
  4225.         $date $rdv->getDate();
  4226.         $smsDate $date->format('d-m-Y H:i');
  4227.         // Notification CLIENT
  4228.         $paramsClient = [
  4229.             'date' => substr($smsDate010),
  4230.             'lien' => $_ENV['BASE_client'] . 'search',
  4231.             'heure' => substr($smsDate1115),
  4232.             'patientName' => $client->getLastName(),
  4233.             'titre' => 'Votre rendez-vous est annulé :',
  4234.             'centerName' => $rdv->getIdCentre()->getName(),
  4235.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4236.             'centerCity' => $rdv->getIdCentre()->getCity(),
  4237.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4238.             'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4239.             'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4240.             'audioMail' => $rdv->getIdAudio()->getMail(),
  4241.             'motif' => $rdv->getIdMotif()->getTitre(),
  4242.         ];
  4243.         $subject "❌ Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  4244.         $publicFunction->sendEmail($paramsClient$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  4245.         // SMS client si demandé
  4246.         //if (isset($data['sms']) && $data['sms']) {
  4247.             $smsMessage "Votre RDV a été annulé, contactez votre centre " $rdv->getIdCentre()->getPhone() .
  4248.                           " pour prendre un autre RDV.\nNe pas répondre.";
  4249.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$smsMessage$client->getPhone());
  4250.        // }
  4251.         // Notification AUDIO
  4252.         $audio $rdv->getIdAudio();
  4253.         if ($audio->getModifRdvMail()) {
  4254.             $paramsAudio = [
  4255.                 'date' => substr($smsDate010),
  4256.                 'lien' => $_ENV['BASE_client'] . 'search',
  4257.                 'heure' => substr($smsDate1115),
  4258.                 'patientName' => $client->getLastName(),
  4259.                 'titre' => 'Votre rendez-vous est annulé :',
  4260.                 'centerName' => $rdv->getIdCentre()->getName(),
  4261.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4262.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  4263.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4264.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4265.                 'audioproName' => $audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastName(),
  4266.                 'audioMail' => $audio->getMail(),
  4267.                 'motif' => $rdv->getIdMotif()->getTitre(),
  4268.             ];
  4269.             $mailAudio $audio->getMailNotif() ?? $audio->getMail();
  4270.             $subjectAudio "❌ Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  4271.             $publicFunction->sendEmail($paramsAudio$mailAudio$audio->getName() . ' ' $audio->getLastName(), $subjectAudio188);
  4272.         }
  4273.     }
  4274.     /**
  4275.      * Supprime les événements Google Calendar associés au RDV
  4276.      */
  4277.     private function deleteGoogleCalendarEvents(Rdv $rdvGoogleCalendarService $googleCalendar): void
  4278.     {
  4279.         try {
  4280.             $rdvEvents $this->entityManager->getRepository(RdvEvent::class)
  4281.                 ->findBy(['rdv' => $rdv]);
  4282.             foreach ($rdvEvents as $rdvEvent) {
  4283.                 $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4284.                 $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  4285.                 $this->entityManager->remove($rdvEvent);
  4286.             }
  4287.             $this->entityManager->flush();
  4288.         } catch (\Exception $e) {
  4289.             $this->logger->error("Erreur suppression événements Google Calendar pour RDV #{$rdv->getId()}: " $e->getMessage());
  4290.         }
  4291.     }
  4292.     /**
  4293.      * Met à jour les événements Google Calendar
  4294.      */
  4295.     private function updateGoogleCalendarEvents(Rdv $rdvGoogleCalendarService $googleCalendar, array $data): void
  4296.     {
  4297.         try {
  4298.             $rdvEvents $this->entityManager->getRepository(RdvEvent::class)
  4299.                 ->findBy(['rdv' => $rdv]);
  4300.             $data['rdv'] = $rdv->getId();
  4301.             if ($rdv->getIdClient() !== null) {
  4302.                 $data['client_id'] = $rdv->getIdClient()->getId();
  4303.             }
  4304.             foreach ($rdvEvents as $rdvEvent) {
  4305.                 $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4306.                 $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  4307.             }
  4308.         } catch (\Exception $e) {
  4309.             $this->logger->error("Erreur mise à jour événements Google Calendar pour RDV #{$rdv->getId()}: " $e->getMessage());
  4310.         }
  4311.     }
  4312.     /**
  4313.      * @Route("/rdv/{id}/trusteduser", name="contactTrustedUser", methods={"POST"})
  4314.      */
  4315.     public function contactTrustedUser(Request $requestPublicFunction $publicFunction)
  4316.     {
  4317.         $pastDate $rdv->getDate();
  4318.         $data json_decode($request->getContent(), true);
  4319.         $entityManager $this->getDoctrine()->getManager();
  4320.         if (!isset($data["token"])) {
  4321.             return new Response(json_encode([
  4322.                 "message" => "Pas de token n'a été spécifié",
  4323.                 "status" => 401,
  4324.             ]), 401);
  4325.         }
  4326.         /** @var Token */
  4327.         $token $this->getDoctrine()
  4328.             ->getRepository(Token::class)
  4329.             ->findOneBy(['token' => $data["token"]]);
  4330.         if (!$token) {
  4331.             return new Response(json_encode([
  4332.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4333.                 "status" => 404,
  4334.             ]), 404);
  4335.         }
  4336.         // get token age
  4337.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4338.         // if the token if older than 7 days
  4339.         if ($dateDiff->7) {
  4340.             $entityManager->remove($token);
  4341.             $entityManager->flush();
  4342.             return $this->json([
  4343.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4344.                 'path' => 'src/Controller/ClientController.php',
  4345.                 "status" => 401,
  4346.             ], 401);
  4347.         }
  4348.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  4349.             return new Response(json_encode([
  4350.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  4351.                 "status" => 404,
  4352.             ]), 404);
  4353.         }
  4354.         if (isset($data["date"])) {
  4355.             // remove the taken schedule by rdv to make sure there is no overlap
  4356.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4357.             $audioMotif $this->getDoctrine()
  4358.                 ->getRepository(AudioMotif::class)
  4359.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  4360.             if ($audioMotif == null) {
  4361.                 return new Response(json_encode(([
  4362.                     'message' => 'Error, no motif of this id found at this audio',
  4363.                     'path' => 'src/Controller/RdvController.php',
  4364.                     "status" => 400,
  4365.                 ])), 400);
  4366.             }
  4367.             if ($rdv->getIdAudio()->getIsIndie()) {
  4368.                 if ($rdv->getIdCentre()) {
  4369.                     // regular centre audio indie
  4370.                     /** @var AudioCentre */
  4371.                     $liaison $this->getDoctrine()
  4372.                         ->getRepository(AudioCentre::class)
  4373.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  4374.                     if ($liaison == null) {
  4375.                         return new Response(json_encode(([
  4376.                             'message' => 'Error, audio isnt part of the centre',
  4377.                             'path' => 'src/Controller/RdvController.php',
  4378.                             "status" => 400,
  4379.                         ])), 400);
  4380.                     }
  4381.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  4382.                         return new Response(json_encode(([
  4383.                             'message' => 'Error, no horaire found for this audio',
  4384.                             'path' => 'src/Controller/RdvController.php',
  4385.                             "status" => 400,
  4386.                         ])), 400);
  4387.                     }
  4388.                     // if ($publicFunction->calculScheduleFitDate($liaison->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), $rdv->getIdCentre()) == false) {
  4389.                     //     return new Response(json_encode(([
  4390.                     //         'message' => 'Error, no timestamp found at this time',
  4391.                     //         'path' => 'src/Controller/RdvController.php',
  4392.                     //         "status" => 400,
  4393.                     //     ])),400);
  4394.                     // }
  4395.                 } else {
  4396.                     // lieu audio indie
  4397.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  4398.                         return new Response(json_encode(([
  4399.                             'message' => 'Error, no horaire found for this audio',
  4400.                             'path' => 'src/Controller/RdvController.php',
  4401.                             "status" => 400,
  4402.                         ])), 400);
  4403.                     }
  4404.                     // if ($publicFunction->calculScheduleFitDate($rdv->getIdLieu()->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), null, $rdv->getIdLieu()) == false) {
  4405.                     //     return new Response(json_encode(([
  4406.                     //         'message' => 'Error, no timestamp found at this time',
  4407.                     //         'path' => 'src/Controller/RdvController.php',
  4408.                     //         "status" => 400,
  4409.                     //     ])),400);
  4410.                     // }
  4411.                 }
  4412.             } else {
  4413.                 // regular centre
  4414.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  4415.                     return new Response(json_encode(([
  4416.                         'message' => 'Error, no horaire found for this audio',
  4417.                         'path' => 'src/Controller/RdvController.php',
  4418.                         "status" => 400,
  4419.                     ])), 400);
  4420.                 }
  4421.                 // if ($publicFunction->calculScheduleFitDate($rdv->getIdCentre()->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), $rdv->getIdCentre()) == false) {
  4422.                 //     return new Response(json_encode(([
  4423.                 //         'message' => 'Error, no timestamp found at this time',
  4424.                 //         'path' => 'src/Controller/RdvController.php',
  4425.                 //         "status" => 400,
  4426.                 //     ])),400);
  4427.                 // }
  4428.             }
  4429.             $rdv->setDate($date);
  4430.         }
  4431.         $date $rdv->getDate();
  4432.         $smsDate $date->format('d-m-Y H:i');
  4433.         $oldDate $pastDate->format('d-m-Y H:i');
  4434.         $publicFunction->sendEmail("MyAudio <noreply@myaudio.fr>"$rdv->getIdClient()->getIdPersonneConfiance()->getMail(), "My Audio: Confirmation RDV""<p>Le RDV de votre proche est validé le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'aléa contactez le centre " $rdv->getIdCentre()->getPhone() . " pour modifier sa consultation.</p>");
  4435.         return new Response(json_encode(([
  4436.             "id" => $rdv->getId(),
  4437.             "status" => 200,
  4438.         ])));
  4439.     }
  4440.     /**
  4441.      * @Route("/rdv/{id}", name="editRdvByID", methods={"PUT"})
  4442.      */
  4443.     public function editRdvByID(PublicFunction $publicFunctionRdv $rdvRequest $requestGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  4444.     {
  4445.         $pastDate $rdv->getDate();
  4446.         $pastDuration $rdv->getDuration();
  4447.         $data json_decode($request->getContent(), true);
  4448.         $entityManager $this->getDoctrine()->getManager();
  4449.         if (!isset($data["token"])) {
  4450.             return new Response(json_encode([
  4451.                 "message" => "Pas de token n'a été spécifié",
  4452.                 "status" => 401,
  4453.             ]), 401);
  4454.         }
  4455.         /** @var Token */
  4456.         $token $this->getDoctrine()
  4457.             ->getRepository(Token::class)
  4458.             ->findOneBy(['token' => $data["token"]]);
  4459.         if (!$token) {
  4460.             return new Response(json_encode([
  4461.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4462.                 "status" => 404,
  4463.             ]), 404);
  4464.         }
  4465.         // get token age
  4466.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4467.         // if the token if older than 7 days
  4468.         if ($dateDiff->7) {
  4469.             $entityManager->remove($token);
  4470.             $entityManager->flush();
  4471.             return $this->json([
  4472.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4473.                 'path' => 'src/Controller/ClientController.php',
  4474.                 "status" => 401,
  4475.             ], 401);
  4476.         }
  4477.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  4478.             return new Response(json_encode([
  4479.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  4480.                 "status" => 404,
  4481.             ]), 404);
  4482.         }
  4483.         if (isset($data["etat_id"])) {
  4484.             $etat $this->getDoctrine()
  4485.                 ->getRepository(EtatRdv::class)
  4486.                 ->findOneBy(['id' => $data["etat_id"]]);
  4487.             if ($etat == null) {
  4488.                 return new Response(json_encode(([
  4489.                     'message' => 'Error, no etat found at this id',
  4490.                     'path' => 'src/Controller/TrustedUserController.php',
  4491.                     "status" => 400,
  4492.                 ])), 400);
  4493.             }
  4494.             $rdv->setIdEtat($etat);
  4495.         }
  4496.         if (isset($data["audio_id"])) {
  4497.             $audio $this->getDoctrine()
  4498.                 ->getRepository(Audio::class)
  4499.                 ->findOneBy(['id' => $data["audio_id"]]);
  4500.             if ($audio == null) {
  4501.                 return new Response(json_encode(([
  4502.                     'message' => 'Error, no audio found at this id',
  4503.                     'path' => 'src/Controller/TrustedUserController.php',
  4504.                     "status" => 400,
  4505.                 ])), 400);
  4506.             }
  4507.             $rdv->setIdAudio($audio);
  4508.         }
  4509.         if (isset($data["motif_id"])) {
  4510.             $motif $this->getDoctrine()
  4511.                 ->getRepository(Motif::class)
  4512.                 ->find($data["motif_id"]);
  4513.             if ($motif == null) {
  4514.                 return new Response(json_encode(([
  4515.                     'message' => 'Error, no motif found at this id',
  4516.                     'path' => 'src/Controller/TrustedUserController.php',
  4517.                     "status" => 400,
  4518.                 ])), 400);
  4519.             }
  4520.             $rdv->setIdMotif($motif);
  4521.         }
  4522.         if (isset($data["client_id"])) {
  4523.             $client $this->getDoctrine()
  4524.                 ->getRepository(Client::class)
  4525.                 ->findOneBy(['id' => $data["client_id"]]);
  4526.             if ($client == null) {
  4527.                 return new Response(json_encode(([
  4528.                     'message' => 'Error, no client found at this id',
  4529.                     'path' => 'src/Controller/TrustedUserController.php',
  4530.                     "status" => 400,
  4531.                 ])), 400);
  4532.             }
  4533.             $rdv->setIdClient($client);
  4534.         }
  4535.         // set client status
  4536.         if (isset($data["client_status_id"])) {
  4537.             $status $this->getDoctrine()
  4538.                 ->getRepository(ClientStatus::class)
  4539.                 ->findOneBy(['id' => $data["client_status_id"]]);
  4540.             if ($status == null) {
  4541.                 return new Response(json_encode(([
  4542.                     'message' => 'Error, no status found at this id',
  4543.                     'path' => 'src/Controller/TrustedUserController.php',
  4544.                     "status" => 400,
  4545.                 ])), 400);
  4546.             }
  4547.             $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  4548.             $client->setClientStatus($status);
  4549.             $client->setLastUpdateStatus(new \DateTimeImmutable);
  4550.         }
  4551.         if (isset($data["date"])) {
  4552.             $submittedDate $data['date'] ?? null;
  4553.             $newDate \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4554.             $currentDate $rdv->getDate();
  4555.             if (!$currentDate || $currentDate->format('d/m/Y H:i') !== $newDate->format('d/m/Y H:i')) {
  4556.                 $rdv->setDateOldRdv($currentDate);
  4557.             }
  4558.             // remove the taken schedule by rdv to make sure there is no overlap
  4559.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4560.             $dateInput \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4561.             $audioMotif $this->getDoctrine()
  4562.                 ->getRepository(AudioMotif::class)
  4563.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  4564.             if ($audioMotif == null) {
  4565.                 return new Response(json_encode(([
  4566.                     'message' => 'Error, no motif of this id found at this audio',
  4567.                     'path' => 'src/Controller/RdvController.php',
  4568.                     "status" => 400,
  4569.                 ])), 400);
  4570.             }
  4571.             if ($rdv->getIdAudio()->getIsIndie()) {
  4572.                 if ($rdv->getIdCentre()) {
  4573.                     // regular centre audio indie
  4574.                     /** @var AudioCentre */
  4575.                     $liaison $this->getDoctrine()
  4576.                         ->getRepository(AudioCentre::class)
  4577.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  4578.                     if ($liaison == null) {
  4579.                         return new Response(json_encode(([
  4580.                             'message' => 'Error, audio isnt part of the centre',
  4581.                             'path' => 'src/Controller/RdvController.php',
  4582.                             "status" => 400,
  4583.                         ])), 400);
  4584.                     }
  4585.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  4586.                         return new Response(json_encode(([
  4587.                             'message' => 'Error, no horaire found for this audio',
  4588.                             'path' => 'src/Controller/RdvController.php',
  4589.                             "status" => 400,
  4590.                         ])), 400);
  4591.                     }
  4592.                 } else {
  4593.                     // lieu audio indie
  4594.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  4595.                         return new Response(json_encode(([
  4596.                             'message' => 'Error, no horaire found for this audio',
  4597.                             'path' => 'src/Controller/RdvController.php',
  4598.                             "status" => 400,
  4599.                         ])), 400);
  4600.                     }
  4601.                 }
  4602.             } else {
  4603.                 // regular centre
  4604.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  4605.                     return new Response(json_encode(([
  4606.                         'message' => 'Error, no horaire found for this audio',
  4607.                         'path' => 'src/Controller/RdvController.php',
  4608.                         "status" => 400,
  4609.                     ])), 400);
  4610.                 }
  4611.             }
  4612.             $rdv->setDate($date);
  4613.         }
  4614.         if (isset($data["comment"]) && $token->getIdClient()) {
  4615.             $rdv->setComment($data["comment"]);
  4616.         }
  4617.         if (isset($data["review"]) && $token->getIdClient()) {
  4618.             $rdv->setReview($data["review"]);
  4619.         }
  4620.         if (isset($data["note"])) {
  4621.             $rdv->setNote($data["note"]);
  4622.         }
  4623.         if (isset($data["duree"])) {
  4624.             $rdv->setDuration($data["duree"]);
  4625.         }
  4626.         ////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
  4627.         $date $rdv->getDate();
  4628.         $smsDate $date->format('d-m-Y H:i');
  4629.         $oldDate $pastDate->format('d-m-Y H:i');
  4630.         $locale 'fr_FR';
  4631.         $formatter = new IntlDateFormatter(
  4632.             $locale,
  4633.             IntlDateFormatter::FULL,
  4634.             IntlDateFormatter::SHORT,
  4635.             null,
  4636.             IntlDateFormatter::GREGORIAN,
  4637.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  4638.         );
  4639.         $smsDateLongFormat $formatter->format($date);
  4640.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  4641.         $frenchDate ucfirst($frenchDate);
  4642.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  4643.         // notif client
  4644.         if ($rdv->getIdEtat()->getId() != 2) {
  4645.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  4646.                 if ($data["sms"]) {
  4647.                     $params = array(
  4648.                         "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4649.                         "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4650.                         "date" => $smsDateLongFormat,
  4651.                         "heure" => substr($smsDate1115),
  4652.                         "motif" => $rdv->getIdMotif()->getTitre(),
  4653.                         "centerName" => $rdv->getIdCentre()->getName(),
  4654.                         "centerAddress" => $rdv->getIdCentre()->getAddress(),
  4655.                         "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  4656.                         "audioMail" => $rdv->getIdAudio()->getMail(),
  4657.                         "centerPhone" => $rdv->getIdCentre()->getPhone(),
  4658.                         "centerCity" => $rdv->getIdCentre()->getCity(),
  4659.                         "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  4660.                         'titre' => 'Votre rendez-vous est modifié pour le',
  4661.                         'frenchDate' => $frenchDate,
  4662.                     );
  4663.                     $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  4664.                     $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  4665.                     $sms "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  4666.                     $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  4667.                 }
  4668.             }
  4669.         }
  4670.         //     //// == suppression
  4671.         else if ($rdv->getIdEtat()->getId() == 2) {
  4672.             // delete google agenda event
  4673.             $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  4674.                 ->findBy(array('rdv' => $rdv));
  4675.             foreach ($rdvEvents as $rdvEvent) {
  4676.                 $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4677.                 if ($googleCalendar) {
  4678.                     $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  4679.                     $entityManager->remove($rdvEvent);
  4680.                     $entityManager->flush();
  4681.                 }
  4682.             }
  4683.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  4684.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {                   
  4685.             $params = array(
  4686.                 "date" => substr($smsDate010),
  4687.                 "lien" => "{$_ENV['BASE_client']}search",
  4688.                 "heure" => substr($smsDate1115),
  4689.                 "patientName" => $client->getLastName(),
  4690.                 'titre' => 'Votre rendez-vous est annulé :',
  4691.                 'centerName' => $rdv->getIdCentre()->getName(),
  4692.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4693.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  4694.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4695.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4696.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4697.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  4698.                 'motif' => $rdv->getIdMotif()->getTitre(),
  4699.             );
  4700.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  4701.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  4702.             if ($data["sms"]) {
  4703.                 $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  4704.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  4705.             }
  4706.             //}
  4707.         }
  4708.         // set center
  4709.         if (isset($data["centre_id"])) {
  4710.             $entityManager $this->getDoctrine()->getManager();
  4711.             $centreId $data["centre_id"];
  4712.             $centre $entityManager->getRepository(Centre::class)->find($centreId);
  4713.             if (!$centre) {
  4714.                 return $this->json([
  4715.                     'message' => 'Error, no Centre found with this ID',
  4716.                     'path' => 'src/Controller/YourController.php',
  4717.                 ]);
  4718.             }
  4719.             $rdv->setIdCentre($centre);
  4720.         }
  4721.         $rdv->setGoogleAgendaImported(false);
  4722.         //notif Audio
  4723.         if ($rdv->getIdEtat()->getId() != 2) {
  4724.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  4725.                 if ($data["sms"]) {
  4726.                     $params = array(
  4727.                         "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  4728.                         "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  4729.                         "date" => substr($smsDate010),
  4730.                         "frenchDate" => $frenchDate,
  4731.                         "heure" => substr($smsDate1115),
  4732.                         'motif' => $rdv->getIdMotif()->getTitre(),
  4733.                         'clientPhone' => $client->getPhone(),
  4734.                         'clientNom' => $client->getLastname(),
  4735.                         'clientPrenom' => $client->getName(),
  4736.                         'clientCivilite' => $client->getCivilite(),
  4737.                         'clientPostal' => $client->getPostal(),
  4738.                         'clientMail' => $client->getMail(),
  4739.                         'centerName' => $rdv->getIdCentre()->getName(),
  4740.                         'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4741.                         'centerCity' => $rdv->getIdCentre()->getCity(),
  4742.                         'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4743.                         'idPatient' => $client->getId(),
  4744.                         'proUrl' => "{$_ENV['BASE_logiciel']}",
  4745.                         'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4746.                         'titre' => 'Votre rendez-vous est modifié pour le :'
  4747.                     );
  4748.                     $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  4749.                     $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  4750.                     if ($rdv->getIdAudio()->getModifRdvMail()) {
  4751.                         $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  4752.                         $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  4753.                     }
  4754.                     if ($rdv->getIdAudio()->getModifRdvSms()) {
  4755.                         // we ignore the sms send to the audio for the case he modify the rdv (so lets commented)
  4756.                         $sms "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre patient " $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  4757.                         //$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  4758.                     }
  4759.                 }
  4760.             }
  4761.         } else if ($rdv->getIdEtat()->getId() == 2) {
  4762.             if ($data["sms"]) {
  4763.                 $params = array(
  4764.                     "date" => substr($smsDate010),
  4765.                     "lien" => "{$_ENV['BASE_client']}search",
  4766.                     "heure" => substr($smsDate1115),
  4767.                     "patientName" => $client->getLastName(),
  4768.                     'titre' => 'Votre rendez-vous est annulé :',
  4769.                     'centerName' => $rdv->getIdCentre()->getName(),
  4770.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4771.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  4772.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4773.                     'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4774.                     'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4775.                     'audioMail' => $rdv->getIdAudio()->getMail(),
  4776.                     'motif' => $rdv->getIdMotif()->getTitre(),
  4777.                 );
  4778.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  4779.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  4780.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  4781.                     $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  4782.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject188);
  4783.                 }
  4784.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  4785.                     $sms "Votre RDV du " substr($oldDate010) . " à " substr($oldDate1115) . "a été annulé, vous pouvez contacter votre patient pour fixer un autre RDV:" $client->getPhone() . " pour fixer un autre RDV.\nNe pas répondre.";
  4786.                     // $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  4787.                 }
  4788.             }
  4789.         }
  4790.         $entityManager->flush();
  4791.         if ((isset($data["prenom_patient"]))  || (isset($data["nom_patient"]))  || (isset($data["birthday_patient"]))  || (isset($data["mail_patient"]))  || (isset($data["portable_patient"]))  || (isset($data["fixe_patient"]))) {
  4792.             if (is_null($rdv->getIdClientTemp())) {
  4793.                 $clientRDV $this->getDoctrine()
  4794.                     ->getRepository(Client::class)
  4795.                     ->findOneBy(['id' => $rdv->getIdClient()->getId()]);
  4796.                 $clientRDV->setName($data["prenom_patient"]);
  4797.                 $clientRDV->setLastname($data["nom_patient"]);
  4798.                 $clientRDV->setMail($data["mail_patient"]);
  4799.                 $clientRDV->setPhone($data["portable_patient"]);
  4800.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  4801.             } else {
  4802.                 $clientRDV $this->getDoctrine()
  4803.                     ->getRepository(ClientTemp::class)
  4804.                     ->findOneBy(['id' => $rdv->getIdClientTemp()->getId()]);
  4805.                 $clientRDV->setName($data["prenom_patient"]);
  4806.                 $clientRDV->setLastname($data["nom_patient"]);
  4807.                 $clientRDV->setMail($data["mail_patient"]);
  4808.                 $clientRDV->setPhone($data["portable_patient"]);
  4809.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  4810.             }
  4811.             if (!empty($data["birthday_patient"])) {
  4812.                 $birth \DateTime::createFromFormat("Y-m-d"$data["birthday_patient"]);
  4813.                 $clientRDV->setBirthdate($birth);
  4814.             }
  4815.             $entityManager->flush();
  4816.         }
  4817.         if (is_null($rdv->getIdClient())) {
  4818.             $prenom_patient $rdv->getIdClientTemp()->getName();
  4819.             $nom_patient $rdv->getIdClientTemp()->getLastname();
  4820.             $mail_patient $rdv->getIdClientTemp()->getMail();
  4821.             $portable_patient $rdv->getIdClientTemp()->getPhone();
  4822.             $fixe_patient $rdv->getIdClientTemp()->getPhoneFixe();
  4823.             $birthday $rdv->getIdClientTemp()->getBirthdate();
  4824.         } elseif (is_null($rdv->getIdClientTemp())) {
  4825.             $prenom_patient =  $rdv->getIdClient()->getName();
  4826.             $nom_patient $rdv->getIdClient()->getLastname();
  4827.             $mail_patient $rdv->getIdClient()->getMail();
  4828.             $portable_patient $rdv->getIdClient()->getPhone();
  4829.             $fixe_patient $rdv->getIdClient()->getPhoneFixe();
  4830.             $birthday $rdv->getIdClient()->getBirthdate();
  4831.         } else {
  4832.             $prenom_patient "";
  4833.             $nom_patient "";
  4834.             $mail_patient "";
  4835.             $portable_patient "";
  4836.             $fixe_patient "";
  4837.             $birthday "";
  4838.         }
  4839.         /* generate sms notif on update */
  4840.         // update sms notification     
  4841.         $rdvSms->updateRdvSms($rdv);
  4842.         // google calendar update
  4843.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  4844.             ->findBy(array('audio' => $rdv->getIdAudio()));
  4845.         $data['rdv'] = $rdv->getId();
  4846.         if ($rdv->getIdClient() !== null) {
  4847.             $data["client_id"] = $rdv->getIdClient()->getId();
  4848.         }
  4849.         if ($rdv->getIdClientTemp() !== null) {
  4850.             $data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
  4851.         }
  4852.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  4853.             ->findBy(array('rdv' => $rdv));
  4854.         foreach ($rdvEvents as $rdvEvent) {
  4855.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4856.             $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  4857.         }
  4858.         $synchronisationCosium $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $rdv->getIdAudio()->getId()]);
  4859.         $cosiumCenter $this->getDoctrine()->getRepository(CosiumCenter::class)->findOneBy(["synchronisationCosium" => $synchronisationCosium"center" => $rdv->getIdCentre()]);
  4860.         if ($cosiumCenter) {
  4861.             $this->clientCosiumService->deleteRdv($synchronisationCosium$rdv);
  4862.             $this->clientCosiumService->createAgenda($synchronisationCosium$rdv$cosiumCenter);
  4863.         }
  4864.         $token $this->entityManager
  4865.              ->getRepository(Token::class)
  4866.              ->findOneBy(['token' => $data['token']]);
  4867.         $tokenAudioId $token->getIdAudio()->getId();
  4868.         $requestAudioId $data['audio_id'] ?? null;
  4869.         if ($requestAudioId && $requestAudioId == $tokenAudioId) {
  4870.         // After successfully updating the RDV
  4871.         $this->mercure->publishRdvUpdate($rdv'updated');
  4872.         }
  4873.         return new Response(json_encode(([
  4874.             "id" => $rdv->getId(),
  4875.             "motif_id" => $rdv->getIdMotif()->getId(),
  4876.             "motif_libelle" => $rdv->getIdMotif()->getTitre(),
  4877.             "audio_id" => $rdv->getIdAudio()->getId(),
  4878.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  4879.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  4880.             "fullName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  4881.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  4882.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  4883.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  4884.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  4885.             "centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
  4886.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  4887.             "etat_id" => $rdv->getIdEtat()->getId(),
  4888.             "date" => $rdv->getDate(),
  4889.             "comment" => $rdv->getComment(),
  4890.             "note" => $rdv->getNote(),
  4891.             "review" => $rdv->getReview(),
  4892.             "clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
  4893.             "prenom_patient" => $prenom_patient,
  4894.             "nom_patient" => $nom_patient,
  4895.             "mail_patient" => $mail_patient,
  4896.             "portable_patient" => $portable_patient,
  4897.             "fixe_patient" => $fixe_patient,
  4898.             "birthday" => $birthday,
  4899.             "status" => 200,
  4900.         ])));
  4901.     }
  4902.     /**
  4903.      * @Route("/rdv-by-patient/{id}", name="editRdvByIDFromPatient", methods={"PUT"})
  4904.      */
  4905.     public function editRdvByIDFromPatient(PublicFunction $publicFunctionRdv $rdvRequest $request): Response
  4906.     {
  4907.         $pastDate $rdv->getDate();
  4908.         $pastDuration $rdv->getDuration();
  4909.         $data json_decode($request->getContent(), true);
  4910.         $entityManager $this->getDoctrine()->getManager();
  4911.         if (!isset($data["token"])) {
  4912.             return new Response(json_encode([
  4913.                 "message" => "Pas de token n'a été spécifié",
  4914.                 "status" => 401,
  4915.             ]), 401);
  4916.         }
  4917.         /** @var Token */
  4918.         $token $this->getDoctrine()
  4919.             ->getRepository(Token::class)
  4920.             ->findOneBy(['token' => $data["token"]]);
  4921.         if (!$token) {
  4922.             return new Response(json_encode([
  4923.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4924.                 "status" => 404,
  4925.             ]), 404);
  4926.         }
  4927.         // get token age
  4928.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4929.         // if the token if older than 7 days
  4930.         if ($dateDiff->7) {
  4931.             $entityManager->remove($token);
  4932.             $entityManager->flush();
  4933.             return $this->json([
  4934.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4935.                 'path' => 'src/Controller/ClientController.php',
  4936.                 "status" => 401,
  4937.             ], 401);
  4938.         }
  4939.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  4940.             return new Response(json_encode([
  4941.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  4942.                 "status" => 404,
  4943.             ]), 404);
  4944.         }
  4945.         if (isset($data["etat_id"])) {
  4946.             $etat $this->getDoctrine()
  4947.                 ->getRepository(EtatRdv::class)
  4948.                 ->findOneBy(['id' => $data["etat_id"]]);
  4949.             if ($etat == null) {
  4950.                 return new Response(json_encode(([
  4951.                     'message' => 'Error, no etat found at this id',
  4952.                     'path' => 'src/Controller/TrustedUserController.php',
  4953.                     "status" => 400,
  4954.                 ])), 400);
  4955.             }
  4956.             $rdv->setIdEtat($etat);
  4957.         }
  4958.         if (isset($data["audio_id"])) {
  4959.             $audio $this->getDoctrine()
  4960.                 ->getRepository(Audio::class)
  4961.                 ->findOneBy(['id' => $data["audio_id"]]);
  4962.             if ($audio == null) {
  4963.                 return new Response(json_encode(([
  4964.                     'message' => 'Error, no audio found at this id',
  4965.                     'path' => 'src/Controller/TrustedUserController.php',
  4966.                     "status" => 400,
  4967.                 ])), 400);
  4968.             }
  4969.             $rdv->setIdAudio($audio);
  4970.         }
  4971.         if (isset($data["motif_id"])) {
  4972.             $motif $this->getDoctrine()
  4973.                 ->getRepository(Motif::class)
  4974.                 ->find($data["motif_id"]);
  4975.             if ($motif == null) {
  4976.                 return new Response(json_encode(([
  4977.                     'message' => 'Error, no motif found at this id',
  4978.                     'path' => 'src/Controller/TrustedUserController.php',
  4979.                     "status" => 400,
  4980.                 ])), 400);
  4981.             }
  4982.             $rdv->setIdMotif($motif);
  4983.         }
  4984.         if (isset($data["client_id"])) {
  4985.             $client $this->getDoctrine()
  4986.                 ->getRepository(Client::class)
  4987.                 ->findOneBy(['id' => $data["client_id"]]);
  4988.             if ($client == null) {
  4989.                 return new Response(json_encode(([
  4990.                     'message' => 'Error, no client found at this id',
  4991.                     'path' => 'src/Controller/TrustedUserController.php',
  4992.                     "status" => 400,
  4993.                 ])), 400);
  4994.             }
  4995.             $rdv->setIdClient($client);
  4996.         }
  4997.         if (isset($data["date"])) {
  4998.             // remove the taken schedule by rdv to make sure there is no overlap
  4999.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  5000.             $dateInput \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  5001.             $audioMotif $this->getDoctrine()
  5002.                 ->getRepository(AudioMotif::class)
  5003.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  5004.             if ($audioMotif == null) {
  5005.                 return new Response(json_encode(([
  5006.                     'message' => 'Error, no motif of this id found at this audio',
  5007.                     'path' => 'src/Controller/RdvController.php',
  5008.                     "status" => 400,
  5009.                 ])), 400);
  5010.             }
  5011.             if ($rdv->getIdAudio()->getIsIndie()) {
  5012.                 if ($rdv->getIdCentre()) {
  5013.                     // regular centre audio indie
  5014.                     /** @var AudioCentre */
  5015.                     $liaison $this->getDoctrine()
  5016.                         ->getRepository(AudioCentre::class)
  5017.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  5018.                     if ($liaison == null) {
  5019.                         return new Response(json_encode(([
  5020.                             'message' => 'Error, audio isnt part of the centre',
  5021.                             'path' => 'src/Controller/RdvController.php',
  5022.                             "status" => 400,
  5023.                         ])), 400);
  5024.                     }
  5025.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  5026.                         return new Response(json_encode(([
  5027.                             'message' => 'Error, no horaire found for this audio',
  5028.                             'path' => 'src/Controller/RdvController.php',
  5029.                             "status" => 400,
  5030.                         ])), 400);
  5031.                     }
  5032.                 } else {
  5033.                     // lieu audio indie
  5034.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  5035.                         return new Response(json_encode(([
  5036.                             'message' => 'Error, no horaire found for this audio',
  5037.                             'path' => 'src/Controller/RdvController.php',
  5038.                             "status" => 400,
  5039.                         ])), 400);
  5040.                     }
  5041.                 }
  5042.             } else {
  5043.                 // regular centre
  5044.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  5045.                     return new Response(json_encode(([
  5046.                         'message' => 'Error, no horaire found for this audio',
  5047.                         'path' => 'src/Controller/RdvController.php',
  5048.                         "status" => 400,
  5049.                     ])), 400);
  5050.                 }
  5051.             }
  5052.             $rdv->setDate($date);
  5053.         }
  5054.         if (isset($data["comment"]) && $token->getIdClient()) {
  5055.             $rdv->setComment($data["comment"]);
  5056.         }
  5057.         if (isset($data["review"]) && $token->getIdClient()) {
  5058.             $rdv->setReview($data["review"]);
  5059.         }
  5060.         if (isset($data["note"])) {
  5061.             $rdv->setNote($data["note"]);
  5062.         }
  5063.         if (isset($data["duree"])) {
  5064.             $rdv->setDuration($data["duree"]);
  5065.         }
  5066.         ////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
  5067.         $date $rdv->getDate();
  5068.         $smsDate $date->format('d-m-Y H:i');
  5069.         $oldDate $pastDate->format('d-m-Y H:i');
  5070.         $locale 'fr_FR';
  5071.         $formatter = new IntlDateFormatter(
  5072.             $locale,
  5073.             IntlDateFormatter::FULL,
  5074.             IntlDateFormatter::SHORT,
  5075.             null,
  5076.             IntlDateFormatter::GREGORIAN,
  5077.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  5078.         );
  5079.         $smsDateLongFormat $formatter->format($date);
  5080.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  5081.         $frenchDate ucfirst($frenchDate);
  5082.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  5083.         // notif client
  5084.         if ($rdv->getIdEtat()->getId() != 2) {
  5085.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  5086.                 $params = array(
  5087.                     "lienModifier" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5088.                     "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5089.                     "date" => $smsDateLongFormat,
  5090.                     "heure" => substr($smsDate1115),
  5091.                     "motif" => $rdv->getIdMotif()->getTitre(),
  5092.                     "centerName" => $rdv->getIdCentre()->getName(),
  5093.                     "centerAddress" => $rdv->getIdCentre()->getAddress(),
  5094.                     "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  5095.                     "audioMail" => $rdv->getIdAudio()->getMail(),
  5096.                     "centerPhone" => $rdv->getIdCentre()->getPhone(),
  5097.                     "centerCity" => $rdv->getIdCentre()->getCity(),
  5098.                     "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  5099.                     'titre' => 'Votre rendez-vous est modifié pour le',
  5100.                     'frenchDate' => $frenchDate,
  5101.                 );
  5102.                 $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  5103.                 $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  5104.                 $sms "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  5105.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5106.             }
  5107.         }
  5108.         //     //// == suppression
  5109.         else if ($rdv->getIdEtat()->getId() == 2) {
  5110.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  5111.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {                   
  5112.             $params = array(
  5113.                 "date" => substr($smsDate010),
  5114.                 "lien" => "{$_ENV['BASE_client']}audioprothesiste/{$rdv->getIdCentre()->getCity()}/{$rdv->getIdCentre()->getPostale()}/{$rdv->getIdCentre()->getName()}/prise-de-rdv-audioprothesiste-rapide/{$rdv->getIdCentre()->getId()}",
  5115.                 "heure" => substr($smsDate1115),
  5116.                 "patientName" => $client->getLastName(),
  5117.                 'titre' => 'Votre rendez-vous est annulé :',
  5118.                 'centerName' => $rdv->getIdCentre()->getName(),
  5119.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5120.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  5121.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5122.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  5123.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5124.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  5125.                 'motif' => $rdv->getIdMotif()->getTitre(),
  5126.             );
  5127.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  5128.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject203);
  5129.             $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  5130.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5131.             //}
  5132.         }
  5133.         // set center
  5134.         if (isset($data["centre_id"])) {
  5135.             $entityManager $this->getDoctrine()->getManager();
  5136.             $centreId $data["centre_id"];
  5137.             $centre $entityManager->getRepository(Centre::class)->find($centreId);
  5138.             if (!$centre) {
  5139.                 return $this->json([
  5140.                     'message' => 'Error, no Centre found with this ID',
  5141.                     'path' => 'src/Controller/YourController.php',
  5142.                 ]);
  5143.             }
  5144.             $rdv->setIdCentre($centre);
  5145.         }
  5146.         $rdv->setGoogleAgendaImported(false);
  5147.         //notif Audio
  5148.         if ($rdv->getIdEtat()->getId() != 2) {
  5149.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  5150.                 $params = array(
  5151.                     "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  5152.                     "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  5153.                     "date" => $pastDate->format("y-m-d"),
  5154.                     "heure" => $pastDate->format("H:i"),
  5155.                     'clientPhone' => $client->getPhone(),
  5156.                     'clientCivilite' => $client->getCivilite(),
  5157.                     'clientNom' => $client->getLastname(),
  5158.                     'clientPrenom' => $client->getName(),
  5159.                     'clientPostal' => $client->getPostal(),
  5160.                     'clientMail' => $client->getMail(),
  5161.                     "birthdate" => $rdv->getIdClient()->getBirthdate()->format("y-m-d"),
  5162.                     "mail" => $rdv->getIdClient()->getMail(),
  5163.                     "phone" => $rdv->getIdClient()->getPhone(),
  5164.                     "motif" => $rdv->getIdMotif()->getTitre(),
  5165.                     "address" => $rdv->getIdCentre()->getAddress(),
  5166.                     "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getLastName() . ' ' $rdv->getIdAudio()->getName(),
  5167.                     "newRdvDate" => substr($smsDate010),
  5168.                     "newRdvHour" => substr($smsDate1115),
  5169.                     "centerName" => $rdv->getIdCentre()->getName(),
  5170.                     "centerAddress" => $rdv->getIdCentre()->getAddress(),
  5171.                     "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  5172.                     'titre' => "Modification de Rendez-vous My Audio de {$rdv->getIdClient()->getLastname()}",
  5173.                     "urlPro" => "{$_ENV['BASE_logiciel']}",
  5174.                     "idPatient" => $rdv->getIdClient()->getId(),
  5175.                 );
  5176.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  5177.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  5178.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  5179.                     $subject "🔀 Rendez-vous My Audio modifié par " $client->getCivilite() . " " $client->getName() . " " $client->getLastname();
  5180.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject185);
  5181.                 }
  5182.                 $subjectMyAudio "🔀 Le patient " $client->getCivilite() . " " $client->getName() . " " $client->getLastname() . "  a modifié son rendez-vous My Audio";
  5183.                 $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subjectMyAudio204);
  5184.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  5185.                     $sms "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre patient " $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  5186.                     $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  5187.                 }
  5188.             }
  5189.         } else if ($rdv->getIdEtat()->getId() == 2) {
  5190.             $params = array(
  5191.                 "date" => substr($smsDate010),
  5192.                 "heure" => substr($smsDate1115),
  5193.                 "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  5194.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5195.                 "motif" => $rdv->getIdMotif()->getTitre(),
  5196.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  5197.                 "centerPostal" => $rdv->getIdCentre()->getPostale(),
  5198.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  5199.                 "centerName" => $rdv->getIdCentre()->getName(),
  5200.                 "clientNom" => $rdv->getIdClient()->getLastname(),
  5201.                 "clientPrenom" => $rdv->getIdClient()->getName(),
  5202.                 "clientMail" => $rdv->getIdClient()->getMail(),
  5203.                 "clientPhone" => $rdv->getIdClient()->getPhone(),
  5204.                 'titre' => "Annulation du Rendez-vous avec le patient {$rdv->getIdClient()->getLastname()}",
  5205.                 "proUrl" => "{$_ENV['BASE_logiciel']}",
  5206.                 "idPatient" => $rdv->getIdClient()->getId(),
  5207.             );
  5208.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  5209.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  5210.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  5211.                 $subject "❌ Annulation du rendez-vous par le patient " $client->getCivilite() . " " $client->getName() . " " $client->getLastname();
  5212.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject187);
  5213.             }
  5214.             $subject "❌ Annulation du rendez-vous par le patient " $client->getCivilite() . " " $client->getName() . " " $client->getLastname();
  5215.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject195);
  5216.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  5217.                 $sms "Votre RDV du " substr($oldDate010) . " à " substr($oldDate1115) . "a été annulé, vous pouvez contacter votre patient pour fixer un autre RDV:" $client->getPhone() . " pour fixer un autre RDV.\nNe pas répondre.";
  5218.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  5219.             }
  5220.         }
  5221.         $entityManager->flush();
  5222.         if ((isset($data["prenom_patient"]))  || (isset($data["nom_patient"]))  || (isset($data["birthday_patient"]))  || (isset($data["mail_patient"]))  || (isset($data["portable_patient"]))  || (isset($data["fixe_patient"]))) {
  5223.             $birth \DateTime::createFromFormat("Y-m-d"$data["birthday_patient"]);
  5224.             if (is_null($rdv->getIdClientTemp())) {
  5225.                 $clientRDV $this->getDoctrine()
  5226.                     ->getRepository(Client::class)
  5227.                     ->findOneBy(['id' => $rdv->getIdClient()->getId()]);
  5228.                 $clientRDV->setName($data["prenom_patient"]);
  5229.                 $clientRDV->setLastname($data["nom_patient"]);
  5230.                 $clientRDV->setBirthdate($birth);
  5231.                 $clientRDV->setMail($data["mail_patient"]);
  5232.                 $clientRDV->setPhone($data["portable_patient"]);
  5233.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  5234.             } else {
  5235.                 $clientRDV $this->getDoctrine()
  5236.                     ->getRepository(ClientTemp::class)
  5237.                     ->findOneBy(['id' => $rdv->getIdClientTemp()->getId()]);
  5238.                 $clientRDV->setName($data["prenom_patient"]);
  5239.                 $clientRDV->setLastname($data["nom_patient"]);
  5240.                 $clientRDV->setBirthdate($birth);
  5241.                 $clientRDV->setMail($data["mail_patient"]);
  5242.                 $clientRDV->setPhone($data["portable_patient"]);
  5243.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  5244.             }
  5245.             $entityManager->flush();
  5246.         }
  5247.         if (is_null($rdv->getIdClient())) {
  5248.             $prenom_patient $rdv->getIdClientTemp()->getName();
  5249.             $nom_patient $rdv->getIdClientTemp()->getLastname();
  5250.             $mail_patient $rdv->getIdClientTemp()->getMail();
  5251.             $portable_patient $rdv->getIdClientTemp()->getPhone();
  5252.             $fixe_patient $rdv->getIdClientTemp()->getPhoneFixe();
  5253.             $birthday $rdv->getIdClientTemp()->getBirthdate();
  5254.         } elseif (is_null($rdv->getIdClientTemp())) {
  5255.             $prenom_patient =  $rdv->getIdClient()->getName();
  5256.             $nom_patient $rdv->getIdClient()->getLastname();
  5257.             $mail_patient $rdv->getIdClient()->getMail();
  5258.             $portable_patient $rdv->getIdClient()->getPhone();
  5259.             $fixe_patient $rdv->getIdClient()->getPhoneFixe();
  5260.             $birthday $rdv->getIdClient()->getBirthdate();
  5261.         } else {
  5262.             $prenom_patient "";
  5263.             $nom_patient "";
  5264.             $mail_patient "";
  5265.             $portable_patient "";
  5266.             $fixe_patient "";
  5267.             $birthday "";
  5268.         }
  5269.         return new Response(json_encode(([
  5270.             "id" => $rdv->getId(),
  5271.             "motif_id" => $rdv->getIdMotif()->getId(),
  5272.             "motif_libelle" => $rdv->getIdMotif()->getTitre(),
  5273.             "audio_id" => $rdv->getIdAudio()->getId(),
  5274.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  5275.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  5276.             "fullName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  5277.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  5278.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  5279.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  5280.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  5281.             "centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
  5282.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  5283.             "etat_id" => $rdv->getIdEtat()->getId(),
  5284.             "date" => $rdv->getDate(),
  5285.             "comment" => $rdv->getComment(),
  5286.             "note" => $rdv->getNote(),
  5287.             "review" => $rdv->getReview(),
  5288.             "prenom_patient" => $prenom_patient,
  5289.             "nom_patient" => $nom_patient,
  5290.             "mail_patient" => $mail_patient,
  5291.             "portable_patient" => $portable_patient,
  5292.             "fixe_patient" => $fixe_patient,
  5293.             "birthday" => $birthday,
  5294.             "status" => 200,
  5295.         ])));
  5296.     }
  5297.     /**
  5298.      * @Route("/rdv/{id}/supp", name="suppRdvByID", methods={"PUT"})
  5299.      */
  5300.     public function suppRdvByID(PublicFunction $publicFunctionRdv $rdvRequest $requestGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  5301.     {
  5302.         $pastDate $rdv->getDate();
  5303.         $data json_decode($request->getContent(), true);
  5304.         $entityManager $this->getDoctrine()->getManager();
  5305.         if (!isset($data["token"])) {
  5306.             return new Response(json_encode([
  5307.                 "message" => "Pas de token n'a été spécifié",
  5308.                 "status" => 401,
  5309.             ]), 401);
  5310.         }
  5311.         /** @var Token */
  5312.         $token $this->getDoctrine()
  5313.             ->getRepository(Token::class)
  5314.             ->findOneBy(['token' => $data["token"]]);
  5315.         if (!$token) {
  5316.             return new Response(json_encode([
  5317.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5318.                 "status" => 404,
  5319.             ]), 404);
  5320.         }
  5321.         // get token age
  5322.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5323.         // if the token if older than 7 days
  5324.         if ($dateDiff->7) {
  5325.             $entityManager->remove($token);
  5326.             $entityManager->flush();
  5327.             return $this->json([
  5328.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5329.                 'path' => 'src/Controller/ClientController.php',
  5330.                 "status" => 401,
  5331.             ], 401);
  5332.         }
  5333.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  5334.             return new Response(json_encode([
  5335.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  5336.                 "status" => 404,
  5337.             ]), 404);
  5338.         }
  5339.         // delete google agenda event
  5340.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  5341.             ->findBy(array('rdv' => $rdv));
  5342.         //dd($rdvEvents);
  5343.         $synchronisationCosium $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $rdv->getIdAudio()->getId()]);
  5344.         $cosiumCenter $this->getDoctrine()->getRepository(CosiumCenter::class)->findBy(["synchronisationCosium" => $synchronisationCosium"center" => $rdv->getIdCentre()]);
  5345.         if ($cosiumCenter) {
  5346.             $this->clientCosiumService->deleteRdv($synchronisationCosium$rdv);
  5347.         }
  5348.         foreach ($rdvEvents as $rdvEvent) {
  5349.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  5350.             $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  5351.             $entityManager->remove($rdvEvent);
  5352.             $entityManager->flush();
  5353.         }
  5354.         $etat $this->getDoctrine()
  5355.             ->getRepository(EtatRdv::class)
  5356.             ->findOneBy(['id' => 2]);
  5357.         if ($etat == null) {
  5358.             return new Response(json_encode(([
  5359.                 'message' => 'Error, no etat found at this id',
  5360.                 'path' => 'src/Controller/TrustedUserController.php',
  5361.                 "status" => 400,
  5362.             ])), 400);
  5363.         }
  5364.         $rdv->setIdEtat($etat);
  5365.         $rdv->setCacher(1);
  5366.         ////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
  5367.         $date $rdv->getDate();
  5368.         $smsDate $date->format('d-m-Y H:i');
  5369.         $oldDate $pastDate->format('d-m-Y H:i');
  5370.         $locale 'fr_FR';
  5371.         $formatter = new IntlDateFormatter(
  5372.             $locale,
  5373.             IntlDateFormatter::FULL,
  5374.             IntlDateFormatter::SHORT,
  5375.             null,
  5376.             IntlDateFormatter::GREGORIAN,
  5377.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  5378.         );
  5379.         $smsDateLongFormat $formatter->format($date);
  5380.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  5381.         $frenchDate ucfirst($frenchDate);
  5382.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  5383.         // notif client
  5384.         if ($rdv->getIdEtat()->getId() != 2) {
  5385.             $params = array(
  5386.                 "lienModifier" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5387.                 "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5388.                 "date" => $smsDateLongFormat,
  5389.                 "heure" => substr($smsDate1115),
  5390.                 "motif" => $rdv->getIdMotif()->getTitre(),
  5391.                 "centerName" => $rdv->getIdCentre()->getName(),
  5392.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  5393.                 "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  5394.                 "audioMail" => $rdv->getIdAudio()->getMail(),
  5395.                 "centerPhone" => $rdv->getIdCentre()->getPhone(),
  5396.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  5397.                 "clientEmail" => $client->getMail(),
  5398.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  5399.                 'titre' => 'Votre rendez-vous est modifié pour le',
  5400.                 'frenchDate' => $frenchDate
  5401.             );
  5402.             $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  5403.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject205);
  5404.             $sms "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  5405.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5406.             // creer un mail de notif pour myAudio + créé le template LP | MA | RR - Modification du RDV - Centre Auditif - MyAudio
  5407.             $subjectMyaudio "Rendez-vous My Audio a été modifié par l'audioprothésiste " $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName();
  5408.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$client->getName() . ' ' $client->getLastName(), $subjectMyaudio206);
  5409.         }
  5410.         //     //// == suppression
  5411.         else if ($rdv->getIdEtat()->getId() == 2) {
  5412.             $params = array(
  5413.                 "date" => substr($smsDate010),
  5414.                 "lien" => "{$_ENV['BASE_client']}search",
  5415.                 "heure" => substr($smsDate1115),
  5416.                 "patientName" => $client->getLastName() . ' ' $client->getName(),
  5417.                 'titre' => 'Votre rendez-vous est annulé :',
  5418.                 'centerName' => $rdv->getIdCentre()->getName(),
  5419.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5420.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  5421.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5422.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  5423.                 "clientEmail" => $client->getMail() ?? '',
  5424.                 "clientPhone" => $client->getPhone() ?? '',
  5425.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5426.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  5427.                 'motif' => $rdv->getIdMotif()->getTitre(),
  5428.             );
  5429.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  5430.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  5431.             $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  5432.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5433.             // creer un mail de notif pour myAudio + créé le template LP | MA | RR - Annlation du RDV - Centre Auditif - MyAudio
  5434.             $subjectMyaudio $rdv->getIdCentre()->getName() . " a annulé un rendez-vous My Audio avec " $client->getName() . ' ' $client->getLastName();
  5435.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$client->getName() . ' ' $client->getLastName(), $subjectMyaudio207);
  5436.         }
  5437.         //notif Audio
  5438.         if ($rdv->getIdEtat()->getId() != 2) {
  5439.             $params = array(
  5440.                 "lienModifier" => "{$_ENV['BASE_logiciel']}rdv",
  5441.                 "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  5442.                 "date" => substr($smsDate010),
  5443.                 "frenchDate" => $frenchDate,
  5444.                 "heure" => substr($smsDate1115),
  5445.                 'motif' => $rdv->getIdMotif()->getTitre(),
  5446.                 'clientPhone' => $client->getPhone(),
  5447.                 'clientNom' => $client->getLastname(),
  5448.                 'clientPrenom' => $client->getName(),
  5449.                 'clientCivilite' => $client->getCivilite(),
  5450.                 'clientPostal' => $client->getPostal(),
  5451.                 'clientMail' => $client->getMail(),
  5452.                 'centerName' => $rdv->getIdCentre()->getName(),
  5453.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5454.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  5455.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5456.                 'idPatient' => $client->getId(),
  5457.                 'proUrl' => "{$_ENV['BASE_logiciel']}",
  5458.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5459.                 'titre' => 'Votre rendez-vous est modifié pour le :'
  5460.             );
  5461.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  5462.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  5463.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  5464.                 $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  5465.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  5466.             }
  5467.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  5468.                 $sms "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre patient " $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  5469.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  5470.             }
  5471.         } else if ($rdv->getIdEtat()->getId() == 2) {
  5472.             /* $params = array(  
  5473.                     "date" => substr($smsDate, 0, 10),
  5474.                     "lien"=> "{$_ENV['BASE_client']}search",
  5475.                     "heure" =>substr($smsDate, 11, 15),
  5476.                     "patientName" => $client->getLastName(),
  5477.                     'titre' => 'Votre rendez-vous est annulé :',
  5478.                     'centerName' => $rdv->getIdCentre()->getName(),
  5479.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5480.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  5481.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5482.                     'centerPhone' => $rdv->getIdCentre()->getPhone(),
  5483.                     'audioproName' => $rdv->getIdAudio()->getCivilite().' '. $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(),                    
  5484.                     'audioMail' => $rdv->getIdAudio()->getMail(),
  5485.                     'motif' => $rdv->getIdMotif()->getTitre(),
  5486.                 );
  5487.                 $subject = "Rendez-vous My Audio annulé avec " . $rdv->getIdCentre()->getName();
  5488.                 $publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(), $subject, 188 );
  5489.                 $sms = "Votre RDV du " . substr($oldDate, 0, 10) . " à " . substr($oldDate, 11, 15) . "a été annulé, vous pouvez contacter votre patient pour fixer un autre RDV:" . $client->getPhone() . " pour fixer un autre RDV.\nNe pas répondre.";
  5490.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());
  5491.                 */
  5492.         }
  5493.         // delete sms notification     
  5494.         $rdvSms->deleteAssociatedRdvSms($rdv);
  5495.         // delete client device
  5496.         /*$clientDevice = $this->getDoctrine()->getRepository(ClientDevice::class)->findOneBy(['rdv' => $rdv]);
  5497. if($clientDevice)
  5498. {
  5499. if ($client instanceof Client) {
  5500.     $nextRdvs = $this->getDoctrine()
  5501.         ->getRepository(Rdv::class)
  5502.         ->findBy([
  5503.             "id_client" => $rdv->getIdClient(),
  5504.             "id_motif" => ['106', '107', '108', '109'] 
  5505.         ]);
  5506.         $client->setClientStatus(null);
  5507. } elseif ($client instanceof ClientTemp) {
  5508.  $nextRdvs = $this->getDoctrine()
  5509.         ->getRepository(Rdv::class)
  5510.         ->findBy([
  5511.             "id_client_temp" => $rdv->getIdClientTemp(),
  5512.             "id_motif" => ['106', '107', '108', '109'] 
  5513.         ]);
  5514.         $client->setClientStatus(null);
  5515.     } 
  5516.     $locale = 'fr_FR';
  5517.     $fmt = new IntlDateFormatter($locale, IntlDateFormatter::FULL, IntlDateFormatter::NONE);
  5518.     $fmt->setPattern("EEEE dd MMMM yyyy"); 
  5519.     if($nextRdvs){
  5520.     $params = array(  
  5521.                 "title" => "Affectation de votre appareil et programmation de vos rendez-vous",
  5522.                 "centerName" => "{$rdv->getIdCentre()->getName()}",
  5523.                 "audioName" => "{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastName()}",
  5524.                 "centerAddress" => "{$rdv->getIdCentre()->getAddress()}",
  5525.                 "device" => "{$clientDevice->getDevice()->getModel()}",
  5526.                 "ears" => "{$clientDevice->getSettingDevice()->getName()}",
  5527.                 "rdvOneDate" => "{$fmt->format($nextRdvs['0']->getDate())}",
  5528.                 "rdvOneHour" => "{$nextRdvs['0']->getDate()->format('H:i')}",
  5529.                 "rdvTwoDate" => "{$fmt->format($nextRdvs['1']->getDate())}",
  5530.                 "rdvTwoHour" => "{$nextRdvs['1']->getDate()->format('H:i')}",
  5531.                 "rdvThreeDate" => "{$fmt->format($nextRdvs['2']->getDate())}",
  5532.                 "rdvThreeHour" => "{$nextRdvs['2']->getDate()->format('H:i')}",
  5533.                 "rdvFourDate" => "{$fmt->format($nextRdvs['3']->getDate())}",
  5534.                 "rdvFourHour" => "{$nextRdvs['3']->getDate()->format('H:i')}",
  5535.             );
  5536.     
  5537.             $publicFunction->sendEmail($params, $client->getMail(), $client->getName().' '.$client->getLastName(), "Annulation de vos prochains RDV", 162 );
  5538.         }
  5539.     foreach($nextRdvs as $rdv)
  5540.     {
  5541.         $entityManager->remove($rdv);
  5542.     }
  5543.     $entityManager->persist($client);
  5544.     $entityManager->remove($clientDevice);
  5545.     $entityManager->flush();
  5546. }*/
  5547.         // Before deleting, publish the deletion event
  5548.         $this->mercure->publishRdvDeletion($rdv);
  5549.         $entityManager->flush();
  5550.         return new Response(json_encode(([
  5551.             "id" => $rdv->getId(),
  5552.             "motif_id" => $rdv->getIdMotif()->getId(),
  5553.             "motif_libelle" => $rdv->getIdMotif()->getTitre(),
  5554.             "audio_id" => $rdv->getIdAudio()->getId(),
  5555.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  5556.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  5557.             "fullName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  5558.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  5559.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  5560.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  5561.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  5562.             "centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
  5563.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  5564.             "etat_id" => $rdv->getIdEtat()->getId(),
  5565.             "date" => $rdv->getDate(),
  5566.             "comment" => $rdv->getComment(),
  5567.             "note" => $rdv->getNote(),
  5568.             "review" => $rdv->getReview(),
  5569.             "status" => 200,
  5570.         ])));
  5571.     }
  5572.     /**
  5573.      * @Route("/rdv/calendar", name="postRdvCalendar", methods={"POST"})
  5574.      */
  5575.     public function postRdvCalendar(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSmsPublisherInterface $publisher): Response
  5576.     {
  5577.         $data json_decode($request->getContent(), true);
  5578.         if (!isset($data["token"])) {
  5579.             return new Response(json_encode([
  5580.                 "message" => "Pas de token n'a été spécifié",
  5581.                 "status" => 401,
  5582.             ]), 401);
  5583.         }
  5584.         $entityManager $this->getDoctrine()->getManager();
  5585.         /** @var Token */
  5586.         $token $this->getDoctrine()
  5587.             ->getRepository(Token::class)
  5588.             ->findOneBy(['token' => $data["token"]]);
  5589.         if (!$token) {
  5590.             return new Response(json_encode([
  5591.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5592.                 "status" => 404,
  5593.             ]), 404);
  5594.         }
  5595.         // get token age
  5596.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5597.         // if the token if older than 7 days
  5598.         if ($dateDiff->7) {
  5599.             $entityManager->remove($token);
  5600.             $entityManager->flush();
  5601.             return $this->json([
  5602.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5603.                 'path' => 'src/Controller/ClientController.php',
  5604.                 "status" => 401,
  5605.             ], 401);
  5606.         }
  5607.         // makes the rdv
  5608.         $rdv = new Rdv();
  5609.         if ($token->getIdAudio()) {
  5610.             //if the token if for an audio
  5611.             $audio $token->getIdAudio();
  5612.             if ((isset($data["client_id"]))) {
  5613.                 $client $this->getDoctrine()
  5614.                     ->getRepository(Client::class)
  5615.                     ->findOneBy(['id' => $data["client_id"]]);
  5616.             } else {
  5617.                 $client $this->getDoctrine()
  5618.                     ->getRepository(ClientTemp::class)
  5619.                     ->findOneBy(['id' => $data["client_id_temp"]]);
  5620.             }
  5621.             if ($client == null) {
  5622.                 return new Response(json_encode(([
  5623.                     'message' => 'Error, no client found at this id',
  5624.                     'path' => 'src/Controller/RdvController.php',
  5625.                     "status" => 400,
  5626.                 ])), 400);
  5627.             }
  5628.         } elseif ($token->getIdClient()) {
  5629.             //if the token if for a client
  5630.             $client $token->getIdClient();
  5631.             /** @var Audio */
  5632.             $audio $this->getDoctrine()
  5633.                 ->getRepository(Audio::class)
  5634.                 ->findOneBy(['id' => $data["audio_id"]]);
  5635.             if (isset($data["proche_id"])) {
  5636.                 $proche $this->getDoctrine()
  5637.                     ->getRepository(Proches::class)
  5638.                     ->findOneBy(['id' => $data["proche_id"], "id_client" => $client]);
  5639.             }
  5640.             if ($audio == null) {
  5641.                 return new Response(json_encode(([
  5642.                     'message' => 'Error, no audio found at this id',
  5643.                     'path' => 'src/Controller/RdvController.php',
  5644.                     "status" => 400,
  5645.                 ])), 400);
  5646.             }
  5647.         } else {
  5648.             return new Response(json_encode(([
  5649.                 'message' => 'Error, token is not an audio token',
  5650.                 'path' => 'src/Controller/RdvController.php',
  5651.                 "status" => 400,
  5652.             ])), 400);
  5653.         }
  5654.         $rdv->setIdAudio($audio);
  5655.         if (isset($proche)) {
  5656.             $rdv->setIdProche($proche);
  5657.         }
  5658.         if (isset($data["client_id_temp"])) {
  5659.             $rdv->setIdClientTemp($client);
  5660.         } else {
  5661.             $rdv->setIdClient($client);
  5662.         }
  5663.         $rdv->setCacher(0);
  5664.         /** @var Centre */
  5665.         if (isset($data["centre_id"])) {
  5666.             $centre $this->getDoctrine()
  5667.                 ->getRepository(Centre::class)
  5668.                 ->findOneBy(['id' => $data["centre_id"]]);
  5669.             if ($centre == null) {
  5670.                 return new Response(json_encode(([
  5671.                     'message' => 'Error, no centre found at this id',
  5672.                     'path' => 'src/Controller/RdvController.php',
  5673.                     "status" => 400,
  5674.                 ])), 400);
  5675.             }
  5676.             /** @var AudioCentre */
  5677.             $liaison $this->getDoctrine()
  5678.                 ->getRepository(AudioCentre::class)
  5679.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  5680.             if ($liaison == null) {
  5681.                 return new Response(json_encode(([
  5682.                     'message' => 'Error, audio isnt part of the centre',
  5683.                     'path' => 'src/Controller/RdvController.php',
  5684.                     "status" => 400,
  5685.                 ])), 400);
  5686.             }
  5687.             $rdv->setIdCentre($centre);
  5688.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  5689.             // tries to set the lieu if it's an audio indie
  5690.             $lieu $this->getDoctrine()
  5691.                 ->getRepository(Lieu::class)
  5692.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  5693.             if ($lieu == null) {
  5694.                 return new Response(json_encode(([
  5695.                     'message' => 'Error, no lieu found at this id',
  5696.                     'path' => 'src/Controller/RdvController.php',
  5697.                     "status" => 400,
  5698.                 ])), 400);
  5699.             }
  5700.             $rdv->setIdLieu($lieu);
  5701.         } else {
  5702.             return new Response(json_encode(([
  5703.                 'message' => 'Error, no lieu/centre id',
  5704.                 'path' => 'src/Controller/RdvController.php',
  5705.                 "status" => 400,
  5706.             ])), 400);
  5707.         }
  5708.         /** @var Motif */
  5709.         $motif $this->getDoctrine()
  5710.             ->getRepository(Motif::class)
  5711.             ->find($data["motif_id"]);
  5712.         if ($motif == null) {
  5713.             return new Response(json_encode(([
  5714.                 'message' => 'Error, no motif found at this id',
  5715.                 'path' => 'src/Controller/RdvController.php',
  5716.                 "status" => 400,
  5717.             ])), 400);
  5718.         }
  5719.         /** @var AudioMotif */
  5720.         $audioMotif $this->getDoctrine()
  5721.             ->getRepository(AudioMotif::class)
  5722.             ->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
  5723.         if ($audioMotif == null) {
  5724.             return new Response(json_encode(([
  5725.                 'message' => 'Error, no motif of this id found at this audio',
  5726.                 'path' => 'src/Controller/RdvController.php',
  5727.                 "status" => 400,
  5728.             ])), 400);
  5729.         }
  5730.         // remove the taken schedule by rdv to make sure there is no overlap
  5731.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  5732.         if (isset($data["note"])) {
  5733.             $rdv->setNote($data["note"]);
  5734.         }
  5735.         // test if the audio is available
  5736.         /*   if (isset($data["lieu_id"]) && $audio->getIsIndie()){
  5737.             if ($publicFunction->calculScheduleFitDate($audio, $date, $audioMotif->getDuration(), null, $lieu) == false) {
  5738.                 return new Response(json_encode(([
  5739.                     'message' => 'Error, no timestamp found at this time',
  5740.                     'path' => 'src/Controller/RdvController.php',
  5741.                     "status" => 400,
  5742.                 ])), 400);
  5743.             }
  5744.         } else {
  5745.             if ($publicFunction->calculScheduleFitDate($audio, $date, $audioMotif->getDuration(), $centre , null) == true) {
  5746.                 return new Response(json_encode(([
  5747.                     'message' => 'Error, no timestamp found at this time',
  5748.                     'path' => 'src/Controller/RdvController.php',
  5749.                     "status" => 400,
  5750.                 ])), 400);
  5751.             }
  5752.         }*/
  5753.         $rdv->setDate($date);
  5754.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  5755.         /** @var EtatRdv */
  5756.         $etat $this->getDoctrine()
  5757.             ->getRepository(EtatRdv::class)
  5758.             ->findOneBy(['id' => $data["etat_id"]]);
  5759.         if ($etat == null) {
  5760.             return new Response(json_encode(([
  5761.                 'message' => 'Error, no etat found at this id',
  5762.                 'path' => 'src/Controller/RdvController.php',
  5763.                 "status" => 400,
  5764.             ])), 400);
  5765.         }
  5766.         $rdv->setIdEtat($etat);
  5767.         $rdv->setIdMotif($motif);
  5768.         $rdv->setDuration($data["duree"]);
  5769.         $rdv->setIsAbsence($data["is_absence"]);
  5770.         $entityManager $this->getDoctrine()->getManager();
  5771.         $entityManager->persist($rdv);
  5772.         $entityManager->flush();
  5773.         $date $rdv->getDate();
  5774.         $smsDate $date->format('d-m-Y H:i');
  5775.         $locale 'fr_FR';
  5776.         $formatter = new IntlDateFormatter(
  5777.             $locale,
  5778.             IntlDateFormatter::FULL,
  5779.             IntlDateFormatter::SHORT,
  5780.             null,
  5781.             IntlDateFormatter::GREGORIAN,
  5782.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  5783.         );
  5784.         $smsDateLongFormat $formatter->format($date);
  5785.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  5786.         // client notif mail Sms
  5787.         // we send parametre for the trait methid
  5788.         //$params = $this->emailNotificationService->prepareEmailParams($user);
  5789.         // send email notifcation
  5790.         //$this->emailNotificationService->sendEmail($params, 'admin@example.com', 'Nouvelle inscription à My Audio Pro', 1);
  5791.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  5792.         $frenchDate ucfirst($frenchDate);
  5793.         $params = array(
  5794.             "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5795.             "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5796.             "date" => $smsDateLongFormat,
  5797.             "prenom" => $client->getName(),
  5798.             //"heure" => $smsDatee,
  5799.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  5800.             "centerName" => $rdv->getIdCentre()->getName(),
  5801.             "centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  5802.             "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  5803.             "centerCity" => $rdv->getIdCentre()->getCity(),
  5804.             "motif" => $rdv->getIdMotif()->getTitre(),
  5805.             "RdvDate" => substr($smsDate010) . " à "  substr($smsDate1115),
  5806.             "audioName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  5807.             "clientMail" => $client->getMail(),
  5808.             "clientPhone" => $client->getPhone(),
  5809.             'titre' => "Votre rendez-vous est validé le " substr($smsDate010) . " à "  substr($smsDate1115),
  5810.             "address" => $rdv->getIdCentre()->getAddress(),
  5811.             "postal" => $rdv->getIdCentre()->getPostale(),
  5812.             "city" => $rdv->getIdCentre()->getCity(),
  5813.             "clientEmail" => $client->getMail(),
  5814.             "clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
  5815.             "clientAddress" => $client->getAddress(),
  5816.             "clientPostal" => $client->getPostal(),
  5817.             "clientCity" => $client->getCity(),
  5818.             "audioName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  5819.             "frenchDate" => $frenchDate,
  5820.             "heure" => substr($smsDate1115),
  5821.             "centerName" => $rdv->getIdCentre()->getName(),
  5822.             "audioMail" => $rdv->getIdAudio()->getMail(),
  5823.             "modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5824.         );
  5825.         $subject "Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  5826.         $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject181);
  5827.         $sms "Votre RDV est validé le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  5828.         // $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone());
  5829.         // audio Notif mail SMS
  5830.         /* $params = array(  
  5831.                         "lienModifer" =>"{$_ENV['BASE_logiciel']}rdv",
  5832.                         "lienAnnule"=> "{$_ENV['BASE_logiciel']}rdv",
  5833.                         "date" => substr($smsDate, 0, 10),
  5834.                         "heure" =>substr($smsDate, 11, 15),
  5835.                         'motif' => $rdv->getIdMotif()->getTitre(),
  5836.                         'clientPhone'=> $client->getPhone(),
  5837.                         'clientNom' =>$client->getLastname(),
  5838.                         'clientPrenom' =>$client->getName(),
  5839.                         'clientCivilite' => $client->getCivilite(),
  5840.                         'clientPostal' => $client->getPostal(),
  5841.                         'clientMail' => $client->getMail(),
  5842.                         'centerName' => $rdv->getIdCentre()->getName(),
  5843.                         'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5844.                         'centerCity' => $rdv->getIdCentre()->getCity(),
  5845.                         'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5846.                         'idPatient' => $client->getId(),
  5847.                         'proUrl' => "{$_ENV['BASE_logiciel']}",
  5848.                         'audioproName' => $rdv->getIdAudio()->getCivilite().' '.$rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(),
  5849.                         'titre' => 'Votre rendez-vous est modifié pour le :'
  5850.                     );
  5851.         $subject = "🔀 Rendez-vous My Audio modifié du ". $frenchDate . " à " . substr($smsDate, 11, 15);
  5852.         $publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(), $subject, 186 );
  5853.         $sms = "Vous avez un nouveau RDV le " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15) . ", en cas d'aléas contactez votre patient " . $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  5854.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());*/
  5855.         // google calendar post
  5856.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  5857.             ->findBy(array('audio' => $audio->getId()));
  5858.         $data['rdv'] = $rdv->getId();
  5859.         $synchronisationCosium $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $audio->getId()]);
  5860.         $cosiumCenter $this->getDoctrine()->getRepository(CosiumCenter::class)->findOneBy(["synchronisationCosium" => $synchronisationCosium"center" => $rdv->getIdCentre()]);
  5861.         if ($cosiumCenter) {
  5862.             $this->clientCosiumService->createAgenda($synchronisationCosium$rdv$cosiumCenter);
  5863.         }
  5864.         foreach ($synchronisations as $synchronisation) {
  5865.             if (!$synchronisation->getIsDeleted()) {
  5866.                 try {
  5867.                     $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  5868.                     $googleCalendar->createEvent($synchronisation$data);
  5869.                 } catch (\Exception $e) {
  5870.                     error_log('Error refreshing access token or creating event: ' $e->getMessage());
  5871.                 }
  5872.             }
  5873.         }
  5874.         // create schedule notification sms
  5875.         $rdvSms->storeRdvSmsNotifications($rdv);
  5876.         if ($rdv->getClientDevice()) {
  5877.             $nextRdv $this->getDoctrine()
  5878.                 ->getRepository(Rdv::class)
  5879.                 ->find($rdv->getClientDevice()->getRdv()->getId());
  5880.             if ($nextRdv->getIdClientTemp()) {
  5881.                 $nextRdvs $this->getDoctrine()
  5882.                     ->getRepository(Rdv::class)
  5883.                     ->findBy([
  5884.                         "id_client_temp" => $nextRdv->getIdClientTemp(),
  5885.                         "id_motif" => ['106''107''108''109']
  5886.                     ]);
  5887.             } else {
  5888.                 $nextRdvs $this->getDoctrine()
  5889.                     ->getRepository(Rdv::class)
  5890.                     ->findBy([
  5891.                         "id_client" => $nextRdv->getIdClient(),
  5892.                         "id_motif" => ['106''107''108''109']
  5893.                     ]);
  5894.             }
  5895.             $mappedNextRdvs array_map(function ($rdv) {
  5896.                 return [
  5897.                     'id' => $rdv->getId(),
  5898.                     'date' => $rdv->getDate()->format('d-m-Y'),
  5899.                     'hours' => $rdv->getDate()->format('H:i'),
  5900.                     'duration' => $rdv->getDuration(),
  5901.                     "motif_id" => $rdv->getIdMotif()->getId(),
  5902.                     "motif_titre" => $rdv->getIdMotif()->getTitre(),
  5903.                     "duration" => $rdv->getDuration(),
  5904.                 ];
  5905.             }, $nextRdvs);
  5906.         }
  5907. $token $this->entityManager
  5908.      ->getRepository(Token::class)
  5909.      ->findOneBy(['token' => $data['token']]);
  5910. $tokenAudioId $token->getIdAudio()->getId();
  5911. $requestAudioId $data['audio_id'] ?? null;
  5912. $requestCenterId $data['center_id'] ?? null;
  5913. // Check audio
  5914. if ($requestAudioId && $requestAudioId == $tokenAudioId) {
  5915.     // Verify center belongs to this audio
  5916.     $centre $this->entityManager
  5917.         ->getRepository(Centre::class)
  5918.         ->findOneBy(['id_gerant' => $tokenAudioId]);
  5919.     if ($centre && $centre->getId() == $requestCenterId) {
  5920.         // All conditions ok → send mercure update
  5921.         $this->mercure->publishRdvUpdate($rdv'created');
  5922.     }
  5923. }
  5924.         return new Response(json_encode(([
  5925.             "id" => $rdv->getId(),
  5926.             "motif_id" => $rdv->getIdMotif()->getId(),
  5927.             "audio_id" => $rdv->getIdAudio()->getId(),
  5928.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  5929.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  5930.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  5931.             "centerName" => $rdv->getIdCentre()->getName(),
  5932.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  5933.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  5934.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  5935.             "duration" => $data["duree"],
  5936.             "etat_id" => $rdv->getIdEtat()->getId(),
  5937.             "date" => $rdv->getDate(),
  5938.             "clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
  5939.             "isClient" => ($client instanceof Client) ? 0,
  5940.             "device" => $rdv->getClientDevice() ? [
  5941.                 "isDevice" => true,
  5942.                 "deviceID" => $rdv->getClientDevice()->getDevice()->getId(),
  5943.                 "clientDeviceID" => $rdv->getClientDevice()->getId(),
  5944.                 "deviceModel" => $rdv->getClientDevice()->getDevice()->getModel(),
  5945.                 "settingName" => $rdv->getClientDevice()->getSettingDevice()->getName(),
  5946.                 "settingDeviceId" => $rdv->getClientDevice()->getSettingDevice()->getSlug(),
  5947.                 "settingSlug" => $rdv->getClientDevice()->getSettingDevice()->getSlug(),
  5948.                 "nextRdvs" => $mappedNextRdvs
  5949.             ] : [
  5950.                 "isDevice" => false
  5951.             ],
  5952.             "comment" => $rdv->getComment(),
  5953.             "review" => $rdv->getReview(),
  5954.             "note" => $rdv->getNote(),
  5955.             "status" => 200,
  5956.         ])));
  5957.     }
  5958.     /**
  5959.      * @Route("/rdv/absence", name="postAbsenceCalendar", methods={"POST"})
  5960.      */
  5961.     public function postAbsenceCalendar(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendar): Response
  5962.     {
  5963.         $data json_decode($request->getContent(), true);
  5964.         if (!isset($data["token"])) {
  5965.             return new Response(json_encode([
  5966.                 "message" => "Pas de token n'a été spécifié",
  5967.                 "status" => 401,
  5968.             ]), 401);
  5969.         }
  5970.         $entityManager $this->getDoctrine()->getManager();
  5971.         /** @var Token */
  5972.         $token $this->getDoctrine()
  5973.             ->getRepository(Token::class)
  5974.             ->findOneBy(['token' => $data["token"]]);
  5975.         if (!$token) {
  5976.             return new Response(json_encode([
  5977.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5978.                 "status" => 404,
  5979.             ]), 404);
  5980.         }
  5981.         // get token age
  5982.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5983.         // if the token if older than 7 days
  5984.         if ($dateDiff->7) {
  5985.             $entityManager->remove($token);
  5986.             $entityManager->flush();
  5987.             return $this->json([
  5988.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5989.                 'path' => 'src/Controller/ClientController.php',
  5990.                 "status" => 401,
  5991.             ], 401);
  5992.         }
  5993.         // makes the rdv
  5994.         $rdv = new Rdv();
  5995.         $audio $token->getIdAudio();
  5996.         $rdv->setIdAudio($audio);
  5997.         /** @var Centre */
  5998.         if (isset($data["centre_id"])) {
  5999.             $centre $this->getDoctrine()
  6000.                 ->getRepository(Centre::class)
  6001.                 ->findOneBy(['id' => $data["centre_id"]]);
  6002.             if ($centre == null) {
  6003.                 return new Response(json_encode(([
  6004.                     'message' => 'Error, no centre found at this id',
  6005.                     'path' => 'src/Controller/RdvController.php',
  6006.                     "status" => 400,
  6007.                 ])), 400);
  6008.             }
  6009.             /** @var AudioCentre */
  6010.             $liaison $this->getDoctrine()
  6011.                 ->getRepository(AudioCentre::class)
  6012.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  6013.             if ($liaison == null) {
  6014.                 return new Response(json_encode(([
  6015.                     'message' => 'Error, audio isnt part of the centre',
  6016.                     'path' => 'src/Controller/RdvController.php',
  6017.                     "status" => 400,
  6018.                 ])), 400);
  6019.             }
  6020.             $rdv->setIdCentre($centre);
  6021.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  6022.             // tries to set the lieu if it's an audio indie
  6023.             $lieu $this->getDoctrine()
  6024.                 ->getRepository(Lieu::class)
  6025.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  6026.             if ($lieu == null) {
  6027.                 return new Response(json_encode(([
  6028.                     'message' => 'Error, no lieu found at this id',
  6029.                     'path' => 'src/Controller/RdvController.php',
  6030.                     "status" => 400,
  6031.                 ])), 400);
  6032.             }
  6033.             $rdv->setIdLieu($lieu);
  6034.         } else {
  6035.             return new Response(json_encode(([
  6036.                 'message' => 'Error, no lieu/centre id',
  6037.                 'path' => 'src/Controller/RdvController.php',
  6038.                 "status" => 400,
  6039.             ])), 400);
  6040.         }
  6041.         // remove the taken schedule by rdv to make sure there is no overlap
  6042.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  6043.         $rdv->setDate($date);
  6044.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  6045.         /** @var EtatRdv */
  6046.         $etat $this->getDoctrine()
  6047.             ->getRepository(EtatRdv::class)
  6048.             ->findOneBy(['id' => $data["etat_id"]]);
  6049.         if ($etat == null) {
  6050.             return new Response(json_encode(([
  6051.                 'message' => 'Error, no etat found at this id',
  6052.                 'path' => 'src/Controller/RdvController.php',
  6053.                 "status" => 400,
  6054.             ])), 400);
  6055.         }
  6056.         $rdv->setIdEtat($etat);
  6057.         $rdv->setDuration($data["duree"]);
  6058.         $rdv->setIsAbsence($data["is_absence"]);
  6059.         $rdv->setMotifAbsence($data["motif"]);
  6060.         $rdv->setColor($data["color"]);
  6061.         $rdv->setNote($data["note"]);
  6062.         $rdv->setCacher(0);
  6063.         $entityManager $this->getDoctrine()->getManager();
  6064.         $entityManager->persist($rdv);
  6065.         $entityManager->flush();
  6066.         // create google calendar absence event
  6067.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  6068.             ->findBy(array('audio' => $audio->getId()));
  6069.         $data['rdv'] = $rdv->getId();
  6070.         $data['motif_absence'] = $rdv->getMotifAbsence() !== '' $rdv->getMotifAbsence() : "Absence";
  6071.         //        dd($data);
  6072.         foreach ($synchronisations as $synchronisation) {
  6073.             if (!$synchronisation->getIsDeleted()) {
  6074.                 try {
  6075.                     $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  6076.                     $googleCalendar->createAbsenceEvent($synchronisation$data);
  6077.                 } catch (\Google\Service\Exception $e) {
  6078.                     if ($e->getCode() === 403 && str_contains($e->getMessage(), 'insufficientPermissions')) {
  6079.                         error_log("Skipped synchronisation ID {$synchronisation->getId()} due to insufficient permissions.");
  6080.                         continue;
  6081.                     }
  6082.                     throw $e;
  6083.                 }
  6084.             }
  6085.         }
  6086.         return new Response(json_encode(([
  6087.             "id" => $rdv->getId(),
  6088.             "audio_id" => $rdv->getIdAudio()->getId(),
  6089.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  6090.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  6091.             "duration" => $data["duree"],
  6092.             "etat_id" => $rdv->getIdEtat()->getId(),
  6093.             "date" => $rdv->getDate(),
  6094.             "status" => 200,
  6095.         ])));
  6096.     }
  6097.     /**
  6098.      * @Route("/rdv/{id}/absence", name="puttAbsenceCalendar", methods={"PUT"})
  6099.      */
  6100.     public function putAbsenceCalendar(Request $requestRdv $rdvPublicFunction $publicFunctionGoogleCalendarService $googleCalendar): Response
  6101.     {
  6102.         $data json_decode($request->getContent(), true);
  6103.         if (!isset($data["token"])) {
  6104.             return new Response(json_encode([
  6105.                 "message" => "Pas de token n'a été spécifié",
  6106.                 "status" => 401,
  6107.             ]), 401);
  6108.         }
  6109.         $entityManager $this->getDoctrine()->getManager();
  6110.         /** @var Token */
  6111.         $token $this->getDoctrine()
  6112.             ->getRepository(Token::class)
  6113.             ->findOneBy(['token' => $data["token"]]);
  6114.         if (!$token) {
  6115.             return new Response(json_encode([
  6116.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6117.                 "status" => 404,
  6118.             ]), 404);
  6119.         }
  6120.         // get token age
  6121.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6122.         // if the token if older than 7 days
  6123.         if ($dateDiff->7) {
  6124.             $entityManager->remove($token);
  6125.             $entityManager->flush();
  6126.             return $this->json([
  6127.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6128.                 'path' => 'src/Controller/ClientController.php',
  6129.                 "status" => 401,
  6130.             ], 401);
  6131.         }
  6132.         // remove the taken schedule by rdv to make sure there is no overlap
  6133.         if (isset($data["date"])) {
  6134.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  6135.             $rdv->setDate($date);
  6136.         }
  6137.         if (isset($data["duree"])) {
  6138.             $rdv->setDuration($data["duree"]);
  6139.         }
  6140.         if (isset($data["motif"])) {
  6141.             $rdv->setMotifAbsence($data["motif"]);
  6142.         }
  6143.         if (isset($data["color"])) {
  6144.             $rdv->setColor($data["color"]);
  6145.         }
  6146.         if (isset($data["note"])) {
  6147.             $rdv->setNote($data["note"]);
  6148.         }
  6149.         $entityManager $this->getDoctrine()->getManager();
  6150.         $entityManager->flush();
  6151.         $data['rdv'] = $rdv->getId();
  6152.         $data['motif_absence'] = $rdv->getMotifAbsence() !== '' $rdv->getMotifAbsence() : "Absence";
  6153.         $data['note'] = $rdv->getNote();
  6154.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  6155.             ->findBy(array('rdv' => $rdv));
  6156.         foreach ($rdvEvents as $rdvEvent) {
  6157.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  6158.             $googleCalendar->updateAbsenceEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  6159.         }
  6160.         return new Response(json_encode(([
  6161.             "id" => $rdv->getId(),
  6162.             "audio_id" => $rdv->getIdAudio()->getId(),
  6163.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  6164.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  6165.             "duration" => $rdv->getDuration(),
  6166.             "etat_id" => $rdv->getIdEtat()->getId(),
  6167.             "date" => $rdv->getDate(),
  6168.             "status" => 200,
  6169.         ])));
  6170.     }
  6171.     /**
  6172.      * @Route("/rdv/{id}/calendar", name="editRdvCalendarByID", methods={"PUT"})
  6173.      */
  6174.     public function editRdvCalendarByID(SmsHandler $smsHandlerRdv $rdvRequest $requestGoogleCalendarService $googleCalendarPublicFunction $publicFunctionRdvSmsService $rdvSms): Response
  6175.     {
  6176.         $pastDate $rdv->getDate();
  6177.         $data json_decode($request->getContent(), true);
  6178.         $entityManager $this->getDoctrine()->getManager();
  6179.         if (!isset($data["token"])) {
  6180.             return new Response(json_encode([
  6181.                 "message" => "Pas de token n'a été spécifié",
  6182.                 "status" => 401,
  6183.             ]), 401);
  6184.         }
  6185.         /** @var Token */
  6186.         $token $this->getDoctrine()
  6187.             ->getRepository(Token::class)
  6188.             ->findOneBy(['token' => $data["token"]]);
  6189.         if (!$token) {
  6190.             return new Response(json_encode([
  6191.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6192.                 "status" => 404,
  6193.             ]), 404);
  6194.         }
  6195.         // get token age
  6196.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6197.         // if the token if older than 7 days
  6198.         if ($dateDiff->7) {
  6199.             $entityManager->remove($token);
  6200.             $entityManager->flush();
  6201.             return $this->json([
  6202.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6203.                 'path' => 'src/Controller/ClientController.php',
  6204.                 "status" => 401,
  6205.             ], 401);
  6206.         }
  6207.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  6208.             return new Response(json_encode([
  6209.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  6210.                 "status" => 404,
  6211.             ]), 404);
  6212.         }
  6213.         if (isset($data["etat_id"])) {
  6214.             $etat $this->getDoctrine()
  6215.                 ->getRepository(EtatRdv::class)
  6216.                 ->findOneBy(['id' => $data["etat_id"]]);
  6217.             if ($etat == null) {
  6218.                 return new Response(json_encode(([
  6219.                     'message' => 'Error, no etat found at this id',
  6220.                     'path' => 'src/Controller/TrustedUserController.php',
  6221.                     "status" => 400,
  6222.                 ])), 400);
  6223.             }
  6224.             $rdv->setIdEtat($etat);
  6225.         }
  6226.         if (isset($data["audio_id"])) {
  6227.             $audio $this->getDoctrine()
  6228.                 ->getRepository(Audio::class)
  6229.                 ->findOneBy(['id' => $data["audio_id"]]);
  6230.             if ($audio == null) {
  6231.                 return new Response(json_encode(([
  6232.                     'message' => 'Error, no audio found at this id',
  6233.                     'path' => 'src/Controller/TrustedUserController.php',
  6234.                     "status" => 400,
  6235.                 ])), 400);
  6236.             }
  6237.             $rdv->setIdAudio($audio);
  6238.         }
  6239.         if (isset($data["motif_id"])) {
  6240.             $motif $this->getDoctrine()
  6241.                 ->getRepository(Motif::class)
  6242.                 ->find($data["motif_id"]);
  6243.             if ($motif == null) {
  6244.                 return new Response(json_encode(([
  6245.                     'message' => 'Error, no motif found at this id',
  6246.                     'path' => 'src/Controller/TrustedUserController.php',
  6247.                     "status" => 400,
  6248.                 ])), 400);
  6249.             }
  6250.             $rdv->setIdMotif($motif);
  6251.         }
  6252.         if (isset($data["client_id"])) {
  6253.             $client $this->getDoctrine()
  6254.                 ->getRepository(Client::class)
  6255.                 ->findOneBy(['id' => $data["client_id"]]);
  6256.             if ($client == null) {
  6257.                 return new Response(json_encode(([
  6258.                     'message' => 'Error, no client found at this id',
  6259.                     'path' => 'src/Controller/TrustedUserController.php',
  6260.                     "status" => 400,
  6261.                 ])), 400);
  6262.             }
  6263.             $rdv->setIdClient($client);
  6264.         }
  6265.         if (isset($data["date"])) {
  6266.             // remove the taken schedule by rdv to make sure there is no overlap
  6267.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  6268.             $audioMotif $this->getDoctrine()
  6269.                 ->getRepository(AudioMotif::class)
  6270.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  6271.             if ($audioMotif == null) {
  6272.                 return new Response(json_encode(([
  6273.                     'message' => 'Error, no motif of this id found at this audio',
  6274.                     'path' => 'src/Controller/RdvController.php',
  6275.                     "status" => 400,
  6276.                 ])), 400);
  6277.             }
  6278.             if ($rdv->getIdAudio()->getIsIndie()) {
  6279.                 if ($rdv->getIdCentre()) {
  6280.                     // regular centre audio indie
  6281.                     /** @var AudioCentre */
  6282.                     $liaison $this->getDoctrine()
  6283.                         ->getRepository(AudioCentre::class)
  6284.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  6285.                     if ($liaison == null) {
  6286.                         return new Response(json_encode(([
  6287.                             'message' => 'Error, audio isnt part of the centre',
  6288.                             'path' => 'src/Controller/RdvController.php',
  6289.                             "status" => 400,
  6290.                         ])), 400);
  6291.                     }
  6292.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  6293.                         return new Response(json_encode(([
  6294.                             'message' => 'Error, no horaire found for this audio',
  6295.                             'path' => 'src/Controller/RdvController.php',
  6296.                             "status" => 400,
  6297.                         ])), 400);
  6298.                     }
  6299.                 } else {
  6300.                     // lieu audio indie
  6301.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  6302.                         return new Response(json_encode(([
  6303.                             'message' => 'Error, no horaire found for this audio',
  6304.                             'path' => 'src/Controller/RdvController.php',
  6305.                             "status" => 400,
  6306.                         ])), 400);
  6307.                     }
  6308.                 }
  6309.             } else {
  6310.                 // regular centre
  6311.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  6312.                     return new Response(json_encode(([
  6313.                         'message' => 'Error, no horaire found for this audio',
  6314.                         'path' => 'src/Controller/RdvController.php',
  6315.                         "status" => 400,
  6316.                     ])), 400);
  6317.                 }
  6318.             }
  6319.             $rdv->setDate($date);
  6320.         }
  6321.         if (isset($data["comment"]) && $token->getIdClient()) {
  6322.             $rdv->setComment($data["comment"]);
  6323.         }
  6324.         if (isset($data["review"]) && $token->getIdClient()) {
  6325.             $rdv->setReview($data["review"]);
  6326.         }
  6327.         if (isset($data["note"])) {
  6328.             $rdv->setNote($data["note"]);
  6329.         }
  6330.         $entityManager->flush();
  6331.         $date $rdv->getDate();
  6332.         $smsDate $date->format('d-m-Y H:i');
  6333.         $oldDate $pastDate->format('d-m-Y H:i');
  6334.         $locale 'fr_FR';
  6335.         $formatter = new IntlDateFormatter(
  6336.             $locale,
  6337.             IntlDateFormatter::FULL,
  6338.             IntlDateFormatter::SHORT,
  6339.             null,
  6340.             IntlDateFormatter::GREGORIAN,
  6341.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  6342.         );
  6343.         $smsDateLongFormat $formatter->format($date);
  6344.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  6345.         $frenchDate ucfirst($frenchDate);
  6346.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  6347.         // notif client
  6348.         if ($rdv->getIdEtat()->getId() != 2) {
  6349.             $params = array(
  6350.                 "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  6351.                 "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  6352.                 "date" => $smsDateLongFormat,
  6353.                 "heure" => substr($smsDate1115),
  6354.                 "motif" => $rdv->getIdMotif()->getTitre(),
  6355.                 "centerName" => $rdv->getIdCentre()->getName(),
  6356.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  6357.                 "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  6358.                 "audioMail" => $rdv->getIdAudio()->getMail(),
  6359.                 "centerPhone" => $rdv->getIdCentre()->getPhone(),
  6360.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  6361.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  6362.                 'titre' => 'Votre rendez-vous est modifié pour le',
  6363.                 'frenchDate' => $frenchDate,
  6364.             );
  6365.             $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  6366.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  6367.             if ($data["sms"]) {
  6368.                 $sms "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  6369.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  6370.             }
  6371.         }
  6372.         //     //// == suppression
  6373.         else if ($rdv->getIdEtat()->getId() == 2) {
  6374.             $params = array(
  6375.                 "date" => substr($smsDate010),
  6376.                 "lien" => "{$_ENV['BASE_client']}search",
  6377.                 "heure" => substr($smsDate1115),
  6378.                 "patientName" => $client->getLastName(),
  6379.                 'titre' => 'Votre rendez-vous est annulé :',
  6380.                 'centerName' => $rdv->getIdCentre()->getName(),
  6381.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  6382.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  6383.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  6384.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  6385.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6386.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  6387.                 'motif' => $rdv->getIdMotif()->getTitre(),
  6388.             );
  6389.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  6390.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  6391.             if ($data["sms"]) {
  6392.                 $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  6393.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  6394.             }
  6395.         }
  6396.         //notif Audio
  6397.         if ($rdv->getIdEtat()->getId() != 2) {
  6398.             if ($data["sms"]) {
  6399.                 $params = array(
  6400.                     "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  6401.                     "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  6402.                     "date" => substr($smsDate010),
  6403.                     "frenchDate" => $frenchDate,
  6404.                     "heure" => substr($smsDate1115),
  6405.                     'motif' => $rdv->getIdMotif()->getTitre(),
  6406.                     'clientPhone' => $client->getPhone(),
  6407.                     'clientNom' => $client->getLastname(),
  6408.                     'clientPrenom' => $client->getName(),
  6409.                     'clientCivilite' => $client->getCivilite(),
  6410.                     'clientPostal' => $client->getPostal(),
  6411.                     'clientMail' => $client->getMail(),
  6412.                     'centerName' => $rdv->getIdCentre()->getName(),
  6413.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  6414.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  6415.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  6416.                     'idPatient' => $client->getId(),
  6417.                     'proUrl' => "{$_ENV['BASE_logiciel']}",
  6418.                     'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6419.                     'titre' => 'Votre rendez-vous est modifié pour le :'
  6420.                 );
  6421.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  6422.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  6423.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  6424.                     $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  6425.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  6426.                 }
  6427.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  6428.                     $sms "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre patient " $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  6429.                     // $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  6430.                 }
  6431.             }
  6432.         } else if ($rdv->getIdEtat()->getId() == 2) {
  6433.             if ($data["sms"]) {
  6434.                 $params = array(
  6435.                     "date" => substr($smsDate010),
  6436.                     "lien" => "{$_ENV['BASE_client']}search",
  6437.                     "heure" => substr($smsDate1115),
  6438.                     "patientName" => $client->getLastName(),
  6439.                     'titre' => 'Votre rendez-vous est annulé :',
  6440.                     'centerName' => $rdv->getIdCentre()->getName(),
  6441.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  6442.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  6443.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  6444.                     'centerPhone' => $rdv->getIdCentre()->getPhone(),
  6445.                     'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6446.                     'audioMail' => $rdv->getIdAudio()->getMail(),
  6447.                     'motif' => $rdv->getIdMotif()->getTitre(),
  6448.                 );
  6449.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  6450.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  6451.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  6452.                     $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  6453.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject188);
  6454.                 }
  6455.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  6456.                     $sms "Votre RDV du " substr($oldDate010) . " à " substr($oldDate1115) . "a été annulé, vous pouvez contacter votre patient pour fixer un autre RDV:" $client->getPhone() . " pour fixer un autre RDV.\nNe pas répondre.";
  6457.                     //$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  6458.                 }
  6459.             }
  6460.         }
  6461.         /* generate sms notif on update */
  6462.         // update sms notification     
  6463.         $rdvSms->updateRdvSms($rdv);
  6464.         // google calendar update
  6465.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  6466.             ->findBy(array('audio' => $rdv->getIdAudio()));
  6467.         $data['rdv'] = $rdv->getId();
  6468.         $data['motif_id'] = $rdv->getIdMotif();
  6469.         $data['note'] = $rdv->getNote();
  6470.         if ($rdv->getIdClient() !== null) {
  6471.             $data["client_id"] = $rdv->getIdClient()->getId();
  6472.         }
  6473.         if ($rdv->getIdClientTemp() !== null) {
  6474.             $data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
  6475.         }
  6476.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  6477.             ->findBy(array('rdv' => $rdv));
  6478.         foreach ($rdvEvents as $rdvEvent) {
  6479.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  6480.             $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  6481.         }
  6482.         return new Response(json_encode(([
  6483.             "id" => $rdv->getId(),
  6484.             "motif_id" => $rdv->getIdMotif()->getId(),
  6485.             "audio_id" => $rdv->getIdAudio()->getId(),
  6486.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  6487.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  6488.             "fullName" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  6489.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  6490.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  6491.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  6492.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  6493.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  6494.             "centre_id" => $rdv->getIdCentre()->getId(),
  6495.             "centerName" => $rdv->getIdCentre()->getName(),
  6496.             "etat_id" => $rdv->getIdEtat()->getId(),
  6497.             "date" => $rdv->getDate(),
  6498.             "comment" => $rdv->getComment(),
  6499.             "note" => $rdv->getNote(),
  6500.             "review" => $rdv->getReview(),
  6501.             "status" => 200,
  6502.         ])));
  6503.     }
  6504.     /**
  6505.      * @Route("/rdv/{id}/absence", name="deletetAbsenceCalendar", methods={"DELETE"})
  6506.      */
  6507.     public function deletetAbsenceCalendar(Request $requestRdv $rdvGoogleCalendarService $googleCalendar): Response
  6508.     {
  6509.         $data json_decode($request->getContent(), true);
  6510.         if (!isset($data["token"])) {
  6511.             return new Response(json_encode([
  6512.                 "message" => "Pas de token n'a été spécifié",
  6513.                 "status" => 401,
  6514.             ]), 401);
  6515.         }
  6516.         $entityManager $this->getDoctrine()->getManager();
  6517.         /** @var Token */
  6518.         $token $this->getDoctrine()
  6519.             ->getRepository(Token::class)
  6520.             ->findOneBy(['token' => $data["token"]]);
  6521.         if (!$token) {
  6522.             return new Response(json_encode([
  6523.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6524.                 "status" => 404,
  6525.             ]), 404);
  6526.         }
  6527.         // get token age
  6528.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6529.         // if the token if older than 7 days
  6530.         if ($dateDiff->7) {
  6531.             $entityManager->remove($token);
  6532.             $entityManager->flush();
  6533.             return $this->json([
  6534.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6535.                 'path' => 'src/Controller/ClientController.php',
  6536.                 "status" => 401,
  6537.             ], 401);
  6538.         }
  6539.         // delete google agenda event
  6540.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  6541.             ->findBy(array('rdv' => $rdv));
  6542.         //dd($rdvEvents);
  6543.         foreach ($rdvEvents as $rdvEvent) {
  6544.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  6545.             $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  6546.             $entityManager->remove($rdvEvent);
  6547.             $entityManager->flush();
  6548.         }
  6549.         $entityManager->remove($rdv);
  6550.         $entityManager->flush();
  6551.         return new Response(json_encode(([
  6552.             "message" => "Absence Supprime",
  6553.             "status" => 200,
  6554.         ])));
  6555.     }
  6556.     /**
  6557.      * @Route("/rdvs/facturation/rdv", name="getMyRDV", methods={"GET"})
  6558.      */
  6559.     public function getMyRDV(Request $request): Response
  6560.     {
  6561.         /* $date = new DateTime();
  6562.         $minutes_to_add = 10;
  6563.         $date->add(new DateInterval('PT' . $minutes_to_add . 'M'));
  6564.         $date->setTimezone(new DateTimeZone('Europe/Paris'));
  6565.         $currentDate = $date->format('Y-m-d H:i:00');
  6566.         $toSend = $this->getDoctrine()->getRepository(Rdv::class)
  6567.             ->findRdvsIn10Mins($currentDate); 
  6568.         */
  6569.     }
  6570.     /**
  6571.      * @Route("/rdvs/facturation/lead", name="getMyLead", methods={"GET"})
  6572.      */
  6573.     public function getMyLead(Request $request): Response {}
  6574.     /**
  6575.      * @Route("/rdvs/total-count", name="getRdvCount", methods={"GET"})
  6576.      */
  6577.     public function getRdvCount(Request $request): Response
  6578.     {
  6579.         $rdvs $this->getDoctrine()->getRepository(Rdv::class)->findAll();
  6580.         return new Response(count($rdvs));
  6581.     }
  6582.     /**
  6583.      * @Route("/admin/update-relance/{id}", name="admin_update_relance", methods={"POST"})
  6584.      */
  6585.     public function updateRelance(Request $requestLeadRdv $leadEntityManagerInterface $em): JsonResponse
  6586.     {
  6587.         $data json_decode($request->getContent(), true);
  6588.         $relanceCount $data['relanceCount'] ?? null;
  6589.         if ($relanceCount !== null) {
  6590.             $lead->setRelanceCallCount((int)$relanceCount);
  6591.             $em->flush();
  6592.             return new JsonResponse(['success' => true]);
  6593.         }
  6594.         return new JsonResponse(['success' => false], 400);
  6595.     }
  6596.     /**
  6597.      * @Route("/rdv/lead", name="postLeadRdv", methods={"POST"})
  6598.      */
  6599.     public function postLeadRdv(Request $requestEntityManagerInterface $entityManagerPublicFunction $publicFunctionGoogleCalendarService $googleCalendar): Response
  6600.     {
  6601.         $data json_decode($request->getContent(), true);
  6602.         $today = new DateTime();
  6603.         try {
  6604.             $client null;
  6605.             // Gestion du client via token ou création
  6606.             if (!empty($data['clientToken'])) {
  6607.                 $token $entityManager->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
  6608.                 $client $token $token->getIdClient() : null;
  6609.             } elseif (!empty($data['client'])) {
  6610.                 $clientData $this->createOrGetClient($data['client']);
  6611.                 $client $entityManager->getRepository(Client::class)->find($clientData['id']);
  6612.             }
  6613.             if (!$client) {
  6614.                 return $this->json(["status" => 400"message" => "Client non trouvé ou invalide"], 400);
  6615.             }
  6616.             // Création du rendez-vous LeadRdv
  6617.             $rdvLead = new LeadRdv();
  6618.             $rdvLead->setClient($client);
  6619.             if (isset($data['titleLead'])) {
  6620.                 $rdvLead->setTitleLead($data['titleLead']);
  6621.             }
  6622.             if (isset($data['rangeAge'])) {
  6623.                 $rdvLead->setRangeAge($data['rangeAge']);
  6624.             }
  6625.             if (isset($data['situations'])) {
  6626.                 $rdvLead->setSituationsGene($data['situations']);
  6627.             }
  6628.             if (isset($data['equipe'])) {
  6629.                 $rdvLead->setEquipeAppareil($data['equipe']);
  6630.             }
  6631.             if (isset($data['durationEquipe'])) {
  6632.                 $rdvLead->setDurationEquipeAppareil($data['durationEquipe']);
  6633.             }
  6634.             if (isset($data['bilanAuditif'])) {
  6635.                 $rdvLead->setBilanAuditif($data['bilanAuditif']);
  6636.             }
  6637.             if (isset($data['ordonance'])) {
  6638.                 $rdvLead->setOrdonance($data['ordonance']);
  6639.             }
  6640.             if (isset($data['dateOrdonance'])) {
  6641.                 $rdvLead->setDateOrdonance($data['dateOrdonance']);
  6642.             }
  6643.             if (isset($data['canMove'])) {
  6644.                 $rdvLead->setCanMove($data['canMove']);
  6645.             }
  6646.             if (isset($data['traffic_source'])) {
  6647.                 $rdvLead->setTrafficSource($data['traffic_source']);
  6648.             }
  6649.             if (isset($data['article_name'])) {
  6650.                 $rdvLead->setTrafficLpVersion($data['article_name']);
  6651.             }
  6652.             if (isset($data['lp_version'])) {
  6653.                 $rdvLead->setTrafficArticleName($data['lp_version']);
  6654.             }
  6655.             if (isset($data['isNewLp'])) {
  6656.                 $rdvLead->setIsNewLp($data['isNewLp']);
  6657.                 $leadStatus $entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'demande_contact']);
  6658.                 if ($leadStatus) {
  6659.                     $rdvLead->setLeadStatus($leadStatus);
  6660.                 }
  6661.             }
  6662.             $rdvLead->setDate($today);
  6663.             if (!empty($data['audio'])) {
  6664.                 $audio $entityManager->getRepository(Audio::class)->find($data['audio']);
  6665.                 if ($audio) {
  6666.                     $rdvLead->setAudio($audio);
  6667.                 }
  6668.             }
  6669.             if ($client->getPostal()) {
  6670.                 $centerCount $this->getMatchingCentresCount($client->getPostal());
  6671.                 $rdvLead->setCentersCount($centerCount);
  6672.                 if ($centerCount == 0) {
  6673.                     $leadStatus $entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'hors_zone']);
  6674.                     if ($leadStatus) {
  6675.                         $rdvLead->setLeadStatus($leadStatus);
  6676.                     }
  6677.                 }
  6678.             }
  6679.             // Création du Token
  6680.             $tokenString $publicFunction->generateRandomString(30);
  6681.             $token = (new Token())
  6682.                 ->setCreationDate(new DateTime())
  6683.                 ->setToken($tokenString)
  6684.                 ->setIdClient($client);
  6685.             $entityManager->persist($rdvLead);
  6686.             $entityManager->persist($token);
  6687.             $entityManager->flush();
  6688.             return $this->json([
  6689.                 "id" => $client->getId(),
  6690.                 "idRdvLead" => $rdvLead->getId(),
  6691.                 "name" => $client->getName(),
  6692.                 "lastname" => $client->getLastname(),
  6693.                 "token" => $tokenString,
  6694.                 "code" => $clientData['password'],
  6695.                 "postalCode" => $client->getPostal() ?? null,
  6696.                 "status" => 200,
  6697.             ]);
  6698.         } catch (\Exception $e) {
  6699.             return $this->json(["status" => 500"message" => $e->getMessage()], 500);
  6700.         }
  6701.     }
  6702.     /**
  6703.      * @Route("/testGenerateVoice", name="testGenerateVoice", methods={"GET"})
  6704.      */
  6705.     public function testGenerateVoice(AppointmentCallService $service): Response
  6706.     {
  6707.         // TEST LOCAL$rdv = $this->entityManager->getRepository(Rdv::class)->find(6653);
  6708.         $rdv $this->entityManager->getRepository(Rdv::class)->find(2306);
  6709.         $lead $this->entityManager->getRepository(LeadRdv::class)->find(496);
  6710.         // $service->handleCallCenterAfterRdv(
  6711.         //     $rdv
  6712.         // );
  6713.         // $service->handleReminderCallToPatient(
  6714.         //     $rdv
  6715.         // );
  6716.         $service->handleEquipmentStatusCall($rdv);
  6717.         // $service->handleReminderCallToPatientOneHourBefore(
  6718.         //     $rdv
  6719.         // );
  6720.         // $service->handleCallToPatientAfterRdv(
  6721.         //     $rdv
  6722.         // );
  6723.         // $service->handleFollowupCall15Days($rdv);
  6724.         // $service->handleNewLeadCall($lead, "+33743393532");
  6725.         // $service->handleFollowupCall31Days($rdv);
  6726.         return new Response(json_encode([
  6727.             "status" => 200,
  6728.         ]), 200, ['Content-Type' => 'application/json']);
  6729.     }
  6730.     /**
  6731.      * @Route("/testSynthflow", name="testSynthflow", methods={"POST"})
  6732.      */
  6733.     public function testSynthflow(SynthflowService $service): Response
  6734.     {
  6735.         // TEST LOCAL
  6736.         $lead $this->entityManager->getRepository(LeadRdv::class)->find(496);
  6737.         $service->initiateCall($lead);
  6738.         return new Response(json_encode([
  6739.             "status" => 200,
  6740.         ]), 200, ['Content-Type' => 'application/json']);
  6741.     }
  6742.     /**
  6743.      * Private method to create a new client or get existing one by phone
  6744.      */
  6745.     private function createOrGetClient(array $data): array
  6746.     {
  6747.         $clientRepository $this->entityManager->getRepository(Client::class);
  6748.         // check sur le mail et phone
  6749.         $existingClient $clientRepository->findOneBy(['mail' => $data['email']]);
  6750.         if ($existingClient) {
  6751.             if ($existingClient->getPostal() !== $data['postalCode']) {
  6752.                 $existingClient->setPostal($data['postalCode']);
  6753.                 $this->entityManager->persist($existingClient);
  6754.                 $this->entityManager->flush();
  6755.             }
  6756.             return ['id' => $existingClient->getId(), 'password' => 'Votre mot de passe'];
  6757.         }
  6758.         $randomPassword $this->generateRandomPassword(12);
  6759.         $client = new Client();
  6760.         $client->setLastname($data['lastname']);
  6761.         $client->setBirthdate(null);
  6762.         $client->setName($data['firstname']);
  6763.         $client->setPhone($data['phone']);
  6764.         $client->setMail($data['email']);
  6765.         $client->setSignupDate(new \DateTime());
  6766.         $client->setPassword(password_hash($randomPasswordPASSWORD_DEFAULT));
  6767.         $client->setPostal($data['postalCode']);
  6768.         $client->setAddress($data['address'] ?? null);
  6769.         $client->setCity($data['city'] ?? null);
  6770.         $client->setDesactivate(false);
  6771.         if (isset($data['civilite'])) {
  6772.             $civilite = ($data['civilite'] === 'Homme') ? 'Monsieur' 'Madame';
  6773.             $client->setCivilite($civilite);
  6774.         }
  6775.         $this->entityManager->persist($client);
  6776.         $this->entityManager->flush();
  6777.         return ['id' => $client->getId(), 'password' => $randomPassword];
  6778.     }
  6779.     private function generateRandomPassword($length 10): string
  6780.     {
  6781.         return bin2hex(random_bytes($length 2));
  6782.     }
  6783.     private function getMatchingCentresCount($clientPostal): int
  6784.     {
  6785.         // Récupérer les coordonnées GPS du code postal du client
  6786.         $clientCoordinates $this->entityManager
  6787.             ->getRepository(RegionDepartment::class)
  6788.             ->findOneBy(['codePostal' => $clientPostal]);
  6789.         $clientLat $clientCoordinates $clientCoordinates->getLatitude() : null;
  6790.         $clientLon $clientCoordinates $clientCoordinates->getLongitude() : null;
  6791.         $centres $this->entityManager->getRepository(Centre::class)->findAll();
  6792.         $count 0;
  6793.         foreach ($centres as $centre) {
  6794.             if ($centre->getZoneKm()) {
  6795.                 $latitude $centre->getLatitude();
  6796.                 $longitude $centre->getLongitude();
  6797.                 $radius $centre->getZoneKm();
  6798.                 $postals $this->entityManager->getRepository(RegionDepartment::class)->findPostalsWithinRadius($latitude$longitude$radius);
  6799.                 $postalCodes array_values(array_unique(array_column($postals'code_postal')));
  6800.                 if (in_array($clientPostal$postalCodes)) {
  6801.                     $count++;
  6802.                 }
  6803.             }
  6804.         }
  6805.         return $count;
  6806.     }
  6807.     /**
  6808.      * @Route("/rdv/send-map", name="getRdvMap", methods={"POST"})
  6809.      */
  6810.     public function sendEmailWithMap(Request $requestPublicFunction $publicFunction): Response
  6811.     {
  6812.         $data json_decode($request->getContent(), true);
  6813.         $mail "";
  6814.         $name "";
  6815.         $centre "";
  6816.         if (isset($data['clientToken'])) {
  6817.             $token $this->getDoctrine()->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
  6818.             $client $token->getIdClient();
  6819.             $mail $client->getMail();
  6820.             $name $client->getLastname() . " " $client->getName();
  6821.             $centre $this->getDoctrine()->getRepository(Centre::class)->findOneBy(['id' => $data['centre']['id']]);
  6822.         } else {
  6823.             $mail $data['email'];
  6824.             $name $data['name'];
  6825.         }
  6826.         $locale 'fr_FR';
  6827.         $dateTime DateTime::createFromFormat('d/m/Y H:i'$data['date']);
  6828.         if ($dateTime) {
  6829.             $fmt = new IntlDateFormatter($localeIntlDateFormatter::FULLIntlDateFormatter::NONE);
  6830.             $fmt->setPattern("EEEE dd MMMM");
  6831.             $formattedDate ucfirst($fmt->format($dateTime));
  6832.         } else {
  6833.             $formattedDate "Date invalide";
  6834.         }
  6835.         $params = [
  6836.             'date' => $data['date'],
  6837.             'time' => $data['time'],
  6838.             'frenchDate' => $formattedDate,
  6839.             'clientAddress' => $data['address'],
  6840.             'centerName' => $centre->getName(),
  6841.             'centerAddress' => $centre->getAddress(),
  6842.             'centerPostal' => $centre->getPostale(),
  6843.             'centerCity' => $centre->getCity(),
  6844.             'start' => $data['start'],
  6845.             'end' => $data['end'],
  6846.             'urlApi' => "{$_ENV['BASE_client']}",
  6847.         ];
  6848.         $publicFunction->sendEmail($params$mail$name"Votre Rendez-vous My Audio"198);
  6849.         return new Response(json_encode([
  6850.             "status" => 200,
  6851.             "params" => $params,
  6852.         ]), 200, ['Content-Type' => 'application/json']);
  6853.     }
  6854.     /**
  6855.      * @Route("/rdv/cantmove", name="notifCantMove", methods={"POST"})
  6856.      */
  6857.     public function notifCantMove(Request $requestPublicFunction $publicFunction): Response
  6858.     {
  6859.         $data json_decode($request->getContent(), true);
  6860.         $email "lead.myaudio@gmail.com";
  6861.         $centre "";
  6862.         $type "My Audio";
  6863.         $details "";
  6864.         $picto "❌";
  6865.         $ordo "sans ordo";
  6866.         $subject "";
  6867.         if (isset($data['ordonance'])) {
  6868.             if ($data["ordonance"] == "oui") {
  6869.                 $ordo "avec ordo";
  6870.             }
  6871.         } else {
  6872.             $ordo "";
  6873.         }
  6874.         if (isset($data['centre'])) {
  6875.             $centre $data['centre'];
  6876.             $subject $picto " Lead - demande de contact ne pouvant pas se déplacer " $data['postal'] . " " $ordo;
  6877.         } else {
  6878.             $centre "";
  6879.             $type "Hors Zone";
  6880.             $details "Pas de centre dans la zone";
  6881.             $subject $picto " Lead Hors Zone " $data['postal'] . " " $ordo " ne pouvant pas se déplacer";
  6882.         }
  6883.         $responses = [
  6884.             'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
  6885.             'situations' => isset($data['situations']) ? $data['situations'] : null,
  6886.             'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
  6887.             'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
  6888.             'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
  6889.             'ordonance' => isset($data['ordonance']) ? $data['ordonance'] : null,
  6890.             'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
  6891.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  6892.         ];
  6893.         $department $this->getDepartmentFromPostalCode($data['address']);
  6894.         $data['departmentCode'] = $department['departmentCode'];
  6895.         $data['departmentName'] = $department['departmentName'];
  6896.         $data['regionName'] = $department['regionName'];
  6897.         $data['city'] = $department['city'];
  6898.         $params = [
  6899.             'date' => $data['date'],
  6900.             'time' => $data['time'],
  6901.             'address' => $data['address'],
  6902.             'centre' => $centre,
  6903.             'type' => $type,
  6904.             'details' => $details,
  6905.             'responses' => $responses,
  6906.             'name' => $data['name'],
  6907.             'civilite' => $data['civilite'],
  6908.             'nom' => $data['firstname'],
  6909.             'prenom' => $data['lastname'],
  6910.             'codePostal' => $data['address'],
  6911.             'telephone' => $data['phone'],
  6912.             'email' => $data['email'],
  6913.             'departement' => $data['departmentName'],
  6914.             'ville' => $data['city'],
  6915.             'region' => $data['regionName'],
  6916.             'trangeAge' => isset($data['rangAge']) ? $data['rangAge'] : null,
  6917.             'situationVecu' => isset($data['situations']) ? implode(', '$data['situations']) : null,
  6918.             'dejaEquipe' => isset($data['equipeAppareil']) ? $data['equipeAppareil'] : null,
  6919.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  6920.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  6921.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  6922.         ];
  6923.         $publicFunction->sendEmail($params$email$data['name'], $subject208);
  6924.         return new Response(json_encode([
  6925.             "status" => 200,
  6926.         ]), 200, ['Content-Type' => 'application/json']);
  6927.     }
  6928.     /**
  6929.      * @Route("/rdv/cantmove/v2", name="notifCantMoveV2", methods={"POST"})
  6930.      */
  6931.     public function notifCantMoveV2(Request $requestPublicFunction $publicFunction): Response
  6932.     {
  6933.         $data json_decode($request->getContent(), true);
  6934.         $email "lead.myaudio@gmail.com";
  6935.         $centre "";
  6936.         $type "My Audio";
  6937.         $details "";
  6938.         $picto "❌";
  6939.         $subject "";
  6940.         $audio "";
  6941.         $subject $picto " Lead ne pouvant pas se déplacer";
  6942.         $department $this->getDepartmentFromPostalCode($data['address']);
  6943.         $data['departmentCode'] = $department['departmentCode'];
  6944.         $data['departmentName'] = $department['departmentName'];
  6945.         $data['regionName'] = $department['regionName'];
  6946.         $data['city'] = $department['city'];
  6947.         $password "";
  6948.         $params = [
  6949.             'name' => $data['name'],
  6950.             'civilite' => $data['civilite'],
  6951.             'nom' => $data['firstname'],
  6952.             'prenom' => $data['lastname'],
  6953.             'codePostal' => $data['address'],
  6954.             'telephone' => $data['phone'],
  6955.             'email' => $data['email'],
  6956.             'password' => $data['clientSecretCookie'],
  6957.             'trancheAge' => isset($data['rangAge']) ? $data['rangAge'] : null,
  6958.             'situationVecu' => isset($data['situations']) ? implode(', '$data['situations']) : null,
  6959.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  6960.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  6961.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  6962.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  6963.             'urlLogin' => "{$_ENV['BASE_client']}login"
  6964.         ];
  6965.         // Send email to MyAudio
  6966.         $publicFunction->sendEmail($params$email$data['name'], $subject220);
  6967.         $publicFunction->sendEmail($params'contact@myaudio.fr'$data['name'], $subject220);
  6968.         // Send email to patient
  6969.         $params = [
  6970.             'clientEmail' => $data['email'],
  6971.             'clientPassword' => $data['clientSecretCookie'],
  6972.             'rdv' => "https://www.myaudio.fr/search",
  6973.             'urlLogin' => "{$_ENV['BASE_client']}login"
  6974.         ];
  6975.         $publicFunction->sendEmail($params$data['email'], $data['name'], 'Rendez-vous My Audio - En cours de traitement'219);
  6976.         $rdvLead $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
  6977.         if ($rdvLead) {
  6978.             $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'cant_move']);
  6979.             if ($leadStatus) {
  6980.                 $rdvLead->setLeadStatus($leadStatus);
  6981.                 $this->entityManager->flush();
  6982.             }
  6983.         }
  6984.         return new Response(json_encode([
  6985.             "status" => 200,
  6986.         ]), 200, ['Content-Type' => 'application/json']);
  6987.     }
  6988.     /**
  6989.      * @Route("/rdv/notiflead", name="notifLead", methods={"POST"})
  6990.      */
  6991.     public function notifLeadRdv(Request $requestPublicFunction $publicFunction): Response
  6992.     {
  6993.         $data json_decode($request->getContent(), true);
  6994.         $email "lead.myaudio@gmail.com";
  6995.         $centre "";
  6996.         $type "My Audio";
  6997.         $details "";
  6998.         $picto "❌";
  6999.         $ordo "sans ordo";
  7000.         $subject "";
  7001.         $name "";
  7002.         $postal "";
  7003.         $emailPatient "";
  7004.         if (isset($data['clientToken']) && !empty($data['clientToken'])) {
  7005.             $token $this->getDoctrine()->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
  7006.             $client $token->getIdClient();
  7007.             $name $client->getLastname() . " " $client->getName();
  7008.             $postal $client->getPostal();
  7009.             $emailPatient $client->getMail();
  7010.         } else {
  7011.             if (isset($data['postal'])) {
  7012.                 $postal $data['postal'];
  7013.             }
  7014.             if (isset($data['name'])) {
  7015.                 $name $data['name'];
  7016.             }
  7017.             if (isset($data['email'])) {
  7018.                 $email $data['email'];
  7019.             }
  7020.             if (isset($data['email'])) {
  7021.                 $emailPatient $data['email'];
  7022.             }
  7023.         }
  7024.         if (isset($data["ordonance"])) {
  7025.             if ($data["ordonance"] == "oui") {
  7026.                 $ordo "avec ordo";
  7027.             }
  7028.         }
  7029.         if (isset($data['centre'])) {
  7030.             $centre $data['centre'];
  7031.             $picto "✅";
  7032.             $subject $picto " Lead booké " $postal " " $ordo;
  7033.         } else {
  7034.             $centre "";
  7035.             $type "Hors Zone";
  7036.             $details "Pas de centre dans la zone";
  7037.             $subject $picto " Lead Hors Zone " $postal " " $ordo;
  7038.         }
  7039.         $responses = [
  7040.             'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
  7041.             'situations' => isset($data['situations']) ? $data['situations'] : null,
  7042.             'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
  7043.             'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
  7044.             'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
  7045.             'ordonance' => isset($data['ordonance']) ? $data['ordonance'] : null,
  7046.             'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
  7047.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  7048.         ];
  7049.         $params = [
  7050.             'date' => $data['date'],
  7051.             'time' => $data['time'],
  7052.             'address' => $data['address'],
  7053.             'centre' => $centre,
  7054.             'type' => $type,
  7055.             'details' => $details,
  7056.             'responses' => $responses,
  7057.             'name' => $name,
  7058.             'email' => $emailPatient,
  7059.         ];
  7060.         $publicFunction->sendEmail($params$email$name$subject180);
  7061.         return new Response(json_encode([
  7062.             "status" => 200,
  7063.             "params" => $params,
  7064.             "responses" => $responses
  7065.         ]), 200, ['Content-Type' => 'application/json']);
  7066.     }
  7067.     /**
  7068.      *  Met à jour l'état d'un rendez-vous.
  7069.      *
  7070.      * Cette fonction permet de modifier l'état d'un rendez-vous en fonction des données envoyées
  7071.      * via une requête PUT. Elle effectue plusieurs vérifications, notamment :
  7072.      * - La présence et la validité du token d'authentification.
  7073.      * - L'existence du rendez-vous et du nouvel état.
  7074.      * - L'expiration du token (plus de 7 jours).
  7075.      * 
  7076.      * Si le rendez-vous est marqué comme "Absence injustifiée" (état ID 3), un email et un SMS sont envoyés
  7077.      * au client et à l'équipe MyAudio pour les informer.
  7078.      * 
  7079.      * @Route("api/save-etat-rdv", name="saveEtatRdv", methods={"PUT"})
  7080.      */
  7081.     public function saveEtatRdv(Request $requestPublicFunction $publicFunction): Response
  7082.     {
  7083.         $entityManager $this->getDoctrine()->getManager();
  7084.         $data json_decode($request->getContent(), true);
  7085.         if (!$data['token']) {
  7086.             return new Response(json_encode([
  7087.                 "message" => "Pas de token n'a été spécifié",
  7088.                 "status" => 401,
  7089.             ]), 401);
  7090.         }
  7091.         /** @var Token */
  7092.         $token $this->getDoctrine()
  7093.             ->getRepository(Token::class)
  7094.             ->findOneBy(['token' => $data['token'], 'id_audio' => $data['audio']]);
  7095.         if (!$token) {
  7096.             return new Response(json_encode([
  7097.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  7098.                 "status" => 404,
  7099.             ]), 404);
  7100.         }
  7101.         // get token age
  7102.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  7103.         // if the token if older than 7 days
  7104.         if ($dateDiff->7) {
  7105.             $entityManager->remove($token);
  7106.             $entityManager->flush();
  7107.             return $this->json([
  7108.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  7109.                 'path' => 'src/Controller/ClientController.php',
  7110.                 "status" => 401,
  7111.             ], 401);
  7112.         }
  7113.         $rdv $this->getDoctrine()->getRepository(Rdv::class)->find($data['rdv']);
  7114.         if (!$rdv) {
  7115.             return new Response(json_encode([
  7116.                 "message" => "Rdv not found.",
  7117.                 "status" => 404,
  7118.             ]), 404);
  7119.         }
  7120.         $rdvEtat $this->getDoctrine()
  7121.             ->getRepository(EtatRdv::class)
  7122.             ->find($data['etat']);
  7123.         if (!$rdvEtat) {
  7124.             return new Response(json_encode([
  7125.                 "message" => "Rdv etat not found.",
  7126.                 "status" => 404,
  7127.             ]), 404);
  7128.         }
  7129.         $rdv->setIdEtat($rdvEtat);
  7130.         $entityManager->flush();
  7131.         $encodedNomDuCentre rawurlencode($rdv->getIdCentre()->getName());
  7132.         $urlApi "audioprothesiste/{$rdv->getIdCentre()->getCity()}/{$rdv->getIdCentre()->getPostale()}/{$encodedNomDuCentre}/prise-de-rdvaudioprothesiste-rapide/{$rdv->getIdCentre()->getId()}";
  7133.         if ($rdvEtat->getId() == 3) {
  7134.             // Send email to client
  7135.             $date $rdv->getDate();
  7136.             $smsDate $date->format('d-m-Y H:i');
  7137.             $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  7138.             $params = array(
  7139.                 "date" => substr($smsDate010),
  7140.                 "lien" => "{$_ENV['BASE_client']}$urlApi,
  7141.                 "heure" => substr($smsDate1115),
  7142.                 'centerName' => $rdv->getIdCentre()->getName() ?? '',
  7143.                 'centerPostal' => $rdv->getIdCentre()->getPostale() ?? '',
  7144.                 'centerCity' => $rdv->getIdCentre()->getCity() ?? '',
  7145.                 'centerAddress' => $rdv->getIdCentre()->getAddress() ?? '',
  7146.                 'centerPhone' => $rdv->getIdCentre()->getPhone() ?? '',
  7147.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName() ?? '',
  7148.                 'audioMail' => $rdv->getIdAudio()->getMail() ?? '',
  7149.             );
  7150.             $subject "Vous avez manqué votre rendez-vous MyAudio avec " $rdv->getIdCentre()->getName();
  7151.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject214);
  7152.             // Send sms to client
  7153.             $sms "Vous avez manqué un RDV My Audio le " substr($smsDate010) . " à " substr($smsDate1115) . " dans votre centre auditif. Contactez le centre dès que possible : " $rdv->getIdCentre()->getPhone();
  7154.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  7155.             // Send email to MyAudio
  7156.             $date $rdv->getDate();
  7157.             $smsDate $date->format('d-m-Y H:i');
  7158.             $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  7159.             $params = array(
  7160.                 "date" => substr($smsDate010),
  7161.                 "lien" => "{$_ENV['BASE_client']}search",
  7162.                 "heure" => substr($smsDate1115),
  7163.                 'centerName' => $rdv->getIdCentre()->getName() ?? '',
  7164.                 'centerPostal' => $rdv->getIdCentre()->getPostale() ?? '',
  7165.                 'centerCity' => $rdv->getIdCentre()->getCity() ?? '',
  7166.                 'centerAddress' => $rdv->getIdCentre()->getAddress() ?? '',
  7167.                 'centerPhone' => $rdv->getIdCentre()->getPhone() ?? '',
  7168.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName() ?? '',
  7169.                 'audioMail' => $rdv->getIdAudio()->getMail() ?? '',
  7170.                 'clientName' => $client->getName() . ' ' $client->getLastName() ?? '',
  7171.                 'clientMail' => $client->getMail() ?? '',
  7172.                 'clientPhone' => $client->getPhone() ?? '',
  7173.             );
  7174.             $subject "Le patient " $client->getName() . ' ' $client->getLastName() . " a manqué son rendez-vous MyAudio avec le centre " $rdv->getIdCentre()->getName();
  7175.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$client->getName() . ' ' $client->getLastName(), $subject215);
  7176.         }
  7177.         return new Response(json_encode([
  7178.             "message" => "rdvEtat has been successfully updated",
  7179.             "status" => 200,
  7180.         ]));
  7181.     }
  7182.     /**
  7183.      * 
  7184.      * @Route("api/send-email/clientnotcompletebook", name="askToContact", methods={"POST"})
  7185.      */
  7186.     public function askToContact(Request $requestPublicFunction $publicFunction): Response
  7187.     {
  7188.         $data json_decode($request->getContent(), true);
  7189.         $staticToken "3f3a8b74f3e5b2d0c4917f5f9a7c07efb1a0f1e5e8c907ec9c4e9df129e3125e9";
  7190.         $token $data['token'] ?? null;
  7191.         if ($token !== $staticToken) {
  7192.             return new JsonResponse(
  7193.                 [
  7194.                     'status' => 'error',
  7195.                     'code' => 'unauthorized',
  7196.                     'message' => 'Unauthorized access.'
  7197.                 ],
  7198.                 JsonResponse::HTTP_UNAUTHORIZED
  7199.             );
  7200.         }
  7201.         $params = [
  7202.             'clientCivilite' => isset($data['civilite']) ? $data['civilite'] : 'Pas indiqué',
  7203.             'clientNom' => isset($data['firstname']) ? $data['firstname'] : null,
  7204.             'clientPrenom' => isset($data['lastname']) ? $data['lastname'] : null,
  7205.             'clientPostal' => isset($data['postalCode']) ? $data['postalCode'] : null,
  7206.             'clientPhone' => isset($data['phone']) ? $data['phone'] : null,
  7207.             'clientMail' => isset($data['email']) ? $data['email'] : null,
  7208.             'password' => isset($data['clientSecretCookie']) ? $data['clientSecretCookie'] : null,
  7209.             'rangeAge' => isset($data['trancheAge']) ? $data['trancheAge'] : null,
  7210.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  7211.             'situations' => isset($data['situations']) ? implode(', '$data['situations']) : null,
  7212.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  7213.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  7214.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  7215.         ];
  7216.         $templateEmailMyAudio 223;
  7217.         if (!empty($data['centre'])) {
  7218.             $centre $data['centre'];
  7219.             $audio $centre['audio'][0];
  7220.             $params['centerName'] = $centre['name'] ?? null;
  7221.             $params['centerPostal'] = $centre['postale'] ?? null;
  7222.             $params['centerCity'] = $centre['city'] ?? null;
  7223.             $params['centerAddress'] = $centre['address'] ?? null;
  7224.             $params['centerPhone'] = $centre['phone'] ?? null;
  7225.             $params['audioproName'] = $audio['civilite'] . ' ' $audio['lastname'] . ' ' $audio['name'] ?? null;
  7226.             $templateEmailMyAudio 222;
  7227.         }
  7228.         // Email to My Audio
  7229.         $email "lead.myaudio@gmail.com";
  7230.         $subject "Demande de contact -  Nouveau Lead À Contacter Hors Zone";
  7231.         $publicFunction->sendEmail($params$email$data['name'], $subject$templateEmailMyAudio);
  7232.         $publicFunction->sendEmail($params'contact@myaudio.fr'$data['name'], $subject$templateEmailMyAudio);
  7233.         $coordinates $this->getCoordinatesFromPostalCode($data['postalCode']);
  7234.         $latitude $coordinates['latitude'];
  7235.         $longitude $coordinates['longitude'];
  7236.         $params = [
  7237.             'email' => isset($data['email']) ? $data['email'] : null,
  7238.             'password' => isset($data['clientSecretCookie']) ? $data['clientSecretCookie'] : null,
  7239.             "lienRdv" => "{$_ENV['BASE_client']}search?latitude={$latitude}&longitude={$longitude}&ville={$data['postalCode']}",
  7240.         ];
  7241.         // Email to Client
  7242.         $subject "My Audio - Confirmation de demande de contact";
  7243.         $publicFunction->sendEmail($params$data['email'], $data['name'], $subject221);
  7244.         $sms "Votre demande validée ! Un spécialiste vous répondra rapidement et vous orientera vers un centre auditif proche. Contactez-nous au 01.89.71.61.09";
  7245.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$data['phone']);
  7246.         if (isset($data['clientRdvLp'])) {
  7247.             $rdvLead $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
  7248.             if ($rdvLead) {
  7249.                 $rdvLead->setSendAskToContact(1);
  7250.                 $rdvLead->setCountAskToContact(($rdvLead->getCountAskToContact() ?? 0) + 1);
  7251.                 $this->entityManager->flush();
  7252.                 $this->sendWhatsApp($data$rdvLead);
  7253.             }
  7254.         }
  7255.         return new Response(json_encode([
  7256.             "message" => "Email ask for contact send with success",
  7257.             "status" => 200,
  7258.         ]));
  7259.     }
  7260.     private function sendWhatsApp($data$lead): void
  7261.     {
  7262.         $adminUrl $this->adminUrlGenerator
  7263.             ->setDashboard(DashboardController::class)
  7264.             ->setController(LeadRdvCrudController::class)
  7265.             ->setAction('detail')
  7266.             ->setEntityId($lead->getId())
  7267.             ->generateUrl();
  7268.         $relativeUrl parse_url($adminUrlPHP_URL_PATH) . '?' parse_url($adminUrlPHP_URL_QUERY);
  7269.         // Supprimer le slash en trop s’il y en a un au début
  7270.         $relativeUrl ltrim($relativeUrl'/');
  7271.         // 🧑‍🤝‍🧑 Tableau des destinataires
  7272.         $destinataires = [
  7273.             '33611879183'// Numéro 1
  7274.             '33667597626'// Numéro 2
  7275.             '447884128220'// Numéro 3
  7276.         ];
  7277.         foreach ($destinataires as $numero) {
  7278.             $this->whatsapp->sendTemplateMessage(
  7279.                 $numero,  // Numéro de téléphone du destinataire
  7280.                 'lead_notif_myaudio',  // Nom du template WhatsApp
  7281.                 [
  7282.                     'body' => [
  7283.                         ['parameter_name' => 'nom_client''text' => $data['firstname'] . ' ' $data['lastname']],  // {{nom_client}}
  7284.                         ['parameter_name' => 'email_client''text' => $data['email'] ?? ' '],  // {{email_client}}
  7285.                         ['parameter_name' => 'telephone_client''text' => $data['phone'] ?? ' '],  // {{telephone_client}}
  7286.                         ['parameter_name' => 'date_lead''text' => $lead->getDate()->format('d/m/Y H:i')],  // {{date_lead}}
  7287.                         ['parameter_name' => 'code_postal''text' => $data['postalCode'] ?? ' '],  // {{code_postal}}
  7288.                         ['parameter_name' => 'nombre_centres''text' => $lead->getCentersCount() ?? '0'],  // {{nombre_centres}}
  7289.                     ],
  7290.                     'button' => $relativeUrl,  // <--- seulement le chemin dynamique
  7291.                 ]
  7292.             );
  7293.         }
  7294.     }
  7295.     /**
  7296.      * Get coordinates from the postal code using the database.
  7297.      */
  7298.     private function getCoordinatesFromPostalCode(string $postalCode): array
  7299.     {
  7300.         $region $this->entityManager
  7301.             ->getRepository(RegionDepartment::class)
  7302.             ->findOneBy(['codePostal' => $postalCode]);
  7303.         if ($region) {
  7304.             return [
  7305.                 'latitude' => $region->getLatitude(),
  7306.                 'longitude' => $region->getLongitude(),
  7307.             ];
  7308.         }
  7309.         return [
  7310.             'latitude' => null,
  7311.             'longitude' => null,
  7312.         ];
  7313.     }
  7314.     /**
  7315.      * Get the department code from the code postal
  7316.      */
  7317.     private function getDepartmentFromPostalCode(string $postalCode): ?array
  7318.     {
  7319.         $region $this->entityManager
  7320.             ->getRepository(RegionDepartment::class)
  7321.             ->findOneBy(['codePostal' => $postalCode]);
  7322.         if ($region) {
  7323.             return [
  7324.                 'departmentCode' => $region->getCodeDepartement(),
  7325.                 'departmentName' => $region->getNomDepartement(),
  7326.                 'regionCode' => $region->getCodeRegion(),
  7327.                 'regionName' => $region->getNomRegion(),
  7328.                 'city' => $region->getNomCommunePostal(),
  7329.             ];
  7330.         }
  7331.         return null;
  7332.     }
  7333.     /**
  7334.      * 
  7335.      * @Route("/giuili-admin/lead/{leadId}/centre/{centreId}", name="showLeadCentre", methods={"GET"})
  7336.      */
  7337.     public function showLeadCentre(int $leadIdCentre $centreId): Response
  7338.     {
  7339.         // dd("tets");
  7340.         $center $centres $this->getDoctrine()
  7341.             ->getRepository(AudioCentre::class)
  7342.             ->findOneBy(['id_centre' => $centreId->getId()]);
  7343.         $audio $center->getIdAudio();
  7344.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  7345.             ->findBy(['id_audio' => $audio'isDeleted' => 0]);
  7346.         return $this->render('easyadmin/leadRdv/centre_show.html.twig', [
  7347.             'audio' => $audio,
  7348.             'leadId' => $leadId,
  7349.             'centreId' => $centreId,
  7350.             'motifs' => $motifs,
  7351.         ]);
  7352.     }
  7353.     /**
  7354.      * @Route("/rdv-easyadmin", name="postRdvEasyAdmin", methods={"POST"})
  7355.      */
  7356.     public function postRdvEasyAdmin(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSmsAppointmentCallService $Callservice): Response
  7357.     {
  7358.         $data json_decode($request->getContent(), true);
  7359.         $entityManager $this->getDoctrine()->getManager();
  7360.         $audio $this->getDoctrine()
  7361.             ->getRepository(Audio::class)
  7362.             ->findOneBy(['id' => $data["audio_id"]]);
  7363.         $leadRdv =   $this->getDoctrine()->getRepository(LeadRdv::class)
  7364.             ->find($data["lead_id"]);
  7365.         $client $this->getDoctrine()->getRepository(Client::class)
  7366.             ->find($leadRdv->getClient());
  7367.         $responses = [
  7368.             'rangeAge' => $leadRdv->getRangeAge(),
  7369.             'situations' =>  implode(", "$leadRdv->getSituationsGene()),
  7370.             'equipeAppareil' => $leadRdv->getEquipeAppareil(),
  7371.             'durationEquipe' => $leadRdv->getDurationEquipeAppareil(),
  7372.             'bilanAuditif' => $leadRdv->getBilanAuditif(),
  7373.             'ordonance' => $leadRdv->getOrdonance(),
  7374.             'dateOrdonance' => $leadRdv->getDateOrdonance(),
  7375.             'canMove' => $leadRdv->getCanMove(),
  7376.         ];
  7377.         // makes the rdv
  7378.         $rdv = new Rdv();
  7379.         $rdv->setIdAudio($audio);
  7380.         if (isset($proche)) {
  7381.             $rdv->setIdProche($proche);
  7382.         }
  7383.         if (isset($data["client_id_temp"])) {
  7384.             $rdv->setIdClientTemp($client);
  7385.         } else {
  7386.             $rdv->setIdClient($client);
  7387.         }
  7388.         $rdv->setIsMyaudio(true);
  7389.         if (isset($data["isRdvLead"])) {
  7390.             $rdv->setIsRdvLp(true);
  7391.         }
  7392.         if (isset($data["isRdvRapide"])) {
  7393.             $rdv->setIsRdvRapide(true);
  7394.         }
  7395.         if (isset($data["duree"])) {
  7396.             $rdv->setDuration($data["duree"]);
  7397.         }
  7398.         if (isset($data["color"])) {
  7399.             $rdv->setColor($data["color"]);
  7400.         }
  7401.         /** @var Centre */
  7402.         if (isset($data["centre_id"])) {
  7403.             $centre $this->getDoctrine()
  7404.                 ->getRepository(Centre::class)
  7405.                 ->findOneBy(['id' => $data["centre_id"]]);
  7406.             if ($centre == null) {
  7407.                 return new Response(json_encode(([
  7408.                     'message' => 'Error, no centre found at this id',
  7409.                     'path' => 'src/Controller/RdvController.php',
  7410.                     "status" => 400,
  7411.                 ])), 400);
  7412.             }
  7413.             /** @var AudioCentre */
  7414.             $liaison $this->getDoctrine()
  7415.                 ->getRepository(AudioCentre::class)
  7416.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  7417.             if ($liaison == null) {
  7418.                 return new Response(json_encode(([
  7419.                     'message' => 'Error, audio isnt part of the centre',
  7420.                     'path' => 'src/Controller/RdvController.php',
  7421.                     "status" => 400,
  7422.                 ])), 400);
  7423.             }
  7424.             $rdv->setIdCentre($centre);
  7425.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  7426.             // tries to set the lieu if it's an audio indie
  7427.             $lieu $this->getDoctrine()
  7428.                 ->getRepository(Lieu::class)
  7429.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  7430.             if ($lieu == null) {
  7431.                 return new Response(json_encode(([
  7432.                     'message' => 'Error, no lieu found at this id',
  7433.                     'path' => 'src/Controller/RdvController.php',
  7434.                     "status" => 400,
  7435.                 ])), 400);
  7436.             }
  7437.             $rdv->setIdLieu($lieu);
  7438.         } else {
  7439.             return new Response(json_encode(([
  7440.                 'message' => 'Error, no lieu/centre id',
  7441.                 'path' => 'src/Controller/RdvController.php',
  7442.                 "status" => 400,
  7443.             ])), 400);
  7444.         }
  7445.         /** @var Motif */
  7446.         $motif $this->getDoctrine()
  7447.             ->getRepository(Motif::class)
  7448.             ->find($data["motif_id"]);
  7449.         if ($motif == null) {
  7450.             return new Response(json_encode(([
  7451.                 'message' => 'Error, no motif found at this id',
  7452.                 'path' => 'src/Controller/RdvController.php',
  7453.                 "status" => 400,
  7454.             ])), 400);
  7455.         }
  7456.         /** @var AudioMotif */
  7457.         $audioMotif $this->getDoctrine()
  7458.             ->getRepository(AudioMotif::class)
  7459.             ->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
  7460.         if ($audioMotif == null) {
  7461.             return new Response(json_encode(([
  7462.                 'message' => 'Error, no motif of this id found at this audio',
  7463.                 'path' => 'src/Controller/RdvController.php',
  7464.                 "status" => 400,
  7465.             ])), 400);
  7466.         }
  7467.         // remove the taken schedule by rdv to make sure there is no overlap
  7468.         $data["date"] = str_replace("h"":"$data["date"]);
  7469.         $date \DateTime::createFromFormat("Y-m-d\TH:i"$data["date"]);
  7470.         if (isset($data["note"])) {
  7471.             $rdv->setNote($data["note"]);
  7472.         }
  7473.         $date \DateTime::createFromFormat("Y-m-d\TH:i"$data["date"]);
  7474.         $rdv->setDate($date);
  7475.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  7476.         /** @var EtatRdv */
  7477.         $etat $this->getDoctrine()
  7478.             ->getRepository(EtatRdv::class)
  7479.             ->findOneBy(['id' => $data["etat_id"]]);
  7480.         if ($etat == null) {
  7481.             return new Response(json_encode(([
  7482.                 'message' => 'Error, no etat found at this id',
  7483.                 'path' => 'src/Controller/RdvController.php',
  7484.                 "status" => 400,
  7485.             ])), 400);
  7486.         }
  7487.         $rdv->setIdEtat($etat);
  7488.         $rdv->setIdMotif($motif);
  7489.         $rdv->setIsAbsence(0);
  7490.         $rdv->setCacher(0);
  7491.         $entityManager $this->getDoctrine()->getManager();
  7492.         $entityManager->persist($rdv);
  7493.         $leadRdv->setRdv($rdv);
  7494.         $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
  7495.         $leadRdv->setLeadStatus($leadStatus);
  7496.         $entityManager->flush();
  7497.         /// SMSEMAIL A décommenter pour autoriser l'envoi de sms / email à la création de rdv par l'audio / le client SMSEMAIL ///
  7498.         $date $rdv->getDate();
  7499.         $smsDate $date->format('d-m-Y H:i');
  7500.         $locale 'fr_FR';
  7501.         $formatter = new IntlDateFormatter(
  7502.             $locale,
  7503.             IntlDateFormatter::FULL,
  7504.             IntlDateFormatter::SHORT,
  7505.             null,
  7506.             IntlDateFormatter::GREGORIAN,
  7507.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  7508.         );
  7509.         $smsDateLongFormat $formatter->format($date);
  7510.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  7511.         $client->setIdCentre($rdv->getIdCentre());
  7512.         $client->setIdAudio($rdv->getIdAudio());
  7513.         $entityManager->persist($client);
  7514.         $entityManager->flush();
  7515.         // client notif mail Sms
  7516.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  7517.         $frenchDate ucfirst($frenchDate);
  7518.         $params = array(
  7519.             "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  7520.             "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  7521.             "date" => $smsDateLongFormat,
  7522.             "RdvDate" => $smsDateLongFormat,
  7523.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  7524.             "centerName" => $rdv->getIdCentre()->getName(),
  7525.             "prenom" => $client->getName(),
  7526.             "centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  7527.             "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  7528.             'motif' => $rdv->getIdMotif()->getTitre(),
  7529.             "centerCity" => $rdv->getIdCentre()->getCity(),
  7530.             "audioName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  7531.             'titre' => "Votre rendez-vous est validé le " substr($smsDate010) . " à "  substr($smsDate1115),
  7532.             "position" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  7533.             "address" => $rdv->getIdCentre()->getAddress(),
  7534.             "postal" => $rdv->getIdCentre()->getPostale(),
  7535.             "city" => $rdv->getIdCentre()->getCity(),
  7536.             "clientEmail" => $client->getMail(),
  7537.             "clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
  7538.             "clientAddress" => $client->getAddress(),
  7539.             "clientPostal" => $client->getPostal(),
  7540.             "clientCity" => $client->getCity(),
  7541.             "audioName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  7542.             "frenchDate" => $frenchDate,
  7543.             "heure" => substr($smsDate1115),
  7544.             "centerName" => $rdv->getIdCentre()->getName(),
  7545.             "audioMail" => $rdv->getIdAudio()->getMail(),
  7546.             "modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
  7547.         );
  7548.         $paramsPatient $params;
  7549.         $isNew false;
  7550.         if (isset($data["isLead"]) && isset($data["passwordGenerated"]) != null) {
  7551.             $subject "✅Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  7552.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject189);
  7553.             $isNew true;
  7554.         } else {
  7555.             $subject "Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  7556.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject181);
  7557.         }
  7558.         $sms "Votre RDV est validé le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  7559.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  7560.         // audio Notif mail SMS
  7561.         $birthday $rdv->getIdClient()->getBirthdate();
  7562.         $params = array(
  7563.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  7564.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  7565.             "date" => substr($smsDate010),
  7566.             "heure" => substr($smsDate1115),
  7567.             "mail" => $client->getMail(),
  7568.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  7569.             'telClient' => $client->getPhone(),
  7570.             'phone' => $client->getPhone(),
  7571.             'clientCivilite' => $client->getCivilite(),
  7572.             'clientNom' => $client->getLastname(),
  7573.             'clientPrenom' => $client->getName(),
  7574.             'clientPostal' => $client->getPostal(),
  7575.             'clientMail' => $client->getMail(),
  7576.             'clientPhone' => $client->getPhone(),
  7577.             'motif' => $rdv->getIdMotif()->getTitre(),
  7578.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  7579.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  7580.             'centerName' => $rdv->getIdCentre()->getName(),
  7581.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  7582.             'centerCity' => $rdv->getIdCentre()->getCity(),
  7583.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  7584.             'idPatient' => $client->getId(),
  7585.             'proUrl' => "{$_ENV['BASE_logiciel']}",
  7586.             'frenchDate' => $frenchDate,
  7587.             'responses' => $responses,
  7588.         );
  7589.         $templateEmail 182;
  7590.         if (!empty($data['canMove'])) {
  7591.             $templateEmail 197;
  7592.         }
  7593.         $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  7594.         $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  7595.         if ($rdv->getIdAudio()->getConfirmRdvMail()) {
  7596.             $subject "✅ Nouveau Rendez-vous My Audio le " $frenchDate " à " substr($smsDate1115);
  7597.             $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject$templateEmail);
  7598.         }
  7599.         if ($rdv->getIdAudio()->getConfirmRdvSms()) {
  7600.             $sms "Vous avez un nouveau RDV le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'aléas contactez votre patient " $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  7601.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  7602.         }
  7603.         $age null;
  7604.         if ($client->getBirthdate()) {
  7605.             $age $client->getBirthdate()->diff(new \DateTime())->y;
  7606.         }
  7607.         // Génère le PDF à partir d’un template
  7608.         $pdfContent $this->generatePdf(
  7609.             'pdf/rdv_recap.html.twig',
  7610.             [
  7611.                 'id' => $client->getId() ?? '',
  7612.                 'nom' => $client->getName() ?? '',
  7613.                 'prenom' => $client->getLastname() ?? '',
  7614.                 'birthday' =>  $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  7615.                 'age' => $age,
  7616.                 'adresse' => $client->getAddress() ?? '',
  7617.                 'postal' => $client->getPostal() ?? '',
  7618.                 'city' => $client->getCity() ?? '',
  7619.                 'phone' => $client->getPhone() ?? '',
  7620.                 'mail' => $client->getMail() ?? '',
  7621.                 'centerName' => $rdv->getIdCentre()->getName() ?? '',
  7622.                 "date" => substr($smsDate010) ?? '',
  7623.                 "heure" => substr($smsDate1115) ?? '',
  7624.                 'duration' => $rdv->getDuration(),
  7625.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  7626.                 'motif' => $rdv->getIdMotif() ? $rdv->getIdMotif()->getTitre() : '',
  7627.                 'situations' => $this->formatImploded($leadRdv->getSituationsGene()),
  7628.                 'IntensiteGen' => $leadRdv->getIntensiteGene() ?? '',
  7629.                 'devicePref' => $this->formatImploded($leadRdv->getPreferenceDevice()),
  7630.                 'deviceModelPref' =>  implode(", "$leadRdv->getDeviceModelPreference()),
  7631.                 'criterePrincipal' => $this->formatImploded($leadRdv->getCriterePrincipal()),
  7632.                 'accoupheneCote' =>  $leadRdv->getAcoupheneCote() ?? '',
  7633.                 'originePerte' => $this->formatImploded($leadRdv->getOriginePerte()),
  7634.                 'diabete' =>  $leadRdv->getDiabete() ?? '',
  7635.                 'hypertension' =>  $leadRdv->getHypertension() ?? '',
  7636.                 'mutuelle' =>  $leadRdv->getMutuelle() ?? '',
  7637.                 'nameMutuelle' =>  $leadRdv->getNameMutuelle() ?? '',
  7638.                 'priseEnCharge' => $leadRdv->getPriseEnCharge() ?? '',
  7639.                 'budget' => $leadRdv->getBudget() ?? '',
  7640.                 'equipeAppareil' => $leadRdv->getEquipeAppareil() ?? '',
  7641.                 'durationEquipe' => $leadRdv->getDurationEquipeAppareil() ?? '',
  7642.                 'bilanAuditif' => $leadRdv->getBilanAuditif() ?? '',
  7643.                 'ordonance' => $leadRdv->getOrdonance() ?? '',
  7644.                 'dateOrdonance' => $leadRdv->getDateOrdonance() ?? '',
  7645.                 'canMove' => $leadRdv->getCanMove() ?? '',
  7646.                 'comment' => $leadRdv->getComment() ?? '',
  7647.             ],
  7648.             $this->getParameter('kernel.project_dir') . '/public/assets/pdf/recap-rdv-myaudio.pdf'
  7649.         );
  7650.         $this->sendEmailWithPdfAttachmentThenDelete(
  7651.             $params,
  7652.             $mailAudio,
  7653.             $client->getName(),
  7654.             $subject,
  7655.             $templateEmail// ID du template Sendinblue
  7656.             $pdfContent
  7657.         );
  7658.         // send notif to admin
  7659.         $paramsSourceLead = [
  7660.             'trafficSource' => "EasyAdmin",
  7661.         ];
  7662.         $paramsAdmin = array(
  7663.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  7664.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  7665.             "RdvDate" => substr($smsDate010),
  7666.             "heure" => substr($smsDate1115),
  7667.             "clientMail" => $client->getMail(),
  7668.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  7669.             'telClient' => $client->getPhone(),
  7670.             'clientNom' => $client->getLastname(),
  7671.             'clientPrenom' => $client->getName(),
  7672.             'clientCivilite' => $client->getCivilite(),
  7673.             'clientPostal' => $client->getPostal(),
  7674.             'clientPhone' => $client->getPhone(),
  7675.             'motif' => $rdv->getIdMotif()->getTitre(),
  7676.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  7677.             'centerName' => $rdv->getIdCentre()->getName(),
  7678.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  7679.             'centerCity' => $rdv->getIdCentre()->getCity(),
  7680.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  7681.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  7682.             'date' => substr($smsDate010),
  7683.             'urlApi' => "{$_ENV['BASE_API']}",
  7684.             'clientId' => $client->getId(),
  7685.             'centerId' => $rdv->getIdCentre()->getId(),
  7686.             'frenchDate' => $frenchDate,
  7687.             'responses' => $responses,
  7688.             'paramsSourceLead' => $paramsSourceLead
  7689.         );
  7690.         $subject "Nouveau RDV MA | RR - " $rdv->getIdCentre()->getName();
  7691.         $templateEmail 183;
  7692.         if (!empty($data['canMove'])) {
  7693.             $templateEmail 190;
  7694.         }
  7695.         $publicFunction->sendEmail($paramsAdmin"contact@myaudio.fr""my audio"$subject$templateEmail);
  7696.         $publicFunction->sendEmail($paramsAdmin"lead.myaudio@gmail.com""my audio"$subject$templateEmail);
  7697.         $specificSubscription $this->getDoctrine()
  7698.              ->getRepository(SpecificSubscription::class)
  7699.              ->findOneBy(['audio' => $audio]);
  7700.       if ($specificSubscription && $specificSubscription->getContractCategory()) {
  7701.         $contractCategory $specificSubscription->getContractCategory();
  7702.       if ($contractCategory->getName() === "OPTICAL CENTER SUCCURSALE") {
  7703.         $publicFunction->sendEmail($paramsAdmin"christel.montagne@optical-center.com""my audio"$subject246);
  7704.          }
  7705.        }
  7706.         try {
  7707.             $Callservice->handleCallCenterAfterRdv(
  7708.                 $rdv
  7709.             );
  7710.             $rdv->setIsNotificationRdvCallSent(1);
  7711.             $this->entityManager->flush();
  7712.         } catch (\Exception $e) {
  7713.             $this->logger->error("Erreur lors de l'appel de notification pour le RDV #{$rdv->getId()}: " $e->getMessage());
  7714.         }
  7715.         // google calendar post
  7716.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  7717.             ->findBy(array('audio' => $audio->getId()));
  7718.         $data['rdv'] = $rdv->getId();
  7719.         foreach ($synchronisations as $synchronisation) {
  7720.             if (!$synchronisation->getIsDeleted()) {
  7721.                 $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  7722.                 $googleCalendar->createEvent($synchronisation$data);
  7723.             }
  7724.         }
  7725.         return new Response(json_encode(([
  7726.             "id" => $rdv->getId(),
  7727.             "motif_id" => $rdv->getIdMotif()->getId(),
  7728.             "audio_id" => $rdv->getIdAudio()->getId(),
  7729.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  7730.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  7731.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  7732.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  7733.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  7734.             "testclient" => $rdv->getTestClient() ? [
  7735.                 "result" => $rdv->getTestClient()->getResultTonal(),
  7736.                 "date" => $rdv->getTestClient()->getDate(),
  7737.                 "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  7738.             ] : null,
  7739.             "duration" => $audioMotif->getDuration(),
  7740.             "consigne" => $audioMotif->getConsigne(),
  7741.             "etat_id" => $rdv->getIdEtat()->getId(),
  7742.             "date" => $rdv->getDate(),
  7743.             "comment" => $rdv->getComment(),
  7744.             "centerName" => $rdv->getIdCentre()->getName(),
  7745.             "review" => $rdv->getReview(),
  7746.             "note" => $rdv->getNote(),
  7747.             "status" => 200,
  7748.             "paramsPatient" => $paramsPatient,
  7749.             "isNew" => $isNew,
  7750.         ])));
  7751.     }
  7752.     private function generatePdf(string $template, array $data = [], string $outputPath): string
  7753.     {
  7754.         // Render le contenu HTML avec Twig
  7755.         $html $this->twig->render($template$data);
  7756.         // Configurer Dompdf
  7757.         $options = new Options();
  7758.         $options->set('defaultFont''Arial');
  7759.         $dompdf = new Dompdf($options);
  7760.         $dompdf->loadHtml($html);
  7761.         $dompdf->setPaper('A4''portrait');
  7762.         $dompdf->render();
  7763.         // Sauvegarder le PDF
  7764.         file_put_contents($outputPath$dompdf->output());
  7765.         return $outputPath// Renvoie le chemin du fichier PDF généré
  7766.     }
  7767.     private function sendEmailWithPdfAttachmentThenDelete(
  7768.         array $params,
  7769.         string $mail,
  7770.         string $name,
  7771.         string $subject,
  7772.         int $templateId,
  7773.         string $pdfFilePath
  7774.     ): void {
  7775.         // Lire et encoder le contenu du PDF
  7776.         $attachment = [
  7777.             "name" => basename($pdfFilePath),
  7778.             "content" => base64_encode(file_get_contents($pdfFilePath)),
  7779.         ];
  7780.         // Construire les données pour l’API Sendinblue
  7781.         $data = [
  7782.             "sender" => [
  7783.                 "email" => 'noreply@myaudio.fr',
  7784.                 "name" => 'My Audio',
  7785.             ],
  7786.             "to" => [
  7787.                 [
  7788.                     "email" => $mail,
  7789.                     "name" => $name,
  7790.                 ],
  7791.             ],
  7792.             "subject" => $subject,
  7793.             "templateId" => $templateId,
  7794.             "params" => $params,
  7795.             "attachment" => [$attachment],
  7796.         ];
  7797.         // Envoi via cURL
  7798.         $ch curl_init();
  7799.         curl_setopt($chCURLOPT_URL'https://api.sendinblue.com/v3/smtp/email');
  7800.         curl_setopt($chCURLOPT_RETURNTRANSFER1);
  7801.         curl_setopt($chCURLOPT_POST1);
  7802.         curl_setopt($chCURLOPT_POSTFIELDSjson_encode($data));
  7803.         $headers = [
  7804.             'Accept: application/json',
  7805.             'Api-Key: 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',
  7806.             'Content-Type: application/json',
  7807.         ];
  7808.         curl_setopt($chCURLOPT_HTTPHEADER$headers);
  7809.         $result curl_exec($ch);
  7810.         if (curl_errno($ch)) {
  7811.             echo 'Erreur email : ' curl_error($ch);
  7812.         }
  7813.         curl_close($ch);
  7814.         // Supprimer le PDF après envoi
  7815.         if (file_exists($pdfFilePath)) {
  7816.             unlink($pdfFilePath);
  7817.         }
  7818.     }
  7819.     private function formatImploded(array $data): string
  7820.     {
  7821.         return implode(', 'array_map(function ($item) {
  7822.             return str_replace('_'' '$item);
  7823.         }, $data));
  7824.     }
  7825.     /**
  7826.      * 
  7827.      * @Route("/admin/rdv/export-pdf-form", name="admin_rdv_export_pdf_form", methods={"GET", "POST"})
  7828.      */
  7829.     public function exportPdfForm(Request $request): Response
  7830.     {
  7831.         $form $this->createFormBuilder()
  7832.             ->add('startDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  7833.                 'label' => 'Date de début',
  7834.                 'widget' => 'single_text',
  7835.                 'html5' => true,
  7836.                 'required' => true,
  7837.             ])
  7838.             ->add('endDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  7839.                 'label' => 'Date de fin',
  7840.                 'widget' => 'single_text',
  7841.                 'html5' => true,
  7842.                 'required' => true,
  7843.             ])
  7844.             ->add('format'\Symfony\Component\Form\Extension\Core\Type\ChoiceType::class, [
  7845.                 'label' => 'Format d\'export',
  7846.                 'choices' => [
  7847.                     'PDF' => 'pdf',
  7848.                     'Excel' => 'excel',
  7849.                 ],
  7850.                 'expanded' => false,
  7851.                 'multiple' => false,
  7852.                 'required' => true,
  7853.             ])
  7854.             ->getForm();
  7855.         //dd($request);
  7856.         $form->handleRequest($request);
  7857.         if ($form->isSubmitted() && $form->isValid()) {
  7858.             $data $form->getData();
  7859.             $start $data['startDate']->format('Y-m-d');
  7860.             $end $data['endDate']->format('Y-m-d');
  7861.             if ($data['format'] === 'pdf') {
  7862.                 return $this->redirectToRoute('admin_rdv_export_pdf', [
  7863.                     'startDate' => $start,
  7864.                     'endDate' => $end,
  7865.                 ]);
  7866.             } else {
  7867.                 return $this->redirectToRoute('admin_rdv_export_excel', [
  7868.                     'startDate' => $start,
  7869.                     'endDate' => $end,
  7870.                 ]);
  7871.             }
  7872.         }
  7873.         return $this->render('easyadmin/rdv/export_pdf_form.html.twig', [
  7874.             'form' => $form->createView(),
  7875.         ]);
  7876.     }
  7877.     /**
  7878.      * 
  7879.      * @Route("/optical/rdv/export-pdf-form", name="optical_rdv_export_pdf_form", methods={"GET", "POST"})
  7880.      */
  7881.     public function exportOpticalPdfForm(Request $request): Response
  7882.     {
  7883.         $form $this->createFormBuilder()
  7884.             ->add('startDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  7885.                 'label' => 'Date de début',
  7886.                 'widget' => 'single_text',
  7887.                 'html5' => true,
  7888.                 'required' => true,
  7889.             ])
  7890.             ->add('endDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  7891.                 'label' => 'Date de fin',
  7892.                 'widget' => 'single_text',
  7893.                 'html5' => true,
  7894.                 'required' => true,
  7895.             ])
  7896.             ->add('format'\Symfony\Component\Form\Extension\Core\Type\ChoiceType::class, [
  7897.                 'label' => 'Format d\'export',
  7898.                 'choices' => [
  7899.                     'PDF' => 'pdf',
  7900.                     'Excel' => 'excel',
  7901.                 ],
  7902.                 'expanded' => false,
  7903.                 'multiple' => false,
  7904.                 'required' => true,
  7905.             ])
  7906.             ->getForm();
  7907.         //dd($request);
  7908.         $form->handleRequest($request);
  7909.         if ($form->isSubmitted() && $form->isValid()) {
  7910.             $data $form->getData();
  7911.             $start $data['startDate']->format('Y-m-d');
  7912.             $end $data['endDate']->format('Y-m-d');
  7913.             if ($data['format'] === 'pdf') {
  7914.                 return $this->redirectToRoute('optical_rdv_export_pdf', [
  7915.                     'startDate' => $start,
  7916.                     'endDate' => $end,
  7917.                 ]);
  7918.             } else {
  7919.                 return $this->redirectToRoute('optical_rdv_export_excel', [
  7920.                     'startDate' => $start,
  7921.                     'endDate' => $end,
  7922.                 ]);
  7923.             }
  7924.         }
  7925.         return $this->render('easyadmin/rdv/export_pdf_form.html.twig', [
  7926.             'form' => $form->createView(),
  7927.         ]);
  7928.     }
  7929.     /**
  7930.      * @Route("/admin/lead-rdv/update-status", name="admin_lead_rdv_update_status", methods={"POST"})
  7931.      */
  7932.     public function updateStatus(Request $request): JsonResponse
  7933.     {
  7934.         // Récupérer les données envoyées en AJAX
  7935.         $data json_decode($request->getContent(), true);
  7936.         $leadId $data['leadId'] ?? null;
  7937.         $statusId $data['statusId'] ?? null;
  7938.         if (!$leadId || !$statusId) {
  7939.             return new JsonResponse(['success' => false'message' => 'Données manquantes'], 400);
  7940.         }
  7941.         // Récupérer le lead et le statut
  7942.         $lead $this->entityManager->getRepository(LeadRdv::class)->find($leadId);
  7943.         $status $this->entityManager->getRepository(LeadStatus::class)->find($statusId);
  7944.         if (!$lead || !$status) {
  7945.             return new JsonResponse(['success' => false'message' => 'Lead ou statut introuvable'], 404);
  7946.         }
  7947.         // Mettre à jour le statut du lead
  7948.         $lead->setLeadStatus($status);
  7949.         $this->entityManager->flush();
  7950.         return new JsonResponse(['success' => true]);
  7951.     }
  7952.     /**
  7953.      * @Route("/admin/rdv/update-client-status", name="admin_rdv_update_client_status", methods={"POST"})
  7954.      */
  7955.     public function updateClientStatus(Request $request): JsonResponse
  7956.     {
  7957.         $data json_decode($request->getContent(), true);
  7958.         $rdvId $data['rdvId'] ?? null;
  7959.         $statusId $data['statusId'] ?? null;
  7960.         if (!$rdvId || !$statusId) {
  7961.             return new JsonResponse(['success' => false'message' => 'Données manquantes'], 400);
  7962.         }
  7963.         // Récupérer le RDV
  7964.         $rdv $this->entityManager->getRepository(Rdv::class)->find($rdvId);
  7965.         if (!$rdv) {
  7966.             return new JsonResponse(['success' => false'message' => 'RDV non trouvé'], 404);
  7967.         }
  7968.         // Récupérer le statut
  7969.         $clientStatus $this->entityManager->getRepository(ClientStatus::class)->find($statusId);
  7970.         if (!$clientStatus) {
  7971.             return new JsonResponse(['success' => false'message' => 'Statut non trouvé'], 404);
  7972.         }
  7973.         // Mettre à jour le client
  7974.         $client $rdv->getIdClient();
  7975.         if ($client) {
  7976.             $client->setClientStatus($clientStatus);
  7977.             $this->entityManager->flush();
  7978.             // Si le statut est "Facturé", lancer la facturation
  7979.             if ((int)$statusId === 2) {
  7980.                 // Réutiliser la méthode de facturation existante
  7981.                 $crudController $this->container->get(RdvMyAudioCrudController::class);
  7982.                 $crudController->billing($rdv);
  7983.             }
  7984.             return new JsonResponse(['success' => true]);
  7985.         }
  7986.         return new JsonResponse(['success' => false'message' => 'Client non trouvé'], 404);
  7987.     }
  7988.     /**
  7989.      * @Route("/admin/rdv/update-rdv-status", name="admin_rdv_update_status", methods={"POST"})
  7990.      */
  7991.     public function updateRdvStatus(Request $requestEntityManagerInterface $entityManager): JsonResponse
  7992.     {
  7993.         $data json_decode($request->getContent(), true);
  7994.         $rdvId $data['rdvId'] ?? null;
  7995.         $statusId $data['statusId'] ?? null;
  7996.         if (!$rdvId || !$statusId) {
  7997.             return new JsonResponse(['success' => false'message' => 'Données manquantes'], 400);
  7998.         }
  7999.         // Récupérer le RDV
  8000.         $rdv $entityManager->getRepository(Rdv::class)->find($rdvId);
  8001.         if (!$rdv) {
  8002.             return new JsonResponse(['success' => false'message' => 'RDV non trouvé'], 404);
  8003.         }
  8004.         // Récupérer le statut
  8005.         $etatRdv $entityManager->getRepository(EtatRdv::class)->find($statusId);
  8006.         if (!$etatRdv) {
  8007.             return new JsonResponse(['success' => false'message' => 'Statut non trouvé'], 404);
  8008.         }
  8009.         // Mettre à jour le statut du RDV
  8010.         $rdv->setIdEtat($etatRdv);
  8011.         $entityManager->flush();
  8012.         return new JsonResponse(['success' => true]);
  8013.     }
  8014.     /**
  8015.      * @Route("/admin/rdv/export-pdf/{startDate}/{endDate}", name="admin_rdv_export_pdf", methods={"GET"})
  8016.      */
  8017.     public function exportPdfFromDate(string $startDatestring $endDateKernelInterface $kernel): Response
  8018.     {
  8019.         $start = new \DateTimeImmutable($startDate);
  8020.         $end = new \DateTimeImmutable($endDate);
  8021.         $today = new \DateTimeImmutable();
  8022.         $rdvs $this->rdvRepository->findBySinceDateAndMyAudio($start$end);
  8023.         $html "
  8024.     <html>
  8025.     <head>
  8026.         <style>
  8027.             body { font-family: Arial, sans-serif; font-size: 13px; }
  8028.             table { width: 100%; border-collapse: collapse; font-size: 11px; }
  8029.             th, td { border: 1px solid #000; padding: 5px; text-align: left; }
  8030.             th { font-weight: bold; }
  8031.             h1 { font-size: 14px; }
  8032.         </style>
  8033.     </head>
  8034.     <body>
  8035.         <h1>Rendez-vous My Audio du " $start->format('d/m/Y') . " au " $end->format('d/m/Y') . "</h1>
  8036.         <table cellspacing='0' cellpadding='5'>
  8037.             <thead>
  8038.                 <tr>
  8039.                     <th>ID du RDV</th>
  8040.                     <th>Date du RDV</th>
  8041.                     <th>Jours écoulés</th>
  8042.                     <th>Statut RDV</th>
  8043.                     <th>Nom patient</th>
  8044.                     <th>Téléphone patient</th>
  8045.                     <th>Statut patient</th>
  8046.                     <th>Centre</th>
  8047.                     <th>Téléphone Centre</th>
  8048.                     <th>Adresse</th>
  8049.                     <th>Nom Audio</th>
  8050.                 </tr>
  8051.             </thead>
  8052.             <tbody>";
  8053.         foreach ($rdvs as $rdv) {
  8054.             $dateRdv $rdv->getDate();
  8055.             $joursEcoules $dateRdv->diff($today)->days;
  8056.             $client $rdv->getIdClient();
  8057.             $centre $rdv->getIdCentre();
  8058.             $etat $rdv->getIdEtat();
  8059.             $audio $rdv->getIdAudio();
  8060.             $html .= "<tr>
  8061.             <td>" $rdv->getId() . "</td>
  8062.             <td>" $dateRdv->format('d/m/Y H:i') . "</td>
  8063.             <td>" $joursEcoules " jours</td>
  8064.             <td>" . ($etat htmlspecialchars($etat->getLibelle()) : 'Non défini') . "</td>
  8065.             <td>" . ($client htmlspecialchars($client->getName() . ' ' $client->getLastname()) : '') . "</td>
  8066.             <td>" . ($client htmlspecialchars($client->getPhone()) : '') . "</td>
  8067.             <td>" . ($client && $client->getClientStatus() ? htmlspecialchars($client->getClientStatus()->getLibelle()) : 'Non défini') . "</td>
  8068.             <td>" . ($centre htmlspecialchars($centre->getName()) : '') . "</td>
  8069.             <td>" . ($centre htmlspecialchars($centre->getPhone()) : '') . "</td>
  8070.             <td>" . ($centre htmlspecialchars($centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity()) : '') . "</td>
  8071.             <td>" . ($audio htmlspecialchars($audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastname()) : '') . "</td>
  8072.         </tr>";
  8073.         }
  8074.         $html .= "</tbody></table></body></html>";
  8075.         // Configuration et rendu du PDF
  8076.         $options = new Options();
  8077.         $options->set('defaultFont''Arial');
  8078.         $dompdf = new Dompdf($options);
  8079.         $dompdf->loadHtml($html);
  8080.         $dompdf->setPaper('A4''landscape');
  8081.         $dompdf->render();
  8082.         // Création du dossier s'il n'existe pas
  8083.         $projectDir $kernel->getProjectDir();
  8084.         $outputDir $projectDir '/public/assets/pdf/rdv';
  8085.         $filesystem = new Filesystem();
  8086.         if (!$filesystem->exists($outputDir)) {
  8087.             $filesystem->mkdir($outputDir0775);
  8088.         }
  8089.         $filenameDate $start->format('Y-m-d') . '_to_' $end->format('Y-m-d');
  8090.         $outputPath "$outputDir/rdvs-$filenameDate.pdf";
  8091.         file_put_contents($outputPath$dompdf->output());
  8092.         return new Response($dompdf->output(), 200, [
  8093.             'Content-Type' => 'application/pdf',
  8094.             'Content-Disposition' => 'attachment; filename="rdvs-' $filenameDate '.pdf"',
  8095.         ]);
  8096.     }
  8097.     /**
  8098.      * @Route("/optical/rdv/export-pdf/{startDate}/{endDate}", name="optical_rdv_export_pdf", methods={"GET"})
  8099.      */
  8100.     public function exportOpticalPdfFromDate(string $startDatestring $endDateKernelInterface $kernel): Response
  8101.     {
  8102.         $start = new \DateTimeImmutable($startDate);
  8103.         $end = new \DateTimeImmutable($endDate);
  8104.         $today = new \DateTimeImmutable();
  8105.         $rdvs $this->rdvRepository->findOpticalBySinceDateAndMyAudio($start$end);
  8106.         $html "
  8107.     <html>
  8108.     <head>
  8109.         <style>
  8110.             body { font-family: Arial, sans-serif; font-size: 13px; }
  8111.             table { width: 100%; border-collapse: collapse; font-size: 11px; }
  8112.             th, td { border: 1px solid #000; padding: 5px; text-align: left; }
  8113.             th { font-weight: bold; }
  8114.             h1 { font-size: 14px; }
  8115.         </style>
  8116.     </head>
  8117.     <body>
  8118.         <h1>Rendez-vous My Audio du " $start->format('d/m/Y') . " au " $end->format('d/m/Y') . "</h1>
  8119.         <table cellspacing='0' cellpadding='5'>
  8120.             <thead>
  8121.                 <tr>
  8122.                     <th>ID du RDV</th>
  8123.                     <th>Date du RDV</th>
  8124.                     <th>Jours écoulés</th>
  8125.                     <th>Statut RDV</th>
  8126.                     <th>Nom patient</th>
  8127.                     <th>Téléphone patient</th>
  8128.                     <th>Statut patient</th>
  8129.                     <th>Centre</th>
  8130.                     <th>Téléphone Centre</th>
  8131.                     <th>Adresse</th>
  8132.                     <th>Nom Audio</th>
  8133.                 </tr>
  8134.             </thead>
  8135.             <tbody>";
  8136.         foreach ($rdvs as $rdv) {
  8137.             $dateRdv $rdv->getDate();
  8138.             $joursEcoules $dateRdv->diff($today)->days;
  8139.             $client $rdv->getIdClient();
  8140.             $centre $rdv->getIdCentre();
  8141.             $etat $rdv->getIdEtat();
  8142.             $audio $rdv->getIdAudio();
  8143.             $html .= "<tr>
  8144.             <td>" $rdv->getId() . "</td>
  8145.             <td>" $dateRdv->format('d/m/Y H:i') . "</td>
  8146.             <td>" $joursEcoules " jours</td>
  8147.             <td>" . ($etat htmlspecialchars($etat->getLibelle()) : 'Non défini') . "</td>
  8148.             <td>" . ($client htmlspecialchars($client->getName() . ' ' $client->getLastname()) : '') . "</td>
  8149.             <td>" . ($client htmlspecialchars($client->getPhone()) : '') . "</td>
  8150.             <td>" . ($client && $client->getClientStatus() ? htmlspecialchars($client->getClientStatus()->getLibelle()) : 'Non défini') . "</td>
  8151.             <td>" . ($centre htmlspecialchars($centre->getName()) : '') . "</td>
  8152.             <td>" . ($centre htmlspecialchars($centre->getPhone()) : '') . "</td>
  8153.             <td>" . ($centre htmlspecialchars($centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity()) : '') . "</td>
  8154.             <td>" . ($audio htmlspecialchars($audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastname()) : '') . "</td>
  8155.         </tr>";
  8156.         }
  8157.         $html .= "</tbody></table></body></html>";
  8158.         // Configuration et rendu du PDF
  8159.         $options = new Options();
  8160.         $options->set('defaultFont''Arial');
  8161.         $dompdf = new Dompdf($options);
  8162.         $dompdf->loadHtml($html);
  8163.         $dompdf->setPaper('A4''landscape');
  8164.         $dompdf->render();
  8165.         // Création du dossier s'il n'existe pas
  8166.         $projectDir $kernel->getProjectDir();
  8167.         $outputDir $projectDir '/public/assets/pdf/rdv';
  8168.         $filesystem = new Filesystem();
  8169.         if (!$filesystem->exists($outputDir)) {
  8170.             $filesystem->mkdir($outputDir0775);
  8171.         }
  8172.         $filenameDate $start->format('Y-m-d') . '_to_' $end->format('Y-m-d');
  8173.         $outputPath "$outputDir/rdvs-$filenameDate.pdf";
  8174.         file_put_contents($outputPath$dompdf->output());
  8175.         return new Response($dompdf->output(), 200, [
  8176.             'Content-Type' => 'application/pdf',
  8177.             'Content-Disposition' => 'attachment; filename="rdvs-' $filenameDate '.pdf"',
  8178.         ]);
  8179.     }
  8180.     /**
  8181.      * 
  8182.      * @Route("/admin/rdv/export/excel/{startDate}/{endDate}", name="admin_rdv_export_excel", methods={"GET"})
  8183.      */
  8184.     public function exportExcelFromDate(string $startDatestring $endDate): Response
  8185.     {
  8186.         $start = new \DateTimeImmutable($startDate);
  8187.         $end = new \DateTimeImmutable($endDate);
  8188.         $rdvs $this->rdvRepository->findBySinceDateAndMyAudio($start$end);
  8189.         $spreadsheet = new Spreadsheet();
  8190.         $sheet $spreadsheet->getActiveSheet();
  8191.         // Headers
  8192.         $sheet->fromArray([
  8193.             'ID du RDV',
  8194.             'Date du RDV',
  8195.             'Jours écoulés',
  8196.             'Statut RDV',
  8197.             'Nom patient',
  8198.             'Téléphone patient',
  8199.             'Statut patient',
  8200.             'Centre',
  8201.             'Téléphone Centre',
  8202.             'Adresse',
  8203.             'Nom Audio'
  8204.         ], null'A1');
  8205.         $today = new \DateTimeImmutable();
  8206.         $row 2;
  8207.         foreach ($rdvs as $rdv) {
  8208.             $dateRdv $rdv->getDate();
  8209.             $joursEcoules $dateRdv->diff($today)->days;
  8210.             $client $rdv->getIdClient();
  8211.             $centre $rdv->getIdCentre();
  8212.             $etat $rdv->getIdEtat();
  8213.             $sheet->fromArray([
  8214.                 $rdv->getId(),
  8215.                 $dateRdv->format('d/m/Y H:i'),
  8216.                 $joursEcoules ' jours',
  8217.                 $etat $etat->getLibelle() : 'Non défini',
  8218.                 $client $client->getName() . ' ' $client->getLastname() : '',
  8219.                 $client $client->getPhone() : '',
  8220.                 $client && $client->getClientStatus() ? $client->getClientStatus()->getLibelle() : 'Non défini',
  8221.                 $centre $centre->getName() : '',
  8222.                 $centre $centre->getPhone() : '',
  8223.                 $centre $centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity() : '',
  8224.                 $rdv->getIdAudio() ? $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastname() : '',
  8225.             ], null'A' $row);
  8226.             $row++;
  8227.         }
  8228.         $writer = new Xlsx($spreadsheet);
  8229.         $filename "rdvs-$startDate-to-$endDate.xlsx";
  8230.         // Stream the file to browser
  8231.         $response = new \Symfony\Component\HttpFoundation\StreamedResponse(function () use ($writer) {
  8232.             $writer->save('php://output');
  8233.         });
  8234.         $dispositionHeader $response->headers->makeDisposition(
  8235.             \Symfony\Component\HttpFoundation\ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  8236.             $filename
  8237.         );
  8238.         $response->headers->set('Content-Type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  8239.         $response->headers->set('Content-Disposition'$dispositionHeader);
  8240.         return $response;
  8241.     }
  8242.     /**
  8243.      * 
  8244.      * @Route("/optical/rdv/export/excel/{startDate}/{endDate}", name="optical_rdv_export_excel", methods={"GET"})
  8245.      */
  8246.     public function exportOpticalExcelFromDate(string $startDatestring $endDate): Response
  8247.     {
  8248.         $start = new \DateTimeImmutable($startDate);
  8249.         $end = new \DateTimeImmutable($endDate);
  8250.         $rdvs $this->rdvRepository->findOpticalBySinceDateAndMyAudio($start$end);
  8251.         $spreadsheet = new Spreadsheet();
  8252.         $sheet $spreadsheet->getActiveSheet();
  8253.         // Headers
  8254.         $sheet->fromArray([
  8255.             'ID du RDV',
  8256.             'Date du RDV',
  8257.             'Jours écoulés',
  8258.             'Statut RDV',
  8259.             'Nom patient',
  8260.             'Téléphone patient',
  8261.             'Statut patient',
  8262.             'Centre',
  8263.             'Téléphone Centre',
  8264.             'Adresse',
  8265.             'Nom Audio'
  8266.         ], null'A1');
  8267.         $today = new \DateTimeImmutable();
  8268.         $row 2;
  8269.         foreach ($rdvs as $rdv) {
  8270.             $dateRdv $rdv->getDate();
  8271.             $joursEcoules $dateRdv->diff($today)->days;
  8272.             $client $rdv->getIdClient();
  8273.             $centre $rdv->getIdCentre();
  8274.             $etat $rdv->getIdEtat();
  8275.             $sheet->fromArray([
  8276.                 $rdv->getId(),
  8277.                 $dateRdv->format('d/m/Y H:i'),
  8278.                 $joursEcoules ' jours',
  8279.                 $etat $etat->getLibelle() : 'Non défini',
  8280.                 $client $client->getName() . ' ' $client->getLastname() : '',
  8281.                 $client $client->getPhone() : '',
  8282.                 $client && $client->getClientStatus() ? $client->getClientStatus()->getLibelle() : 'Non défini',
  8283.                 $centre $centre->getName() : '',
  8284.                 $centre $centre->getPhone() : '',
  8285.                 $centre $centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity() : '',
  8286.                 $rdv->getIdAudio() ? $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastname() : '',
  8287.             ], null'A' $row);
  8288.             $row++;
  8289.         }
  8290.         $writer = new Xlsx($spreadsheet);
  8291.         $filename "rdvs-$startDate-to-$endDate.xlsx";
  8292.         // Stream the file to browser
  8293.         $response = new \Symfony\Component\HttpFoundation\StreamedResponse(function () use ($writer) {
  8294.             $writer->save('php://output');
  8295.         });
  8296.         $dispositionHeader $response->headers->makeDisposition(
  8297.             \Symfony\Component\HttpFoundation\ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  8298.             $filename
  8299.         );
  8300.         $response->headers->set('Content-Type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  8301.         $response->headers->set('Content-Disposition'$dispositionHeader);
  8302.         return $response;
  8303.     }
  8304.     /**
  8305.      * 
  8306.      * @Route("/admin/update-note", name="update_note", methods={"POST"})
  8307.      */
  8308.     public function updateNote(Request $requestEntityManagerInterface $em): JsonResponse
  8309.     {
  8310.         $data json_decode($request->getContent(), true);
  8311.         $id $data['id'] ?? null;
  8312.         $note $data['note'] ?? null;
  8313.         if (!$id || $note === null) {
  8314.             return new JsonResponse(['status' => 'error''message' => 'Invalid data'], 400);
  8315.         }
  8316.         $entity $em->getRepository(Rdv::class)->find($id);
  8317.         if (!$entity) {
  8318.             return new JsonResponse(['status' => 'error''message' => 'Entity not found'], 404);
  8319.         }
  8320.         $entity->setNote($note);
  8321.         $em->flush();
  8322.         return new JsonResponse(['status' => 'success']);
  8323.     }
  8324.     /**
  8325.      * 
  8326.      * @Route("/giuili-admin/edit-rdv/{rdvId}/centre/{centreId}", name="update_admin_rdv", methods={"GET"})
  8327.      */
  8328.     public function showRdvCentre(int $rdvIdCentre $centreId): Response
  8329.     {
  8330.         // dd("tets");
  8331.         $center $centres $this->getDoctrine()
  8332.             ->getRepository(AudioCentre::class)
  8333.             ->findOneBy(['id_centre' => $centreId->getId()]);
  8334.         $audio $center->getIdAudio();
  8335.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  8336.             ->findBy(['id_audio' => $audio'isDeleted' => 0]);
  8337.         return $this->render('easyadmin/rdv/centre_show.html.twig', [
  8338.             'audio' => $audio,
  8339.             'rdvId' => $rdvId,
  8340.             'centreId' => $centreId,
  8341.             'motifs' => $motifs,
  8342.         ]);
  8343.     }
  8344.     
  8345.     /**
  8346.      * 
  8347.      * @Route("/optical-center/edit-rdv/{rdvId}/centre/{centreId}", name="update_optical_rdv", methods={"GET"})
  8348.      */
  8349.     public function showRdvCentreOptical(int $rdvIdCentre $centreId): Response
  8350.     {
  8351.         // dd("tets");
  8352.         $center $centres $this->getDoctrine()
  8353.             ->getRepository(AudioCentre::class)
  8354.             ->findOneBy(['id_centre' => $centreId->getId()]);
  8355.         $audio $center->getIdAudio();
  8356.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  8357.             ->findBy(['id_audio' => $audio'isDeleted' => 0]);
  8358.         return $this->render('easyadmin/rdv/centre_show.html.twig', [
  8359.             'audio' => $audio,
  8360.             'rdvId' => $rdvId,
  8361.             'centreId' => $centreId,
  8362.             'motifs' => $motifs,
  8363.         ]);
  8364.     }
  8365.     /**
  8366.      * @Route("/update-rdv-easyadmin", name="update_rdv_easyadmin", methods={"POST"})
  8367.      */
  8368.     public function updateRdvEasyadmin(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  8369.     {
  8370.         $data json_decode($request->getContent(), true);
  8371.         $rdv $this->getDoctrine()
  8372.             ->getRepository(Rdv::class)
  8373.             ->find($data["rdv_id"]);
  8374.         $pastDate $rdv->getDate();
  8375.         $entityManager $this->getDoctrine()->getManager();
  8376.         if (isset($data["etat_id"])) {
  8377.             $etat $this->getDoctrine()
  8378.                 ->getRepository(EtatRdv::class)
  8379.                 ->findOneBy(['id' => $data["etat_id"]]);
  8380.             if ($etat == null) {
  8381.                 return new Response(json_encode(([
  8382.                     'message' => 'Error, no etat found at this id',
  8383.                     'path' => 'src/Controller/TrustedUserController.php',
  8384.                     "status" => 400,
  8385.                 ])), 400);
  8386.             }
  8387.             $rdv->setIdEtat($etat);
  8388.         }
  8389.         if (isset($data["audio_id"])) {
  8390.             $audio $this->getDoctrine()
  8391.                 ->getRepository(Audio::class)
  8392.                 ->findOneBy(['id' => $data["audio_id"]]);
  8393.             if ($audio == null) {
  8394.                 return new Response(json_encode(([
  8395.                     'message' => 'Error, no audio found at this id',
  8396.                     'path' => 'src/Controller/TrustedUserController.php',
  8397.                     "status" => 400,
  8398.                 ])), 400);
  8399.             }
  8400.             $rdv->setIdAudio($audio);
  8401.         }
  8402.         if (isset($data["motif_id"])) {
  8403.             $motif $this->getDoctrine()
  8404.                 ->getRepository(Motif::class)
  8405.                 ->find($data["motif_id"]);
  8406.             if ($motif == null) {
  8407.                 return new Response(json_encode(([
  8408.                     'message' => 'Error, no motif found at this id',
  8409.                     'path' => 'src/Controller/TrustedUserController.php',
  8410.                     "status" => 400,
  8411.                 ])), 400);
  8412.             }
  8413.             $rdv->setIdMotif($motif);
  8414.         }
  8415.         if (isset($data["client_id"])) {
  8416.             $client $this->getDoctrine()
  8417.                 ->getRepository(Client::class)
  8418.                 ->findOneBy(['id' => $data["client_id"]]);
  8419.             if ($client == null) {
  8420.                 return new Response(json_encode(([
  8421.                     'message' => 'Error, no client found at this id',
  8422.                     'path' => 'src/Controller/TrustedUserController.php',
  8423.                     "status" => 400,
  8424.                 ])), 400);
  8425.             }
  8426.             $rdv->setIdClient($client);
  8427.         }
  8428.         if (isset($data["date"])) {
  8429.             $data["date"] = str_replace("h"":"$data["date"]);
  8430.             $date \DateTime::createFromFormat("Y-m-d\TH:i"$data["date"]);
  8431.             $audioMotif $this->getDoctrine()
  8432.                 ->getRepository(AudioMotif::class)
  8433.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  8434.             if ($audioMotif == null) {
  8435.                 return new Response(json_encode(([
  8436.                     'message' => 'Error, no motif of this id found at this audio',
  8437.                     'path' => 'src/Controller/RdvController.php',
  8438.                     "status" => 400,
  8439.                 ])), 400);
  8440.             }
  8441.             if ($rdv->getIdAudio()->getIsIndie()) {
  8442.                 if ($rdv->getIdCentre()) {
  8443.                     // regular centre audio indie
  8444.                     /** @var AudioCentre */
  8445.                     $liaison $this->getDoctrine()
  8446.                         ->getRepository(AudioCentre::class)
  8447.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  8448.                     if ($liaison == null) {
  8449.                         return new Response(json_encode(([
  8450.                             'message' => 'Error, audio isnt part of the centre',
  8451.                             'path' => 'src/Controller/RdvController.php',
  8452.                             "status" => 400,
  8453.                         ])), 400);
  8454.                     }
  8455.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  8456.                         return new Response(json_encode(([
  8457.                             'message' => 'Error, no horaire found for this audio',
  8458.                             'path' => 'src/Controller/RdvController.php',
  8459.                             "status" => 400,
  8460.                         ])), 400);
  8461.                     }
  8462.                 } else {
  8463.                     // lieu audio indie
  8464.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  8465.                         return new Response(json_encode(([
  8466.                             'message' => 'Error, no horaire found for this audio',
  8467.                             'path' => 'src/Controller/RdvController.php',
  8468.                             "status" => 400,
  8469.                         ])), 400);
  8470.                     }
  8471.                 }
  8472.             } else {
  8473.                 // regular centre
  8474.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  8475.                     return new Response(json_encode(([
  8476.                         'message' => 'Error, no horaire found for this audio',
  8477.                         'path' => 'src/Controller/RdvController.php',
  8478.                         "status" => 400,
  8479.                     ])), 400);
  8480.                 }
  8481.             }
  8482.             $rdv->setDate($date);
  8483.         }
  8484.         if (isset($data["comment"]) && $token->getIdClient()) {
  8485.             $rdv->setComment($data["comment"]);
  8486.         }
  8487.         if (isset($data["review"]) && $token->getIdClient()) {
  8488.             $rdv->setReview($data["review"]);
  8489.         }
  8490.         if (isset($data["note"])) {
  8491.             $rdv->setNote($data["note"]);
  8492.         }
  8493.         $entityManager->flush();
  8494.         $date $rdv->getDate();
  8495.         $smsDate $date->format('d-m-Y H:i');
  8496.         $oldDate $pastDate->format('d-m-Y H:i');
  8497.         $locale 'fr_FR';
  8498.         $formatter = new IntlDateFormatter(
  8499.             $locale,
  8500.             IntlDateFormatter::FULL,
  8501.             IntlDateFormatter::SHORT,
  8502.             null,
  8503.             IntlDateFormatter::GREGORIAN,
  8504.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  8505.         );
  8506.         $smsDateLongFormat $formatter->format($date);
  8507.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  8508.         $frenchDate ucfirst($frenchDate);
  8509.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  8510.         // notif client
  8511.         if ($rdv->getIdEtat()->getId() != 2) {
  8512.             $params = array(
  8513.                 "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  8514.                 "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  8515.                 "date" => $smsDateLongFormat,
  8516.                 "heure" => substr($smsDate1115),
  8517.                 "motif" => $rdv->getIdMotif()->getTitre(),
  8518.                 "centerName" => $rdv->getIdCentre()->getName(),
  8519.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  8520.                 "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  8521.                 "audioMail" => $rdv->getIdAudio()->getMail(),
  8522.                 "centerPhone" => $rdv->getIdCentre()->getPhone(),
  8523.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  8524.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  8525.                 'titre' => 'Votre rendez-vous est modifié pour le',
  8526.                 'frenchDate' => $frenchDate,
  8527.             );
  8528.             $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  8529.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  8530.             $sms "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  8531.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  8532.         }
  8533.         //     //// == suppression
  8534.         else if ($rdv->getIdEtat()->getId() == 2) {
  8535.             $params = array(
  8536.                 "date" => substr($smsDate010),
  8537.                 "lien" => "{$_ENV['BASE_client']}search",
  8538.                 "heure" => substr($smsDate1115),
  8539.                 "patientName" => $client->getLastName(),
  8540.                 'titre' => 'Votre rendez-vous est annulé :',
  8541.                 'centerName' => $rdv->getIdCentre()->getName(),
  8542.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  8543.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  8544.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  8545.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  8546.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  8547.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  8548.                 'motif' => $rdv->getIdMotif()->getTitre(),
  8549.             );
  8550.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  8551.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  8552.             if ($data["sms"]) {
  8553.                 $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  8554.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  8555.             }
  8556.         }
  8557.         //notif Audio
  8558.         if ($rdv->getIdEtat()->getId() != 2) {
  8559.             $params = array(
  8560.                 "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  8561.                 "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  8562.                 "date" => substr($smsDate010),
  8563.                 "frenchDate" => $frenchDate,
  8564.                 "heure" => substr($smsDate1115),
  8565.                 'motif' => $rdv->getIdMotif()->getTitre(),
  8566.                 'clientPhone' => $client->getPhone(),
  8567.                 'clientNom' => $client->getLastname(),
  8568.                 'clientPrenom' => $client->getName(),
  8569.                 'clientCivilite' => $client->getCivilite(),
  8570.                 'clientPostal' => $client->getPostal(),
  8571.                 'clientMail' => $client->getMail(),
  8572.                 'centerName' => $rdv->getIdCentre()->getName(),
  8573.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  8574.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  8575.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  8576.                 'idPatient' => $client->getId(),
  8577.                 'proUrl' => "{$_ENV['BASE_logiciel']}",
  8578.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  8579.                 'titre' => 'Votre rendez-vous est modifié pour le :'
  8580.             );
  8581.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  8582.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  8583.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  8584.                 $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  8585.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  8586.             }
  8587.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  8588.                 $sms "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre patient " $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  8589.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  8590.             }
  8591.         } else if ($rdv->getIdEtat()->getId() == 2) {
  8592.             $params = array(
  8593.                 "date" => substr($smsDate010),
  8594.                 "lien" => "{$_ENV['BASE_client']}search",
  8595.                 "heure" => substr($smsDate1115),
  8596.                 "patientName" => $client->getLastName(),
  8597.                 'titre' => 'Votre rendez-vous est annulé :',
  8598.                 'centerName' => $rdv->getIdCentre()->getName(),
  8599.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  8600.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  8601.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  8602.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  8603.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  8604.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  8605.                 'motif' => $rdv->getIdMotif()->getTitre(),
  8606.             );
  8607.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  8608.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  8609.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  8610.                 $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  8611.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject188);
  8612.             }
  8613.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  8614.                 $sms "Votre RDV du " substr($oldDate010) . " à " substr($oldDate1115) . "a été annulé, vous pouvez contacter votre patient pour fixer un autre RDV:" $client->getPhone() . " pour fixer un autre RDV.\nNe pas répondre.";
  8615.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  8616.             }
  8617.         }
  8618.         /* generate sms notif on update */
  8619.         // update sms notification     
  8620.         $rdvSms->updateRdvSms($rdv);
  8621.         // google calendar update
  8622.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  8623.             ->findBy(array('audio' => $rdv->getIdAudio()));
  8624.         $data['rdv'] = $rdv->getId();
  8625.         $data['motif_id'] = $rdv->getIdMotif();
  8626.         $data['note'] = $rdv->getNote();
  8627.         if ($rdv->getIdClient() !== null) {
  8628.             $data["client_id"] = $rdv->getIdClient()->getId();
  8629.         }
  8630.         if ($rdv->getIdClientTemp() !== null) {
  8631.             $data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
  8632.         }
  8633.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  8634.             ->findBy(array('rdv' => $rdv));
  8635.         foreach ($rdvEvents as $rdvEvent) {
  8636.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  8637.             $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  8638.         }
  8639.         return new Response(json_encode(([
  8640.             "id" => $rdv->getId(),
  8641.             "motif_id" => $rdv->getIdMotif()->getId(),
  8642.             "audio_id" => $rdv->getIdAudio()->getId(),
  8643.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  8644.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  8645.             "fullName" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  8646.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  8647.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  8648.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  8649.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  8650.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  8651.             "centre_id" => $rdv->getIdCentre()->getId(),
  8652.             "centerName" => $rdv->getIdCentre()->getName(),
  8653.             "etat_id" => $rdv->getIdEtat()->getId(),
  8654.             "date" => $rdv->getDate(),
  8655.             "comment" => $rdv->getComment(),
  8656.             "note" => $rdv->getNote(),
  8657.             "review" => $rdv->getReview(),
  8658.             "status" => 200,
  8659.         ])));
  8660.     }
  8661.     private function checkRdvReminder($rdv): ?array
  8662.     {
  8663.         $dateRdv $rdv->getDate();
  8664.         $today = new \DateTime();
  8665.         $today->setTime(000);
  8666.         $dateRdv->setTime(000);
  8667.         $intervalDays $today->diff($dateRdv)->days;
  8668.         if ($intervalDays === 1) {
  8669.             $interval "24";
  8670.         } elseif ($intervalDays === 2) {
  8671.             $interval "48";
  8672.         } elseif ($intervalDays === 3) {
  8673.             $interval "72";
  8674.         } elseif ($intervalDays === 4) {
  8675.             $interval "96";
  8676.         } else { // >= 4 jours
  8677.             $interval "92";
  8678.         }
  8679.         $client $rdv->getIdClientTemp() ?: $rdv->getIdClient();
  8680.         $clientId $client $client->getId() : null;
  8681.         $clientName null;
  8682.         if ($client) {
  8683.             $clientName $client->getName() . ' ' $client->getLastName();
  8684.         }
  8685.         $motif $rdv->getIdMotif();
  8686.         $motifTitle $motif $motif->getTitre() : null;
  8687.         $centre $rdv->getIdCentre();
  8688.         $centreName null;
  8689.         if ($centre) {
  8690.             $centreName $centre->getName();
  8691.         }
  8692.         return [
  8693.             'rdvId' => $rdv->getId(),
  8694.             'clientId' => $clientId,
  8695.             'clientName' => $clientName ?? 'N/A',
  8696.             'interval' => $interval,
  8697.             'date' => $rdv->getDate() ? $rdv->getDate()->format('d-m-Y H:i') : null,
  8698.             'motif' => $motifTitle ?? 'N/A',
  8699.             'centreName' => $centreName ?? 'N/A',
  8700.         ];
  8701.     }
  8702. }