src/Controller/RdvController.php line 8705

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\Token;
  13. use Twig\Environment;
  14. use App\Entity\Centre;
  15. use App\Entity\Client;
  16. use \IntlDateFormatter;
  17. use App\Entity\CallLog;
  18. use App\Entity\EtatRdv;
  19. use App\Entity\LeadRdv;
  20. use App\Entity\Proches;
  21. use App\Entity\LieuTier;
  22. use App\Entity\RdvEvent;
  23. use App\Entity\AudioMotif;
  24. use App\Entity\CentreTier;
  25. use App\Entity\ClientTemp;
  26. use App\Entity\LeadStatus;
  27. use App\Entity\Remplacant;
  28. use App\Entity\TestClient;
  29. use App\Entity\AudioCentre;
  30. use App\Service\SmsHandler;
  31. use App\Entity\AccessCentre;
  32. use App\Entity\ClientStatus;
  33. use Psr\Log\LoggerInterface;
  34. use App\Entity\ClientBlocked;
  35. use App\Entity\CentreMutuelle;
  36. use App\Entity\LieuPrestation;
  37. use App\Entity\AudioSpecialite;
  38. use App\Entity\CallInteraction;
  39. use App\Service\PublicFunction;
  40. use App\Entity\CentrePrestation;
  41. use App\Entity\RegionDepartment;
  42. use App\Repository\RdvRepository;
  43. use Symfony\Component\Mime\Email;
  44. use App\Entity\Device\ClientDevice;
  45. use App\Entity\Notification\RdvSms;
  46. use App\Service\Lead\TwilioService;
  47. use App\Service\Lead\WhatsappService;
  48. use App\Entity\SynchronisationSetting;
  49. use App\Service\Lead\SynthflowService;
  50. use App\Service\Lead\ElevenLabsService;
  51. use Doctrine\ORM\EntityManagerInterface;
  52. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  53. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  54. use Symfony\Contracts\Cache\ItemInterface;
  55. use App\Service\Cosium\ClientCosiumService;
  56. use App\Service\Notification\RdvSmsService;
  57. use App\Entity\SpecificSubscription;
  58. use Symfony\Contracts\Cache\CacheInterface;
  59. use App\Entity\Synchronisation\CosiumCenter;
  60. use App\Service\Lead\AppointmentCallService;
  61. use Symfony\Component\Filesystem\Filesystem;
  62. use Symfony\Component\HttpFoundation\Request;
  63. use Symfony\Component\Mailer\MailerInterface;
  64. use Symfony\Component\HttpFoundation\Response;
  65. use Symfony\Component\Routing\Annotation\Route;
  66. use Doctrine\Common\Collections\ArrayCollection;
  67. use App\EasyAdmin\Controller\DashboardController;
  68. use Symfony\Component\HttpKernel\KernelInterface;
  69. use Symfony\Component\HttpFoundation\JsonResponse;
  70. use App\EasyAdmin\Controller\LeadRdvCrudController;
  71. use App\Service\AdsCompany\RepresentativeCdaService;
  72. use App\Entity\Synchronisation\SynchronisationCosium;
  73. use App\Service\GoogleCalendar\GoogleCalendarService;
  74. use App\EasyAdmin\Controller\RdvMyAudioCrudController;
  75. use App\Service\Notification\EmailNotificationService;
  76. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  77. use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
  78. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  79. use Symfony\Component\Mercure\PublisherInterface;
  80. use Symfony\Component\Mercure\Update;
  81. use App\Service\Mercure\MercureService;
  82. class RdvController extends AbstractController
  83. {
  84.     private $emailNotificationService;
  85.     private $clientCosiumService;
  86.     private $rdvRepository;
  87.     private $entityManager;
  88.     private $cache;
  89.     private $mercure;
  90.     private $twig;
  91.     private AdminUrlGenerator $adminUrlGenerator;
  92.     private WhatsappService $whatsapp;
  93.     private LoggerInterface $logger;  // Service de journalisation
  94.     private RdvRepository $rdvRepo;
  95.     public function __construct(CacheInterface $cacheEntityManagerInterface $entityManagerRdvRepository $rdvRepoEmailNotificationService $emailNotificationServiceClientCosiumService $clientCosiumServiceRdvRepository $rdvRepositoryEnvironment $twigAdminUrlGenerator $adminUrlGeneratorWhatsappService $whatsappLoggerInterface $logger,MercureService $mercure)
  96.     {
  97.         $this->entityManager $entityManager;
  98.         $this->emailNotificationService $emailNotificationService;
  99.         $this->clientCosiumService $clientCosiumService;
  100.         $this->rdvRepository $rdvRepository;
  101.         $this->cache $cache;
  102.         $this->twig $twig;
  103.         $this->adminUrlGenerator $adminUrlGenerator;
  104.         $this->whatsapp $whatsapp;
  105.         $this->logger $logger;
  106.         $this->rdvRepo $rdvRepo;
  107.         $this->mercure $mercure;
  108.     }
  109.     /**
  110.      * @Route("/rdv/{id}", name="deleteRdvByID", methods={"DELETE"})
  111.      */
  112.     public function deleteRdvByID(Request $requestRdv $rdvGoogleCalendarService $googleCalendar)
  113.     {
  114.         if (!$request->query->get('token')) {
  115.             return new Response(json_encode([
  116.                 "message" => "Pas de token n'a été spécifié",
  117.                 "status" => 401,
  118.             ]), 401);
  119.         }
  120.         $entityManager $this->getDoctrine()->getManager();
  121.         /** @var Token */
  122.         $token $this->getDoctrine()
  123.             ->getRepository(Token::class)
  124.             ->findOneBy(['token' => $request->query->get('token')]);
  125.         if (!$token) {
  126.             return new Response(json_encode([
  127.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  128.                 "status" => 404,
  129.             ]), 404);
  130.         }
  131.         // get token age
  132.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  133.         // if the token if older than 7 days
  134.         if ($dateDiff->7) {
  135.             $entityManager->remove($token);
  136.             $entityManager->flush();
  137.             return $this->json([
  138.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  139.                 'path' => 'src/Controller/ClientController.php',
  140.                 "status" => 401,
  141.             ], 401);
  142.         }
  143.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  144.             return new Response(json_encode([
  145.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  146.                 "status" => 404,
  147.             ]), 404);
  148.         }
  149.         $entityManager->remove($rdv);
  150.         $entityManager->flush();
  151.         return new Response(json_encode(([
  152.             'message' => "Rdv has been successfully deleted",
  153.             "status" => 200,
  154.         ])));
  155.     }
  156.     /**
  157.      * @Route("/rdv/{id}", name="getRdvByID", methods={"GET","HEAD"})
  158.      */
  159.     public function getRdvByID(Request $requestRdv $rdvPublicFunction $publicFunction)
  160.     {
  161.         if (!$request->query->get('token')) {
  162.             return new Response(json_encode([
  163.                 "message" => "Pas de token n'a été spécifié",
  164.                 "status" => 401,
  165.             ]), 401);
  166.         }
  167.         $entityManager $this->getDoctrine()->getManager();
  168.         /** @var Token */
  169.         $token $this->getDoctrine()
  170.             ->getRepository(Token::class)
  171.             ->findOneBy(['token' => $request->query->get('token')]);
  172.         if (!$token) {
  173.             return new Response(json_encode([
  174.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  175.                 "status" => 404,
  176.             ]), 404);
  177.         }
  178.         // get token age
  179.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  180.         // if the token if older than 7 days
  181.         if ($dateDiff->7) {
  182.             $entityManager->remove($token);
  183.             $entityManager->flush();
  184.             return $this->json([
  185.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  186.                 'path' => 'src/Controller/ClientController.php',
  187.                 "status" => 401,
  188.             ], 401);
  189.         }
  190.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  191.             return new Response(json_encode([
  192.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  193.                 "status" => 404,
  194.             ]), 404);
  195.         }
  196.         /** @var AudioCentre */
  197.         $liaison $this->getDoctrine()->getRepository(AudioCentre::class)
  198.             ->findOneBy(array('id_audio' => $rdv->getIdAudio(), 'id_centre' => $rdv->getIdCentre(), 'isConfirmed' => true));
  199.         // Motif filter
  200.         /** @var AudioMotif[] */
  201.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  202.             ->findBy(array('id_audio' => $rdv->getIdAudio(), 'id_motif' => $rdv->getIdMotif()));
  203.         $resultMotif = new ArrayCollection();
  204.         foreach ($motifs as $motif) {
  205.             $resultMotif->add([
  206.                 "id" => $motif->getIdMotif()->getId(),
  207.                 "titre" => $motif->getIdMotif()->getTitre(),
  208.                 "consigne" => $motif->getConsigne(),
  209.                 "duration" => $motif->getDuration(),
  210.             ]);
  211.         }
  212.         // Specialities
  213.         /** @var AudioSpecialite[] */
  214.         $specialities $this->getDoctrine()->getRepository(AudioSpecialite::class)
  215.             ->findBy(array('id_audio' => $rdv->getIdAudio()));
  216.         $resultSpeciality = new ArrayCollection();
  217.         foreach ($specialities as $speciality) {
  218.             $resultSpeciality->add([
  219.                 "id" => $speciality->getIdSpecialite()->getId(),
  220.                 "titre" => $speciality->getIdSpecialite()->getLibelle(),
  221.             ]);
  222.         }
  223.         if ($rdv->getIdCentre())
  224.         /** @var AccessCentre*/
  225.         {
  226.             $accessCentre $this->getDoctrine()->getRepository(AccessCentre::class)
  227.                 ->findOneBy(array('id_centre' => $rdv->getIdCentre()));
  228.         } else
  229.         /** @var AccessCentre*/
  230.         {
  231.             $accessCentre $this->getDoctrine()->getRepository(AccessCentre::class)
  232.                 ->findOneBy(array('id_lieu' => $rdv->getIdLieu()));
  233.         }
  234.         if ($rdv->getIdCentre())
  235.         /** @var CentrePrestation[]*/
  236.         {
  237.             $prestations $this->getDoctrine()->getRepository(CentrePrestation::class)
  238.                 ->findBy(array('id_centre' => $liaison->getIdCentre()->getId()));
  239.         } else
  240.         /** @var LieuPrestation[]*/
  241.         {
  242.             $prestations $this->getDoctrine()->getRepository(LieuPrestation::class)
  243.                 ->findBy(array('id_lieu' => $rdv->getIdLieu()));
  244.         }
  245.         $resultPrestation = new ArrayCollection();
  246.         foreach ($prestations as $prestation) {
  247.             $resultPrestation->add([
  248.                 "id" => $prestation->getIdPrestation()->getId(),
  249.                 "titre" => $prestation->getIdPrestation()->getLibelle(),
  250.             ]);
  251.         }
  252.         $mutuelles $this->getDoctrine()->getRepository(CentreMutuelle::class)
  253.             ->findBy(array('id_centre' => $rdv->getIdCentre()));
  254.         $resultMutuelle = new ArrayCollection();
  255.         foreach ($mutuelles as $mutuelle) {
  256.             $resultMutuelle->add([
  257.                 "id" => $mutuelle->getIdMutuelle()->getId(),
  258.                 "titre" => $mutuelle->getIdMutuelle()->getLibelle(),
  259.             ]);
  260.         }
  261.         if ($rdv->getIdCentre())
  262.         /** @var CentreTier[]*/
  263.         {
  264.             $tiers $this->getDoctrine()->getRepository(CentreTier::class)
  265.                 ->findBy(array('id_centre' => $liaison->getIdCentre()->getId()));
  266.         } else
  267.         /** @var LieuTier[]*/
  268.         {
  269.             $tiers $this->getDoctrine()->getRepository(LieuTier::class)
  270.                 ->findBy(array('id_lieu' => $rdv->getIdLieu()));
  271.         }
  272.         $resultTier = new ArrayCollection();
  273.         foreach ($tiers as $tier) {
  274.             $resultTier->add([
  275.                 "id" => $tier->getIdTier()->getId(),
  276.                 "titre" => $tier->getIdTier()->getLibelle(),
  277.             ]);
  278.         }
  279.         $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  280.         /** @var Rdv[] */
  281.         $audioRdvs $this->getDoctrine()->getRepository(Rdv::class)
  282.             ->findAllReviewsAudio($rdv->getIdAudio()->getId());
  283.         /** @var Rdv[] */
  284.         $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  285.             ->findAllReviewsCentre($rdvCentre->getId());
  286.         // Comment
  287.         /** @var Rdv[] */
  288.         $rdvs $this->getDoctrine()->getRepository(Rdv::class)
  289.             ->findBy(array('id_audio' => $rdv->getIdAudio()));
  290.         $comments = [];
  291.         foreach ($rdvs as $rdv)
  292.             if ($rdv->getComment() && $rdv->getReview() && $rdv->getIdClient())
  293.                 array_push($comments, [
  294.                     "id" => $rdv->getIdClient()->getId(),
  295.                     "name" => $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname()[0] . ".",
  296.                     "comment" => $rdv->getComment(),
  297.                     "isMale" => $rdv->getIdClient()->getCivilite() == "Monsieur",
  298.                     "review" => $rdv->getReview(),
  299.                 ]);
  300.         return new Response(json_encode(([
  301.             "id" => $rdv->getId(),
  302.             "motif_id" => $rdv->getIdMotif()->getId(),
  303.             "motif_titre" => $rdv->getIdMotif()->getTitre(),
  304.             "audio_id" => $rdv->getIdAudio()->getId(),
  305.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  306.             "client_id" => $rdv->getIdClient()->getId(),
  307.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  308.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  309.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  310.             "etat_id" => $rdv->getIdEtat()->getId(),
  311.             "date" => $rdv->getDate(),
  312.             "comment" => $rdv->getComment(),
  313.             "review" => $rdv->getReview(),
  314.             "note" => $rdv->getNote(),
  315.             "testclient" => $rdv->getTestClient() ? [
  316.                 "result" => $rdv->getTestClient()->getResultTonal(),
  317.                 "date" => $rdv->getTestClient()->getDate(),
  318.                 "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  319.             ] : null,
  320.             "comments" => $comments,
  321.             "audio" => [
  322.                 "id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : $rdv->getIdAudio()->getId(),
  323.                 "civilite" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getCivilite() : $rdv->getIdAudio()->getCivilite(),
  324.                 "name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() : $rdv->getIdAudio()->getName(),
  325.                 "lastname" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getLastname(),
  326.                 "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  327.                 "mail" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getMail() : $rdv->getIdAudio()->getMail(),
  328.                 "phone" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getPhone() : $rdv->getIdAudio()->getPhone(),
  329.                 "adeli" => $rdv->getIdAudio()->getAdeli(),
  330.                 "pin" => $rdv->getIdAudio()->getPin(),
  331.                 "description" => $rdv->getIdAudio()->getDescription(),
  332.                 "averageRating" => $publicFunction->calculateRating($audioRdvs),
  333.                 "nbrReview" => count($audioRdvs),
  334.                 "motifs" => $resultMotif->toArray(),
  335.                 "specialities" => $resultSpeciality->toArray(),
  336.             ],
  337.             "centre" => [
  338.                 "id" => $rdvCentre->getId(),
  339.                 "audio_id" => $rdvCentre->getIdGerant()->getId(),
  340.                 "name" => $rdvCentre->getName(),
  341.                 "imgUrl" => $rdvCentre->getImgUrl(),
  342.                 "isRdvDomicile" => $rdv->getIdCentre() ? $rdvCentre->getIsRdvDomicile() : $rdv->getIdAudio()->getIsRdvDomicileIndie(),
  343.                 "address" => $rdvCentre->getAddress(),
  344.                 "postale" => $rdvCentre->getPostale(),
  345.                 "city" => $rdvCentre->getCity(),
  346.                 "finess" => $rdvCentre->getFiness(),
  347.                 "siret" => $rdvCentre->getSiret(),
  348.                 "website" => $rdvCentre->getWebsite(),
  349.                 "phone" => $rdvCentre->getPhone(),
  350.                 "isHandicap" => $rdvCentre->getIsHandicap(),
  351.                 "longitude" => $rdvCentre->getLongitude(),
  352.                 "latitude" => $rdvCentre->getLatitude(),
  353.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  354.                 "nbrReview" => count($centreRdvs),
  355.                 "tram" => $accessCentre->getTram(),
  356.                 "rer" => $accessCentre->getRer(),
  357.                 "metro" => $accessCentre->getMetro(),
  358.                 "bus" => $accessCentre->getBus(),
  359.                 "parking" => $accessCentre->getParkingPublic(),
  360.                 "description" => $rdv->getIdCentre()->getDescription(),
  361.                 "parkingPrivate" => $accessCentre->getParkingPrivate(),
  362.                 "other" => $accessCentre->getOther(),
  363.                 "prestations" => $resultPrestation->toArray(),
  364.                 "mutuelles" => $resultMutuelle->toArray(),
  365.                 "tiers" => $resultTier->toArray(),
  366.                 "isLieu" => false,
  367.                 "schedule" => $rdv->getIdAudio()->getIsIndie() == false $rdv->getIdCentre()->getHoraire() : ($rdv->getIdLieu() ? $rdv->getIdLieu()->getHoraire() : $liaison->getHoraire()),
  368.             ],
  369.             "status" => 200,
  370.         ])));
  371.     }
  372.     /**
  373.      * @Route("/rdvs/client/{id}", name="getRdvsByClientID", methods={"GET","HEAD"})
  374.      */
  375.     public function getRdvsByClientID(Request $requestClient $clientPublicFunction $publicFunction)
  376.     {
  377.         if (!$request->query->get('token')) {
  378.             return new Response(json_encode([
  379.                 "message" => "Pas de token n'a été spécifié",
  380.                 "status" => 401,
  381.             ]), 401);
  382.         }
  383.         $entityManager $this->getDoctrine()->getManager();
  384.         /** @var Token */
  385.         $token $this->getDoctrine()
  386.             ->getRepository(Token::class)
  387.             ->findOneBy(['token' => $request->query->get('token')]);
  388.         if (!$token) {
  389.             return new Response(json_encode([
  390.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  391.                 "status" => 404,
  392.             ]), 404);
  393.         }
  394.         // get token age
  395.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  396.         // if the token if older than 7 days
  397.         if ($dateDiff->7) {
  398.             $entityManager->remove($token);
  399.             $entityManager->flush();
  400.             return $this->json([
  401.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  402.                 'path' => 'src/Controller/ClientController.php',
  403.                 "status" => 401,
  404.             ], 401);
  405.         }
  406.         if ($token->getIdClient()) {
  407.             if ($client != $token->getIdClient()) {
  408.                 return new Response(json_encode([
  409.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  410.                     "status" => 404,
  411.                 ]), 404);
  412.             }
  413.         } else if ($token->getIdAudio()) {
  414.             /** @var Token */
  415.             $token $this->getDoctrine()
  416.                 ->getRepository(Rdv::class)
  417.                 ->findOneBy(['id_client' => $client'id_audio' => $token->getIdAudio()]);
  418.             if ($client != $token->getIdClient()) {
  419.                 return new Response(json_encode([
  420.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  421.                     "status" => 404,
  422.                 ]), 404);
  423.             }
  424.         } else {
  425.             return new Response(json_encode([
  426.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  427.                 "status" => 404,
  428.             ]), 404);
  429.         }
  430.         if ($request->query->get('audio')) {
  431.             /** @var Rdv[] */
  432.             $rdvs $this->getDoctrine()
  433.                 ->getRepository(Rdv::class)
  434.                 ->findBy(['id_client' => $client->getId(), 'id_audio' => $token->getIdAudio()]);
  435.             $rdvResult = new ArrayCollection();
  436.         } else {
  437.             /** @var Rdv[] */
  438.             $rdvs $this->getDoctrine()
  439.                 ->getRepository(Rdv::class)
  440.                 ->findBy(['id_client' => $client->getId()]);
  441.             $rdvResult = new ArrayCollection();
  442.         }
  443.         if ($request->query->get('old')) {
  444.             $oldRdvResult = new ArrayCollection();
  445.         }
  446.         foreach ($rdvs as $rdv) {
  447.             if ($rdv->getIdEtat()->getId() != 1) {
  448.                 continue;
  449.             }
  450.             /** @var AudioMotif */
  451.             $audioMotif $this->getDoctrine()
  452.                 ->getRepository(AudioMotif::class)
  453.                 ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  454.             if (!$audioMotif) {
  455.                 continue;
  456.             }
  457.             $duration '';
  458.             if (is_null($rdv->getDuration())) {
  459.                 $duration $audioMotif->getDuration();
  460.             } else {
  461.                 $duration $rdv->getDuration();
  462.             }
  463.             $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  464.             /** @var Rdv[] */
  465.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  466.                 ->findAllReviewsCentre($rdvCentre->getId());
  467.             $rdvItem = [
  468.                 "id" => $rdv->getId(),
  469.                 "motif_id" => $rdv->getIdMotif()->getId(),
  470.                 "duration" => $duration,
  471.                 "color" => $audioMotif->getColor(),
  472.                 "audio_id" => $rdv->getIdAudio()->getId(),
  473.                 "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  474.                 "audio_name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() . " " $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  475.                 "client_id" => $rdv->getIdClient()->getId(),
  476.                 "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  477.                 "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  478.                 "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  479.                 "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  480.                 "testclient" => $rdv->getTestClient() ? [
  481.                     "result" => $rdv->getTestClient()->getResultTonal(),
  482.                     "date" => $rdv->getTestClient()->getDate(),
  483.                     "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  484.                 ] : null,
  485.                 "name" => $rdvCentre->getName(),
  486.                 "phone" => $rdvCentre->getPhone(),
  487.                 "imgUrl" => $rdvCentre->getImgUrl(),
  488.                 "address" => $rdvCentre->getAddress(),
  489.                 "postale" => $rdvCentre->getPostale(),
  490.                 "city" => $rdvCentre->getCity(),
  491.                 "etat_id" => $rdvCentre->getId(),
  492.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  493.                 "nbrReview" => count($centreRdvs),
  494.                 "acceptedCurrency" => "CB Chèque",
  495.                 "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  496.                 "note" => $rdv->getNote(),
  497.                 "comment" => $rdv->getComment(),
  498.                 "review" => $rdv->getReview(),
  499.             ];
  500.             if ($rdv->getDate() >= new DateTime()) {
  501.                 $rdvResult->add($rdvItem);
  502.             } else if ($request->query->get('old')) {
  503.                 $oldRdvResult->add($rdvItem);
  504.             }
  505.         }
  506.         if ($request->query->get('old')) {
  507.             if ($request->query->get('onlyOld')) {
  508.                 if (count($rdvResult) > || count($oldRdvResult) > 0) {
  509.                     return new Response(json_encode(([
  510.                         "oldRdv" => $oldRdvResult->toArray(),
  511.                         "status" => 200,
  512.                     ])));
  513.                 } else {
  514.                     return new Response(json_encode(([
  515.                         "message" => "Aucun rendez-vous n'a été trouvé!",
  516.                         "test" => "count:" count($rdvs),
  517.                         'path' => 'src/Controller/RdvController.php',
  518.                         "rdv" => array(),
  519.                         "oldRdv" => array(),
  520.                         "status" => 404,
  521.                     ])));
  522.                 }
  523.             } else {
  524.                 if (count($rdvResult) > || count($oldRdvResult) > 0) {
  525.                     return new Response(json_encode(([
  526.                         "rdv" => $rdvResult->toArray(),
  527.                         "oldRdv" => $oldRdvResult->toArray(),
  528.                         "status" => 200,
  529.                     ])));
  530.                 } else {
  531.                     return new Response(json_encode(([
  532.                         "message" => "Aucun rendez-vous n'a été trouvé!",
  533.                         "test" => "count:" count($rdvs),
  534.                         'path' => 'src/Controller/RdvController.php',
  535.                         "rdv" => array(),
  536.                         "oldRdv" => array(),
  537.                         "status" => 404,
  538.                     ])));
  539.                 }
  540.             }
  541.         } else {
  542.             if (count($rdvResult) > 0) {
  543.                 return new Response(json_encode(([
  544.                     "content" => $rdvResult->toArray(),
  545.                     "status" => 200,
  546.                 ])));
  547.             } else {
  548.                 return new Response(json_encode(([
  549.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  550.                     "test" => "count2:" count($rdvs),
  551.                     'path' => 'src/Controller/RdvController.php',
  552.                     "status" => 404,
  553.                 ])));
  554.             }
  555.         }
  556.     }
  557.     /**
  558.      * @Route("/rdvs/client/{id}/centre", name="getRdvsByClientIDForCentre", methods={"GET","HEAD"})
  559.      */
  560.     public function getRdvsByClientIDForCentre(Request $requestClient $clientPublicFunction $publicFunction)
  561.     {
  562.         if (!$request->query->get('token')) {
  563.             return new Response(json_encode([
  564.                 "message" => "Pas de token n'a été spécifié",
  565.                 "status" => 401,
  566.             ]), 401);
  567.         }
  568.         $entityManager $this->getDoctrine()->getManager();
  569.         /** @var Token */
  570.         $token $this->getDoctrine()
  571.             ->getRepository(Token::class)
  572.             ->findOneBy(['token' => $request->query->get('token')]);
  573.         if (!$token) {
  574.             return new Response(json_encode([
  575.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  576.                 "status" => 404,
  577.             ]), 404);
  578.         }
  579.         $audio $this->getDoctrine()
  580.             ->getRepository(Audio::class)
  581.             ->findOneBy(['id' => $request->query->get('audio')]);
  582.         $audioCentre $this->getDoctrine()
  583.             ->getRepository(AudioCentre::class)
  584.             ->findOneBy(['id_audio' => $audio]);
  585.         // get token age
  586.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  587.         // if the token if older than 7 days
  588.         if ($dateDiff->7) {
  589.             $entityManager->remove($token);
  590.             $entityManager->flush();
  591.             return $this->json([
  592.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  593.                 'path' => 'src/Controller/ClientController.php',
  594.                 "status" => 401,
  595.             ], 401);
  596.         }
  597.         if ($token->getIdClient()) {
  598.             if ($client != $token->getIdClient()) {
  599.                 return new Response(json_encode([
  600.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  601.                     "status" => 404,
  602.                 ]), 404);
  603.             }
  604.         } else if ($token->getIdAudio()) {
  605.             /** @var Token */
  606.             if ($token->getIdAudio() != $audio) {
  607.                 return new Response(json_encode([
  608.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  609.                     "status" => 404,
  610.                 ]), 404);
  611.             }
  612.         } else {
  613.             return new Response(json_encode([
  614.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  615.                 "status" => 404,
  616.             ]), 404);
  617.         }
  618.         if ($request->query->get('centre')) {
  619.             /** @var Rdv[] */
  620.             $rdvs $this->getDoctrine()
  621.                 ->getRepository(Rdv::class)
  622.                 ->findBy(['id_client' => $client->getId(), 'id_centre' => $audioCentre->getIdCentre()]);
  623.             $rdvResult = new ArrayCollection();
  624.         } else {
  625.             /** @var Rdv[] */
  626.             $rdvs $this->getDoctrine()
  627.                 ->getRepository(Rdv::class)
  628.                 ->findBy(['id_client' => $client->getId()]);
  629.             $rdvResult = new ArrayCollection();
  630.         }
  631.         if ($request->query->get('old')) {
  632.             $oldRdvResult = new ArrayCollection();
  633.         }
  634.         foreach ($rdvs as $rdv) {
  635.             /*if ($rdv->getIdEtat()->getId() != 1) {
  636.                 continue;
  637.             }*/
  638.             /** @var AudioMotif */
  639.             $audioMotif $this->getDoctrine()
  640.                 ->getRepository(AudioMotif::class)
  641.                 ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  642.             if (!$audioMotif) {
  643.                 continue;
  644.             }
  645.             $duration '';
  646.             if (is_null($rdv->getDuration())) {
  647.                 $duration $audioMotif->getDuration();
  648.             } else {
  649.                 $duration $rdv->getDuration();
  650.             }
  651.             $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  652.             /** @var Rdv[] */
  653.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  654.                 ->findAllReviewsCentre($rdvCentre->getId());
  655.             $rdvItem = [
  656.                 "id" => $rdv->getId(),
  657.                 "motif_id" => $rdv->getIdMotif()->getId(),
  658.                 "duration" => $duration,
  659.                 "color" => $audioMotif->getColor(),
  660.                 "audio_id" => $rdv->getIdAudio()->getId(),
  661.                 "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  662.                 "audio_name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() . " " $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  663.                 "client_id" => $rdv->getIdClient()->getId(),
  664.                 "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  665.                 "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  666.                 "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  667.                 "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  668.                 "testclient" => $rdv->getTestClient() ? [
  669.                     "result" => $rdv->getTestClient()->getResultTonal(),
  670.                     "date" => $rdv->getTestClient()->getDate(),
  671.                     "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  672.                 ] : null,
  673.                 "name" => $rdvCentre->getName(),
  674.                 "phone" => $rdvCentre->getPhone(),
  675.                 "imgUrl" => $rdvCentre->getImgUrl(),
  676.                 "address" => $rdvCentre->getAddress(),
  677.                 "postale" => $rdvCentre->getPostale(),
  678.                 "city" => $rdvCentre->getCity(),
  679.                 "etat_id" => $rdvCentre->getId(),
  680.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  681.                 "nbrReview" => count($centreRdvs),
  682.                 "acceptedCurrency" => "CB Chèque",
  683.                 "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  684.                 "note" => $rdv->getNote(),
  685.                 "comment" => $rdv->getComment(),
  686.                 "review" => $rdv->getReview(),
  687.                 "status" => $rdv->getIdEtat()->getLibelle()
  688.             ];
  689.             // dd(new DateTime());
  690.             if ($rdv->getDate() >= new DateTime()) {
  691.                 $rdvResult->add($rdvItem);
  692.             } else if ($request->query->get('old')) {
  693.                 $oldRdvResult->add($rdvItem);
  694.             }
  695.         }
  696.         if ($request->query->get('old')) {
  697.             if (count($rdvResult) > || count($oldRdvResult) > 0) {
  698.                 return new Response(json_encode(([
  699.                     "rdv" => $rdvResult->toArray(),
  700.                     "oldRdv" => $oldRdvResult->toArray(),
  701.                     "status" => 200,
  702.                 ])));
  703.             } else {
  704.                 return new Response(json_encode(([
  705.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  706.                     "test" => "count:" count($rdvs),
  707.                     'path' => 'src/Controller/RdvController.php',
  708.                     "status" => 404,
  709.                 ])), 404);
  710.             }
  711.         } else {
  712.             if (count($rdvResult) > 0) {
  713.                 return new Response(json_encode(([
  714.                     "content" => $rdvResult->toArray(),
  715.                     "status" => 200,
  716.                 ])));
  717.             } else {
  718.                 return new Response(json_encode(([
  719.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  720.                     "test" => "count2:" count($rdvs),
  721.                     'path' => 'src/Controller/RdvController.php',
  722.                     "status" => 404,
  723.                 ])));
  724.             }
  725.         }
  726.     }
  727.     /////// CRON
  728.     /**
  729.      * @Route("/confirmRdvSms", name="confirmRdvSms", methods={"GET","HEAD"})
  730.      */
  731.     public function confirmRdvSms(PublicFunction $publicFunction): Response
  732.     {
  733.         $date = new DateTime();
  734.         $minutes_to_add 30;
  735.         $date->add(new DateInterval('PT' $minutes_to_add 'M'));
  736.         $date->setTimezone(new DateTimeZone('Europe/Paris'));
  737.         $currentDate $date->format('Y-m-d H:i:00');
  738.         $toSend $this->getDoctrine()->getRepository(Rdv::class)
  739.             ->findRdvsIn10Mins($currentDate);
  740.         $entityManager $this->getDoctrine()->getManager();
  741.         $rdvResult = new ArrayCollection();
  742.         foreach ($toSend as $rdv) {
  743.             $date $rdv->getDate();
  744.             // $smsDate = $date->format('d-m-Y H:i');
  745.             //$client = $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  746.             //$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.";
  747.             // // $publicFunction->sendEmail("MyAudio <noreply@myaudio.fr>", $client->getMail(), "My Audio: Testing CRON", "<p>Testing Cron.</p>");
  748.             //$response = $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone(), 4);
  749.             //$another_response = explode(" | ", $response);
  750.             // $idSms = trim($another_response[2]);
  751.             // $rdv->setIdSms($idSms);
  752.             //$entityManager->persist($rdv);
  753.             // $entityManager->flush();
  754.         }
  755.         return new Response(json_encode([
  756.             // "test" => $idSms,
  757.             "currentDate" => $currentDate
  758.         ]));
  759.     }
  760.     /////// CRON 
  761.     /**
  762.      * @Route("/validateRdvSms", name="validateRdvSms", methods={"GET","HEAD"})
  763.      */
  764.     public function validateRdvSms(Request $requestPublicFunction $publicFunction): Response
  765.     {
  766.         $entityManager $this->getDoctrine()->getManager();
  767.         $smsId $_GET['smsID'];
  768.         $message $_GET['message'];
  769.         $callLog $this->getDoctrine()
  770.             ->getRepository(CallLog::class)
  771.             ->findOneBy(['smsId' => $smsId]);
  772.         if ($callLog) {
  773.             $callLog->setAnsweredAt(new \DateTimeImmutable());
  774.             $interaction = new CallInteraction;
  775.             $interaction->setCallLog($callLog);
  776.             try {
  777.                 if ($message == "1") {
  778.                     $interaction->setStep('equipment_status');
  779.                     $interaction->setResponse('réponse_reçue');
  780.                     $interaction->setTimestamp(new \DateTimeImmutable());
  781.                     $interaction->setAdditionalData(['digit' => '1''status' => 'en_essai']);
  782.                     $entityManager->persist($interaction);
  783.                     $sms "Merci pour votre réponse. Nous notons que vous êtes actuellement en période d'essai. Merci et bonne journée avec MyAudio";
  784.                     $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  785.                 } else if ($message == "2") {
  786.                     $interaction->setStep('equipment_status');
  787.                     $interaction->setResponse('réponse_reçue');
  788.                     $interaction->setTimestamp(new \DateTimeImmutable());
  789.                     $interaction->setAdditionalData(['digit' => '2''status' => 'finalise']);
  790.                     $entityManager->persist($interaction);
  791.                     $sms "Félicitations pour votre appareillage ! Nous sommes ravis que vous ayez finalisé cet achat important. Bonne journée avec My Audio.";
  792.                     $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  793.                 } else if ($message == "3") {
  794.                     $interaction->setStep('equipment_status');
  795.                     $interaction->setResponse('réponse_reçue');
  796.                     $interaction->setTimestamp(new \DateTimeImmutable());
  797.                     $interaction->setAdditionalData(['digit' => '3''status' => 'abandonne']);
  798.                     $entityManager->persist($interaction);
  799.                     $sms "Nous avons bien noté que vous avez rendu les appareils sans finaliser l'achat. Bonne journée avec My Audio.";
  800.                     $result $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  801.                     error_log("Résultat envoi SMSSSSSSSSSSSSSSSSSSSSSSSSS: " json_encode($result));
  802.                 } else if ($message == "4") {
  803.                     $interaction->setStep('equipment_status');
  804.                     $interaction->setResponse('réponse_reçue');
  805.                     $interaction->setTimestamp(new \DateTimeImmutable());
  806.                     $interaction->setAdditionalData(['digit' => '4''status' => 'attente_rdv_orl']);
  807.                     $entityManager->persist($interaction);
  808.                     $sms "Nous avons bien noté que vous etes en attente d'un rendez-vous avec un ORL. Bonne journée avec My Audio.";
  809.                     $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  810.                 } else if ($message == "5") {
  811.                     $interaction->setStep('equipment_status');
  812.                     $interaction->setResponse('réponse_reçue');
  813.                     $interaction->setTimestamp(new \DateTimeImmutable());
  814.                     $interaction->setAdditionalData(['digit' => '5''status' => 'autre']);
  815.                     $entityManager->persist($interaction);
  816.                     $sms "Merci pour votre réponse. Un conseiller My Audio vous contactera dans les prochains jours. Bonne journée.";
  817.                     $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  818.                 } else {
  819.                     error_log("Message non reconnu: " $message);
  820.                     return new Response(json_encode([
  821.                         "message" => "La réponse spécifiée est incorrecte",
  822.                         "status" => 401,
  823.                         "réponse" => $message,
  824.                     ]), 401);
  825.                 }
  826.                 $entityManager->flush();
  827.                 return new Response(json_encode([
  828.                     "message" => "Réponse traitée avec succès",
  829.                     "status" => 200,
  830.                 ]));
  831.             } catch (\Exception $e) {
  832.                 return new Response(json_encode([
  833.                     "message" => "Erreur lors du traitement de la réponse: " $e->getMessage(),
  834.                     "status" => 500,
  835.                 ]), 500);
  836.             }
  837.         }
  838.         return new Response(json_encode([
  839.             "smsId" => $smsId,
  840.             "message" => $currentDate
  841.         ]));
  842.     }
  843.     /**
  844.      * @Route("/rdvs/old/client/{id}", name="getOldRdvsByClientId", methods={"GET","HEAD"})
  845.      */
  846.     public function getOldRdvsByClientId(Request $requestClient $clientPublicFunction $publicFunction)
  847.     {
  848.         if (!$request->query->get('token')) {
  849.             return new Response(json_encode([
  850.                 "message" => "Pas de token n'a été spécifié",
  851.                 "status" => 401,
  852.             ]), 401);
  853.         }
  854.         $entityManager $this->getDoctrine()->getManager();
  855.         /** @var Token */
  856.         $token $this->getDoctrine()
  857.             ->getRepository(Token::class)
  858.             ->findOneBy(['token' => $request->query->get('token')]);
  859.         if (!$token) {
  860.             return new Response(json_encode([
  861.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  862.                 "status" => 404,
  863.             ]), 404);
  864.         }
  865.         // get token age
  866.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  867.         // if the token if older than 7 days
  868.         if ($dateDiff->7) {
  869.             $entityManager->remove($token);
  870.             $entityManager->flush();
  871.             return $this->json([
  872.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  873.                 'path' => 'src/Controller/ClientController.php',
  874.                 "status" => 401,
  875.             ], 401);
  876.         }
  877.         if ($token->getIdClient()) {
  878.             if ($client != $token->getIdClient()) {
  879.                 return new Response(json_encode([
  880.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  881.                     "status" => 404,
  882.                 ]), 404);
  883.             }
  884.         } else if ($token->getIdAudio()) {
  885.             /** @var Token */
  886.             $token $this->getDoctrine()
  887.                 ->getRepository(Rdv::class)
  888.                 ->findOneBy(['id_client' => $client'id_audio' => $token->getIdAudio()]);
  889.             if ($client != $token->getIdClient()) {
  890.                 return new Response(json_encode([
  891.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  892.                     "status" => 404,
  893.                 ]), 404);
  894.             }
  895.         } else {
  896.             return new Response(json_encode([
  897.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  898.                 "status" => 404,
  899.             ]), 404);
  900.         }
  901.         if ($request->query->get('audio')) {
  902.             /** @var ActivityRepository */
  903.             $activityRepo $this->getDoctrine();
  904.             if ($request->query->get('limit')) {
  905.                 /** @var Rdv[] */
  906.                 $rdvs $activityRepo
  907.                     ->getRepository(Rdv::class)
  908.                     ->findLastsOldRdvsWithLimit($request->query->get('limit'), $client->getId(), $request->query->get('audio'), new DateTime());
  909.                 $rdvResult = new ArrayCollection();
  910.             } else {
  911.                 /** @var Rdv[] */
  912.                 $rdvs $activityRepo
  913.                     ->getRepository(Rdv::class)
  914.                     ->findOldRdvs($client->getId(), $request->query->get('audio'), new DateTime());
  915.                 $rdvResult = new ArrayCollection();
  916.             }
  917.             foreach ($rdvs as $rdv) {
  918.                 /*if ($rdv->getIdEtat()->getId() != 1) {
  919.                     continue;
  920.                 }*/
  921.                 /** @var AudioMotif */
  922.                 $audioMotif $this->getDoctrine()
  923.                     ->getRepository(AudioMotif::class)
  924.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  925.                 if (!$audioMotif) {
  926.                     continue;
  927.                 }
  928.                 $duration '';
  929.                 if (is_null($rdv->getDuration())) {
  930.                     $duration $audioMotif->getDuration();
  931.                 } else {
  932.                     $duration $rdv->getDuration();
  933.                 }
  934.                 $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  935.                 /** @var Rdv[] */
  936.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  937.                     ->findAllReviewsCentre($rdvCentre->getId());
  938.                 $rdvItem = [
  939.                     "id" => $rdv->getId(),
  940.                     "motif_id" => $rdv->getIdMotif()->getId(),
  941.                     "duration" => $duration,
  942.                     "color" => $audioMotif->getColor(),
  943.                     "audio_id" => $rdv->getIdAudio()->getId(),
  944.                     "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  945.                     "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  946.                     "client_id" => $rdv->getIdClient()->getId(),
  947.                     "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  948.                     "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  949.                     "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  950.                     "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  951.                     "testclient" => $rdv->getTestClient() ? [
  952.                         "result" => $rdv->getTestClient()->getResultTonal(),
  953.                         "date" => $rdv->getTestClient()->getDate(),
  954.                         "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  955.                     ] : null,
  956.                     "name" => $rdvCentre->getName(),
  957.                     "phone" => $rdvCentre->getPhone(),
  958.                     "imgUrl" => $rdvCentre->getImgUrl(),
  959.                     "address" => $rdvCentre->getAddress(),
  960.                     "postale" => $rdvCentre->getPostale(),
  961.                     "city" => $rdvCentre->getCity(),
  962.                     "etat_id" => $rdvCentre->getId(),
  963.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  964.                     "nbrReview" => count($centreRdvs),
  965.                     "acceptedCurrency" => "CB Chèque",
  966.                     "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  967.                     "note" => $rdv->getNote(),
  968.                     "comment" => $rdv->getComment(),
  969.                     "review" => $rdv->getReview(),
  970.                 ];
  971.                 $rdvResult->add($rdvItem);
  972.             }
  973.         }
  974.         if (count($rdvResult) > 0) {
  975.             return new Response(json_encode(([
  976.                 "rdv" => $rdvResult->toArray(),
  977.                 "status" => 200,
  978.             ])));
  979.         } else {
  980.             return new Response(json_encode(([
  981.                 "message" => "Aucun rendez-vous a venir!",
  982.                 'path' => 'src/Controller/RdvController.php',
  983.                 "status" => 404,
  984.             ])));
  985.         }
  986.     }
  987.     /**
  988.      * @Route("/rdvs/old/client/{id}/centre", name="getOldRdvsByClientIdForCentre", methods={"GET","HEAD"})
  989.      */
  990.     public function getOldRdvsByClientIdForCentre(Request $requestClient $clientPublicFunction $publicFunction)
  991.     {
  992.         if (!$request->query->get('token')) {
  993.             return new Response(json_encode([
  994.                 "message" => "Pas de token n'a été spécifié",
  995.                 "status" => 401,
  996.             ]), 401);
  997.         }
  998.         $entityManager $this->getDoctrine()->getManager();
  999.         /** @var Token */
  1000.         $token $this->getDoctrine()
  1001.             ->getRepository(Token::class)
  1002.             ->findOneBy(['token' => $request->query->get('token')]);
  1003.         if (!$token) {
  1004.             return new Response(json_encode([
  1005.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1006.                 "status" => 404,
  1007.             ]), 404);
  1008.         }
  1009.         $audio $this->getDoctrine()
  1010.             ->getRepository(Audio::class)
  1011.             ->findOneBy(['id' => $request->query->get('audio')]);
  1012.         $audioCentre $this->getDoctrine()
  1013.             ->getRepository(AudioCentre::class)
  1014.             ->findOneBy(['id_audio' => $audio]);
  1015.         // get token age
  1016.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1017.         // if the token if older than 7 days
  1018.         if ($dateDiff->7) {
  1019.             $entityManager->remove($token);
  1020.             $entityManager->flush();
  1021.             return $this->json([
  1022.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1023.                 'path' => 'src/Controller/ClientController.php',
  1024.                 "status" => 401,
  1025.             ], 401);
  1026.         }
  1027.         if ($token->getIdClient()) {
  1028.             if ($client != $token->getIdClient()) {
  1029.                 return new Response(json_encode([
  1030.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  1031.                     "status" => 404,
  1032.                 ]), 404);
  1033.             }
  1034.         } else if ($token->getIdAudio()) {
  1035.             /** @var Token */
  1036.             if ($token->getIdAudio() != $audio) {
  1037.                 return new Response(json_encode([
  1038.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  1039.                     "status" => 404,
  1040.                 ]), 404);
  1041.             }
  1042.         } else {
  1043.             return new Response(json_encode([
  1044.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  1045.                 "status" => 404,
  1046.             ]), 404);
  1047.         }
  1048.         if ($request->query->get('audio')) {
  1049.             /** @var ActivityRepository */
  1050.             $activityRepo $this->getDoctrine();
  1051.             if ($request->query->get('limit')) {
  1052.                 /** @var Rdv[] */
  1053.                 $rdvs $activityRepo
  1054.                     ->getRepository(Rdv::class)
  1055.                     ->findLastsOldRdvCentresWithLimit($request->query->get('limit'), $client->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  1056.                 $rdvResult = new ArrayCollection();
  1057.             } else {
  1058.                 /** @var Rdv[] */
  1059.                 $rdvs $activityRepo
  1060.                     ->getRepository(Rdv::class)
  1061.                     ->findOldRdvsByCentre($client->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  1062.                 $rdvResult = new ArrayCollection();
  1063.             }
  1064.             //dd($rdvs);
  1065.             foreach ($rdvs as $rdv) {
  1066.                 // we comment this becoz it was just the validate , we implment other choice select
  1067.                 /* if ($rdv->getIdEtat()->getId() != 5) {
  1068.                     continue;
  1069.                 }*/
  1070.                 /** @var AudioMotif */
  1071.                 $audioMotif $this->getDoctrine()
  1072.                     ->getRepository(AudioMotif::class)
  1073.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  1074.                 if (!$audioMotif) {
  1075.                     continue;
  1076.                 }
  1077.                 $duration '';
  1078.                 if (is_null($rdv->getDuration())) {
  1079.                     $duration $audioMotif->getDuration();
  1080.                 } else {
  1081.                     $duration $rdv->getDuration();
  1082.                 }
  1083.                 $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  1084.                 /** @var Rdv[] */
  1085.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  1086.                     ->findAllReviewsCentre($rdvCentre->getId());
  1087.                 $rdvItem = [
  1088.                     "id" => $rdv->getId(),
  1089.                     "motif_id" => $rdv->getIdMotif()->getId(),
  1090.                     "duration" => $duration,
  1091.                     "color" => $audioMotif->getColor(),
  1092.                     "audio_id" => $rdv->getIdAudio()->getId(),
  1093.                     "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  1094.                     "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  1095.                     "client_id" => $rdv->getIdClient()->getId(),
  1096.                     "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  1097.                     "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  1098.                     "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  1099.                     "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  1100.                     "testclient" => $rdv->getTestClient() ? [
  1101.                         "result" => $rdv->getTestClient()->getResultTonal(),
  1102.                         "date" => $rdv->getTestClient()->getDate(),
  1103.                         "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  1104.                     ] : null,
  1105.                     "name" => $rdvCentre->getName(),
  1106.                     "phone" => $rdvCentre->getPhone(),
  1107.                     "imgUrl" => $rdvCentre->getImgUrl(),
  1108.                     "address" => $rdvCentre->getAddress(),
  1109.                     "postale" => $rdvCentre->getPostale(),
  1110.                     "city" => $rdvCentre->getCity(),
  1111.                     "etat_id" => $rdvCentre->getId(),
  1112.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  1113.                     "nbrReview" => count($centreRdvs),
  1114.                     "acceptedCurrency" => "CB Chèque",
  1115.                     "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  1116.                     "note" => $rdv->getNote(),
  1117.                     "comment" => $rdv->getComment(),
  1118.                     "review" => $rdv->getReview(),
  1119.                     "status" => $rdv->getIdEtat()->getLibelle()
  1120.                 ];
  1121.                 $rdvResult->add($rdvItem);
  1122.             }
  1123.         }
  1124.         if (count($rdvResult) > 0) {
  1125.             return new Response(json_encode(([
  1126.                 "rdv" => $rdvResult->toArray(),
  1127.                 "status" => 200,
  1128.             ])));
  1129.         } else {
  1130.             return new Response(json_encode(([
  1131.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  1132.                 'path' => 'src/Controller/RdvController.php',
  1133.                 "status" => 404,
  1134.             ])));
  1135.         }
  1136.     }
  1137.     private function getOpeningHours($centerId)
  1138.     {
  1139.         $center $this->getDoctrine()->getRepository(Centre::class)->find($centerId);
  1140.         $audioCentre $this->getDoctrine()->getRepository(AudioCentre::class)
  1141.             ->findOneBy(['id_centre' => $center->getId(), 'id_audio' => $center->getIdGerant()->getId()]);
  1142.         $schedule $audioCentre->getHoraire();
  1143.         $availableHours = [];
  1144.         if (isset($schedule['fixed'])) {
  1145.             foreach ($schedule['fixed'] as $day => $hours) {
  1146.                 $dayInFrench strtolower($day);
  1147.                 $slots = [];
  1148.                 foreach ($hours as $period) {
  1149.                     $start strtotime($period['open']);
  1150.                     $end strtotime($period['close']);
  1151.                     while ($start $end) {
  1152.                         $slots[] = date('H:i'$start);
  1153.                         $start strtotime('+30 minutes'$start);
  1154.                     }
  1155.                 }
  1156.                 $availableHours[$dayInFrench] = $slots;
  1157.             }
  1158.         }
  1159.         if (isset($schedule['exceptionalOpened'])) {
  1160.             foreach ($schedule['exceptionalOpened'] as $exception) {
  1161.                 $dayOfWeek strtolower(date('l'strtotime($exception['open'])));
  1162.                 $start strtotime($exception['open']);
  1163.                 $end strtotime($exception['close']);
  1164.                 $exceptionSlots = [];
  1165.                 while ($start $end) {
  1166.                     $exceptionSlots[] = date('H:i'$start);
  1167.                     $start strtotime('+30 minutes'$start);
  1168.                 }
  1169.                 $availableHours[$dayOfWeek] = array_merge(
  1170.                     $availableHours[$dayOfWeek] ?? [],
  1171.                     $exceptionSlots
  1172.                 );
  1173.             }
  1174.         }
  1175.         if (isset($schedule['exceptionalClosed'])) {
  1176.             foreach ($schedule['exceptionalClosed'] as $exception) {
  1177.                 $dayOfWeek strtolower(date('l'strtotime($exception['open'])));
  1178.                 unset($availableHours[$dayOfWeek]);
  1179.             }
  1180.         }
  1181.         return $availableHours;
  1182.     }
  1183.     private function getBookedSlotsForDate($centerId$date)
  1184.     {
  1185.         $bookedSlots $this->getDoctrine()
  1186.             ->getRepository(Rdv::class)
  1187.             ->getBookedSlotsForDate($centerId$date);
  1188.         return $bookedSlots;
  1189.     }
  1190.     private function getAvailableSlotsForDate($openingHours$centerId$date)
  1191.     {
  1192.         $dayOfWeek date('l'strtotime($date));
  1193.         $dayInFrench $this->convertDayToFrench($dayOfWeek);
  1194.         if (!$dayInFrench) {
  1195.             throw new \Exception("Invalid day of the week: $dayOfWeek");
  1196.         }
  1197.         $slots $openingHours[$dayInFrench] ?? [];
  1198.         $bookedSlots $this->getBookedSlotsForDate($centerId$date);
  1199.         $bookedTimes = [];
  1200.         foreach ($bookedSlots as $bookedSlot) {
  1201.             $startTime $bookedSlot['date'];
  1202.             $duration $bookedSlot['duration'];
  1203.             $endTime = (clone $startTime)->modify("+$duration minutes");
  1204.             $bookedTimes[] = ['start' => $startTime'end' => $endTime];
  1205.         }
  1206.         $availableSlots = [];
  1207.         foreach ($slots as $slot) {
  1208.             $slotTime \DateTime::createFromFormat('H:i'$slot);
  1209.             $slotTime->setDate(date('Y'strtotime($date)), date('m'strtotime($date)), date('d'strtotime($date)));
  1210.             if (!$slotTime) {
  1211.                 continue;
  1212.             }
  1213.             $isAvailable true;
  1214.             foreach ($bookedTimes as $bookedTime) {
  1215.                 if ($slotTime >= $bookedTime['start'] && $slotTime $bookedTime['end']) {
  1216.                     $isAvailable false;
  1217.                     break;
  1218.                 }
  1219.             }
  1220.             if ($isAvailable) {
  1221.                 $availableSlots[] = $slot;
  1222.             }
  1223.         }
  1224.         return $availableSlots;
  1225.     }
  1226.     private function convertDayToFrench($englishDay)
  1227.     {
  1228.         $daysMap = [
  1229.             'monday' => 'lundi',
  1230.             'tuesday' => 'mardi',
  1231.             'wednesday' => 'mercredi',
  1232.             'thursday' => 'jeudi',
  1233.             'friday' => 'vendredi',
  1234.             'saturday' => 'samedi',
  1235.             'sunday' => 'dimanche'
  1236.         ];
  1237.         return $daysMap[strtolower($englishDay)] ?? null;
  1238.     }
  1239.     /**
  1240.      * @Route("/audio/{id}/rdvs/", name="getAudioRdvs", methods={"GET","HEAD"})
  1241.      */
  1242.     public function getAudioRdvs(Request $requestAudio $audio)
  1243.     {
  1244.         if (!$request->query->get('token')) {
  1245.             return new Response(json_encode([
  1246.                 "message" => "Pas de token n'a été spécifié",
  1247.                 "status" => 401,
  1248.             ]), 401);
  1249.         }
  1250.         $entityManager $this->getDoctrine()->getManager();
  1251.         /** @var Token */
  1252.         $token $this->getDoctrine()
  1253.             ->getRepository(Token::class)
  1254.             ->findOneBy(['token' => $request->query->get('token')]);
  1255.         if (!$token) {
  1256.             return new Response(json_encode([
  1257.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1258.                 "status" => 404,
  1259.             ]), 404);
  1260.         }
  1261.         // get token age
  1262.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1263.         // if the token if older than 7 days
  1264.         if ($dateDiff->7) {
  1265.             $entityManager->remove($token);
  1266.             $entityManager->flush();
  1267.             return $this->json([
  1268.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1269.                 'path' => 'src/Controller/ClientController.php',
  1270.                 "status" => 401,
  1271.             ], 401);
  1272.         }
  1273.         if ($audio != $token->getIdAudio()) {
  1274.             return new Response(json_encode([
  1275.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1276.                 "status" => 404,
  1277.             ]), 404);
  1278.         }
  1279.         $centre = (int)$request->query->get('centre');
  1280.         if (($request->query->get('debut')) && ($request->query->get('fin'))) {
  1281.             $rdvs $this->getDoctrine()
  1282.                 ->getRepository(Rdv::class)
  1283.                 ->findBetweenDate(
  1284.                     $audio->getId(),
  1285.                     new DateTime($request->query->get('debut')),
  1286.                     new DateTime($request->query->get('fin')),
  1287.                     $centre // Le centre est maintenant un entier
  1288.                 );
  1289.         } else {
  1290.             $rdvs $this->getDoctrine()
  1291.                 ->getRepository(Rdv::class)
  1292.                 ->findBy(['id_audio' => $audio->getId()]);
  1293.         }
  1294.         $rdvResult = new ArrayCollection();
  1295.         $centerId $request->query->get('centre');
  1296.         // $openingHours = $this->getOpeningHours($centerId); 
  1297.         $centerId $request->query->get('centre');
  1298.         $dateCache = new \DateTime();
  1299.         $openingHours $this->cache->get('centre_' $centerId '_horaires_' $dateCache->format('Y-m-d'), function (ItemInterface $item) use ($centerId$dateCache) {
  1300.             $item->expiresAfter(7200);
  1301.             return $this->getOpeningHours($centerId);
  1302.         });
  1303.         //dd($openingHours);
  1304.         foreach ($rdvs as $rdv) {
  1305.             if ($rdv->getIdEtat()->getId() != null) {
  1306.                 if ($rdv->getIsAbsence() != 1) {
  1307.                     /** @var AudioMotif */
  1308.                     $audioMotif $this->getDoctrine()
  1309.                         ->getRepository(AudioMotif::class)
  1310.                         ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $audio->getId()]);
  1311.                     if (!isset($audioMotif)) {
  1312.                         continue;
  1313.                     }
  1314.                     $motif $this->getDoctrine()
  1315.                         ->getRepository(Motif::class)
  1316.                         ->findOneBy(['id' => $rdv->getIdMotif()->getId()]);
  1317.                     $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  1318.                     if ($rdv->getIdClientTemp()) {
  1319.                         $confiance "";
  1320.                     } else {
  1321.                         $confiance $client->getIdPersonneConfiance() ? $client->getIdPersonneConfiance()->getId() : null;
  1322.                     }
  1323.                 }
  1324.                 $duration '';
  1325.                 if (is_null($rdv->getDuration())) {
  1326.                     $duration $audioMotif->getDuration();
  1327.                 } else {
  1328.                     $duration $rdv->getDuration();
  1329.                 }
  1330.                 $dateFin = new DateTime($rdv->getDate()->format('Y-m-d\TH:i:s'));
  1331.                 $dateFin $dateFin->add(new DateInterval("PT" $duration "M"));
  1332.                 if ($rdv->getIdClientTemp()) {
  1333.                     $findNextRdv $this->getDoctrine()
  1334.                         ->getRepository(Rdv::class)
  1335.                         ->findBy([
  1336.                             "id_client_temp" => $rdv->getIdClientTemp(),
  1337.                             "id_motif" => ['106''107''108''109']
  1338.                         ]);
  1339.                 } else {
  1340.                     $findNextRdv $this->getDoctrine()
  1341.                         ->getRepository(Rdv::class)
  1342.                         ->findBy([
  1343.                             "id_client_temp" => $rdv->getIdClient(),
  1344.                             "id_motif" => ['106''107''108''109']
  1345.                         ]);
  1346.                 }
  1347.                 $finalRdv null;
  1348.                 /*if ($rdv->getRdvParent()) {
  1349.     $finalRdv = $this->getDoctrine()
  1350.         ->getRepository(Rdv::class)
  1351.         ->find($rdv->getRdvParent());
  1352. }*/
  1353.                 //if($client->getClientDevices())
  1354.                 //{
  1355.                 //if ($client->getClientDevices()->first()) {
  1356.                 /*$nextRdv = $this->getDoctrine()
  1357.                  ->getRepository(Rdv::class)
  1358.                  ->find($finalRdv->getClientDevice()->getRdv()->getId());*/
  1359.                 //  }
  1360.                 //}
  1361.                 if ($rdv->getIsAbsence() != 1) {
  1362.                     if ($rdv->getIdClientTemp()) {
  1363.                         $nextRdvs $this->getDoctrine()
  1364.                             ->getRepository(Rdv::class)
  1365.                             ->findBy([
  1366.                                 "id_client_temp" => $client,
  1367.                                 "id_motif" => ['106''107''108''109']
  1368.                             ]);
  1369.                     } else {
  1370.                         $nextRdvs $this->getDoctrine()
  1371.                             ->getRepository(Rdv::class)
  1372.                             ->findBy([
  1373.                                 "id_client" => $client,
  1374.                                 "id_motif" => ['106''107''108''109']
  1375.                             ]);
  1376.                     }
  1377.                     if ($client->getClientDevices()) {
  1378.                         if ($client->getClientDevices()->first()) {
  1379.                             if (empty($nextRdvs)) {
  1380.                                 $isNextRdv false;
  1381.                                 $initialRdvDate $rdv->getDate();
  1382.                                 $availableSlots = [
  1383.                                     'Suivi de l’essai' => $this->findFirstAvailableSlot($centerId$initialRdvDate7),
  1384.                                     'Confirmation de l’essai' => $this->findFirstAvailableSlot($centerId$initialRdvDate14),
  1385.                                     'Validation de l’appareillage' => $this->findFirstAvailableSlot($centerId$initialRdvDate21),
  1386.                                     'Facturation de l’appareillage' => $this->findFirstAvailableSlot($centerId$initialRdvDate30),
  1387.                                     'duration' => "30"
  1388.                                 ];
  1389.                                 $mappedNextRdvs = [
  1390.                                     'Suivi de l’essai' => $this->findAvailableDay($centerId$initialRdvDate7),
  1391.                                     'Confirmation de l’essai' => $this->findAvailableDay($centerId$initialRdvDate14),
  1392.                                     'Validation de l’appareillage' => $this->findAvailableDay($centerId$initialRdvDate21),
  1393.                                     'Facturation de l’appareillage' => $this->findAvailableDay($centerId$initialRdvDate30),
  1394.                                     'duration' => "30"
  1395.                                 ];
  1396.                             } else {
  1397.                                 $isNextRdv true;
  1398.                                 $initialRdvDate $rdv->getDate();
  1399.                                 // Available slots for each follow-up date
  1400.                                 $availableSlots = [];
  1401.                                 if (isset($nextRdvs[0])) {
  1402.                                     $availableSlots['Suivi de l’essai'] = $this->getAvailableSlotsForDate(
  1403.                                         $openingHours,
  1404.                                         $centerId,
  1405.                                         $nextRdvs[0]->getDate()->format('Y-m-d')
  1406.                                     );
  1407.                                 }
  1408.                                 if (isset($nextRdvs[1])) {
  1409.                                     $availableSlots['Confirmation de l’essai'] = $this->getAvailableSlotsForDate(
  1410.                                         $openingHours,
  1411.                                         $centerId,
  1412.                                         $nextRdvs[1]->getDate()->format('Y-m-d')
  1413.                                     );
  1414.                                 }
  1415.                                 if (isset($nextRdvs[2])) {
  1416.                                     $availableSlots['Validation de l’appareillage'] = $this->getAvailableSlotsForDate(
  1417.                                         $openingHours,
  1418.                                         $centerId,
  1419.                                         $nextRdvs[2]->getDate()->format('Y-m-d')
  1420.                                     );
  1421.                                 }
  1422.                                 if (isset($nextRdvs[3])) {
  1423.                                     $availableSlots['Facturation de l’appareillage'] = $this->getAvailableSlotsForDate(
  1424.                                         $openingHours,
  1425.                                         $centerId,
  1426.                                         $nextRdvs[3]->getDate()->format('Y-m-d')
  1427.                                     );
  1428.                                 }
  1429.                                 $mappedNextRdvs array_map(function ($rdv) {
  1430.                                     return [
  1431.                                         'id' => $rdv->getId(),
  1432.                                         'date' => $rdv->getDate()->format('d-m-Y'),
  1433.                                         'hours' => $rdv->getDate()->format('H:i'),
  1434.                                         'duration' => $rdv->getDuration(),
  1435.                                         "motif_id" => $rdv->getIdMotif()->getId(),
  1436.                                         "motif_titre" => $rdv->getIdMotif()->getTitre(),
  1437.                                     ];
  1438.                                 }, $nextRdvs);
  1439.                             }
  1440.                         }
  1441.                     }
  1442.                     $rdvItem = [
  1443.                         "id" => $rdv->getId(),
  1444.                         "motif_id" => $rdv->getIdMotif()->getId(),
  1445.                         "motif_titre" => $motif->getTitre(),
  1446.                         "duration" => $duration,
  1447.                         "color" => $audioMotif->getColor(),
  1448.                         "audio_id" => $rdv->getIdAudio()->getId(),
  1449.                         "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  1450.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  1451.                         "client_id" => $client->getId(),
  1452.                         "isClient" => ($client instanceof Client) ? 0,
  1453.                         "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() : $client->getName(),
  1454.                         "client_lastname" => $rdv->getIdProche() ? $rdv->getIdProche()->getLastname() : $client->getLastname(),
  1455.                         "client_mail" => $client->getMail(),
  1456.                         "client_tel" => $client->getPhone(),
  1457.                         "client_fixe" => $client->getPhoneFixe(),
  1458.                         "confiance" =>  $confiance,
  1459.                         "client_birthday" => $client->getBirthdate() ? $client->getBirthdate()->format("Y-m-d") : null,
  1460.                         "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  1461.                         "centre_id" => $rdv->getIdCentre()->getId(),
  1462.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  1463.                         "testclient" => $rdv->getTestClient() ? [
  1464.                             "result" => $rdv->getTestClient()->getResultTonal(),
  1465.                             "date" => $rdv->getTestClient()->getDate(),
  1466.                             "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  1467.                         ] : null,
  1468.                         "name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : $rdv->getIdLieu()->getName(),
  1469.                         "centerName" => $rdv->getIdCentre()->getName(),
  1470.                         "phone" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getPhone() : $rdv->getIdLieu()->getPhone(),
  1471.                         "etat_id" => $rdv->getIdEtat()->getId(),
  1472.                         "clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
  1473.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  1474.                         "dateFin" => $dateFin->format('Y-m-d\TH:i:s'),
  1475.                         "comment" => $rdv->getComment(),
  1476.                         "note" => $rdv->getNote(),
  1477.                         "isTemp" => $rdv->getIdClientTemp() ? 0,
  1478.                         "isAbsence" => $rdv->getIsAbsence(),
  1479.                         "device" => $client->getClientDevices()->first() ? [
  1480.                             "isDevice" => true,
  1481.                             "isNextRdv" => $isNextRdv,
  1482.                             "deviceID" => $client->getClientDevices()->first()->getDevice()->getId(),
  1483.                             "clientDeviceID" => $client->getClientDevices()->first()->getId(),
  1484.                             "deviceModel" => $client->getClientDevices()->first()->getDevice()->getModel(),
  1485.                             "settingDeviceId" => $client->getClientDevices()->first()->getSettingDevice()->getSlug(),
  1486.                             "settingName" => $client->getClientDevices()->first()->getSettingDevice()->getName(),
  1487.                             "settingSlug" => $client->getClientDevices()->first()->getSettingDevice()->getSlug(),
  1488.                             "nextRdvs" => $mappedNextRdvs,
  1489.                             "available_slots" => $availableSlots
  1490.                         ] : [
  1491.                             "isDevice" => false
  1492.                         ]
  1493.                     ];
  1494.                 } else {
  1495.                     // $clientDevice = $client->getClientDevices()->first();
  1496.                     $rdvItem = [
  1497.                         "id" => $rdv->getId(),
  1498.                         "duration" => $duration,
  1499.                         "color" => $rdv->getColor() ? $rdv->getColor() . '66' '#ffb2b266',
  1500.                         "audio_id" => $rdv->getIdAudio()->getId(),
  1501.                         "client_id" =>  "",
  1502.                         "isClient" => false,
  1503.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  1504.                         "centre_id" => $rdv->getIdCentre()->getId(),
  1505.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  1506.                         "name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : $rdv->getIdLieu()->getName(),
  1507.                         "phone" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getPhone() : $rdv->getIdLieu()->getPhone(),
  1508.                         "etat_id" => $rdv->getIdEtat()->getId(),
  1509.                         "clientEtatId" => "",
  1510.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  1511.                         "dateFin" => $dateFin->format('Y-m-d\TH:i:s'),
  1512.                         "note" => $rdv->getNote(),
  1513.                         "device" => "",
  1514.                         "centerName" => $rdv->getIdCentre()->getName(),
  1515.                         "isTemp" => $rdv->getIdClientTemp() ? 0,
  1516.                         "isAbsence" => $rdv->getIsAbsence(),
  1517.                         "motif_titre" => $rdv->getMotifAbsence() ? $rdv->getMotifAbsence() : "Absence",
  1518.                     ];
  1519.                 }
  1520.                 //  if ($rdv->getDate() >= new DateTime())
  1521.                 $rdvResult->add($rdvItem);
  1522.             }
  1523.         }
  1524.         $startDate = new \DateTime('2024-02-20');
  1525.         $rdvs $this->rdvRepo->findRdvsNeedingReminderByAudio($startDate$audio->getId());
  1526.         //dd($audio->getId());
  1527.         $reminders = [];
  1528.         //dd($rdvs);
  1529.         foreach ($rdvs as $rdv) {
  1530.             $info $this->checkRdvReminder($rdv);
  1531.             if ($info !== null) {
  1532.                 $reminders[] = $info;
  1533.             }
  1534.         }
  1535.         //dd($reminders);
  1536.         if (count($rdvResult) > 0) {
  1537.             return new Response(json_encode(([
  1538.                 "content" => $rdvResult->toArray(),
  1539.                 "status" => 200,
  1540.                 "reminders" => $reminders,
  1541.                 "datefin" => $dateFin
  1542.             ])));
  1543.         } else {
  1544.             $rdvItem = [];
  1545.             //$rdvResult->add($rdvItem);
  1546.             return new Response(json_encode(([
  1547.                 "content" => $rdvResult->toArray(),
  1548.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  1549.                 'path' => 'src/Controller/RdvController.php',
  1550.                 "reminders" => $reminders,
  1551.                 "status" => 404,
  1552.             ])));
  1553.         }
  1554.     }
  1555.     private function findAvailableDay(int $centerId\DateTime $initialRdvDateint $offset): string
  1556.     {
  1557.         $currentDate = (clone $initialRdvDate)->modify("+{$offset} days");
  1558.         while (true) {
  1559.             $formattedDate $currentDate->format('Y-m-d');
  1560.             $slots $this->getAvailableSlotsForDate(
  1561.                 $this->getOpeningHoursList($centerId$formattedDate),
  1562.                 $centerId,
  1563.                 $formattedDate
  1564.             );
  1565.             if (!empty($slots)) {
  1566.                 return $formattedDate;
  1567.             }
  1568.             $currentDate->modify('+1 day');
  1569.         }
  1570.     }
  1571.     private function findFirstAvailableSlot(int $centerId\DateTime $initialRdvDateint $offset): array
  1572.     {
  1573.         $currentDate = (clone $initialRdvDate)->modify("+{$offset} days");
  1574.         while (true) {
  1575.             $formattedDate $currentDate->format('Y-m-d');
  1576.             $slots $this->getAvailableSlotsForDate(
  1577.                 $this->getOpeningHoursList($centerId$formattedDate),
  1578.                 $centerId,
  1579.                 $formattedDate
  1580.             );
  1581.             if (!empty($slots)) {
  1582.                 return $slots;
  1583.             }
  1584.             $currentDate->modify('+1 day');
  1585.         }
  1586.     }
  1587.     private function getOpeningHoursList($centerId$date)
  1588.     {
  1589.         $center $this->getDoctrine()->getRepository(Centre::class)->find($centerId);
  1590.         $audioCentre $this->getDoctrine()->getRepository(AudioCentre::class)
  1591.             ->findOneBy(['id_centre' => $center->getId(), 'id_audio' => $center->getIdGerant()->getId()]);
  1592.         $schedule $audioCentre->getHoraire();
  1593.         $availableHours = [];
  1594.         $holidayDates = [
  1595.             'JourdelAn' => '01-01',
  1596.             'LundidePâques' => '21-04',
  1597.             'FêteduTravail' => '01-05',
  1598.             'Victoire1945' => '08-05',
  1599.             'Ascension' => '29-05',
  1600.             'LundidePentecôte' => '09-06',
  1601.             'FêteNationale' => '14-07',
  1602.             'Assomption' => '15-08',
  1603.             'Toussaint' => '01-11',
  1604.             'Armistice1918' => '11-11',
  1605.             'Noël' => '25-12',
  1606.         ];
  1607.         $holidays $center->getHorairesHoliday();
  1608.         $requestDate date('d-m'strtotime($date));
  1609.         $englishToFrenchDays = [
  1610.             'monday' => 'lundi',
  1611.             'tuesday' => 'mardi',
  1612.             'wednesday' => 'mercredi',
  1613.             'thursday' => 'jeudi',
  1614.             'friday' => 'vendredi',
  1615.             'saturday' => 'samedi',
  1616.             'sunday' => 'dimanche',
  1617.         ];
  1618.         $dayOfWeek strtolower(date('l'strtotime($date)));
  1619.         $dayInFrench $englishToFrenchDays[$dayOfWeek];
  1620.         if (isset($schedule['fixed'])) {
  1621.             foreach ($schedule['fixed'] as $day => $hours) {
  1622.                 $dayKey strtolower($day);
  1623.                 $slots = [];
  1624.                 foreach ($hours as $period) {
  1625.                     $start strtotime($period['open']);
  1626.                     $end strtotime($period['close']);
  1627.                     while ($start $end) {
  1628.                         $slots[] = date('H:i'$start);
  1629.                         $start strtotime('+30 minutes'$start);
  1630.                     }
  1631.                 }
  1632.                 $availableHours[$dayKey] = $slots;
  1633.             }
  1634.         }
  1635.         foreach ($holidays['fixed'] as $holiday => $hours) {
  1636.             if (isset($holidayDates[$holiday]) && $holidayDates[$holiday] === $requestDate) {
  1637.                 $holidaySlots = [];
  1638.                 if (!empty($hours)) {
  1639.                     foreach ($hours as $period) {
  1640.                         $start strtotime($period['open']);
  1641.                         $end strtotime($period['close']);
  1642.                         while ($start $end) {
  1643.                             $holidaySlots[] = date('H:i'$start);
  1644.                             $start strtotime('+30 minutes'$start);
  1645.                         }
  1646.                     }
  1647.                     $availableHours[$dayInFrench] = $holidaySlots;
  1648.                 } else {
  1649.                     $availableHours[$dayInFrench] = [];
  1650.                 }
  1651.                 break;
  1652.             }
  1653.         }
  1654.         return $availableHours;
  1655.     }
  1656.     /**
  1657.      * @Route("/audio/{id}/rdvsTest/", name="getAudioRdvsTest", methods={"GET","HEAD"})
  1658.      */
  1659.     public function getAudioRdvsTest(Request $requestAudio $audio)
  1660.     {
  1661.         if (!$request->query->get('token')) {
  1662.             return new Response(json_encode([
  1663.                 "message" => "Pas de token n'a été spécifié",
  1664.                 "status" => 401,
  1665.             ]), 401);
  1666.         }
  1667.         $entityManager $this->getDoctrine()->getManager();
  1668.         /** @var Token */
  1669.         $token $this->getDoctrine()
  1670.             ->getRepository(Token::class)
  1671.             ->findOneBy(['token' => $request->query->get('token')]);
  1672.         if (!$token) {
  1673.             return new Response(json_encode([
  1674.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1675.                 "status" => 404,
  1676.             ]), 404);
  1677.         }
  1678.         // get token age
  1679.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1680.         // if the token if older than 7 days
  1681.         if ($dateDiff->7) {
  1682.             $entityManager->remove($token);
  1683.             $entityManager->flush();
  1684.             return $this->json([
  1685.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1686.                 'path' => 'src/Controller/ClientController.php',
  1687.                 "status" => 401,
  1688.             ], 401);
  1689.         }
  1690.         if ($audio != $token->getIdAudio()) {
  1691.             return new Response(json_encode([
  1692.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1693.                 "status" => 404,
  1694.             ]), 404);
  1695.         }
  1696.         /** @var Rdv[] */
  1697.         if (($request->query->get('debut')) && ($request->query->get('fin'))) {
  1698.             $rdvs $this->getDoctrine()
  1699.                 ->getRepository(Rdv::class)
  1700.                 ->findBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1701.         } else {
  1702.             $rdvs $this->getDoctrine()
  1703.                 ->getRepository(Rdv::class)
  1704.                 ->findBy(['id_audio' => $audio->getId()]);
  1705.         }
  1706.         $rdvResult = new ArrayCollection();
  1707.         foreach ($rdvs as $rdv) {
  1708.             if ($rdv->getIdEtat()->getId() != null) {
  1709.                 /** @var AudioMotif */
  1710.                 $audioMotif $this->getDoctrine()
  1711.                     ->getRepository(AudioMotif::class)
  1712.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $audio->getId()]);
  1713.                 if (!isset($audioMotif)) {
  1714.                     continue;
  1715.                 }
  1716.                 $motif $this->getDoctrine()
  1717.                     ->getRepository(Motif::class)
  1718.                     ->findOneBy(['id' => $rdv->getIdMotif()->getId()]);
  1719.                 $dateFin = new DateTime($rdv->getDate()->format('Y-m-d H:i:s'));
  1720.                 $dateFin $dateFin->add(new DateInterval("PT" $audioMotif->getDuration() . "M"));
  1721.                 $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  1722.                 $name $rdv->getIdProche() ? $rdv->getIdProche()->getName() : $client->getName();
  1723.                 $lastName $rdv->getIdProche() ? $rdv->getIdProche()->getLastname() : $client->getLastname();
  1724.                 $rdvItem = [
  1725.                     "id" => $rdv->getId(),
  1726.                     "title" => $lastName ' ' $name,
  1727.                     "start" => $rdv->getDate()->format('Y-m-d H:i:s'),
  1728.                     "end"   => $dateFin->format('Y-m-d H:i:s'),
  1729.                     "backgroundColor" => $audioMotif->getColor(),
  1730.                     "editable" => true,
  1731.                     "durationEditable" => false,
  1732.                     "resourceEditable" => true,
  1733.                     "cache" => false,
  1734.                     "motif_id" => $rdv->getIdMotif()->getId(),
  1735.                     "motif" => $motif->getTitre(),
  1736.                     "duree" => $audioMotif->getDuration(),
  1737.                     "color" => $audioMotif->getColor(),
  1738.                     "color_motif" => $audioMotif->getColor(),
  1739.                     "client_id" => $client->getId(),
  1740.                     "clientName" => $name,
  1741.                     "clientLastName" => $lastName,
  1742.                     "mail" => $client->getMail(),
  1743.                     "telephone" => $client->getPhone(),
  1744.                     "birthday" => $client->getBirthdate(),
  1745.                     "etat_id" => $rdv->getIdEtat()->getId(),
  1746.                     "dateDeb" => $rdv->getDate()->format('Y-m-d H:i:s'),
  1747.                     "dateFin" => $dateFin->format('Y-m-d H:i:s'),
  1748.                     "commentaire" => $rdv->getNote(),
  1749.                     "event_title" => "<b>" $lastName "</b> " $name,
  1750.                 ];
  1751.                 //  if ($rdv->getDate() >= new DateTime())
  1752.                 $rdvResult->add($rdvItem);
  1753.             }
  1754.         }
  1755.         if (count($rdvResult) > 0) {
  1756.             return new Response(json_encode(
  1757.                 $rdvResult->toArray(),
  1758.             ));
  1759.         } else {
  1760.             $rdvItem = [];
  1761.             //$rdvResult->add($rdvItem);
  1762.             return new Response(json_encode(
  1763.                 $rdvResult->toArray(),
  1764.             ));
  1765.         }
  1766.     }
  1767.     /**
  1768.      * @Route("/audio/{id}/rdvs/count", name="getCountAudioRdvs", methods={"GET","HEAD"})
  1769.      */
  1770.     public function getCountAudioRdvs(Request $requestAudio $audio)
  1771.     {
  1772.         if (!$request->query->get('token')) {
  1773.             return new Response(json_encode([
  1774.                 "message" => "Pas de token n'a été spécifié",
  1775.                 "status" => 401,
  1776.             ]), 401);
  1777.         }
  1778.         $entityManager $this->getDoctrine()->getManager();
  1779.         /** @var Token */
  1780.         $token $this->getDoctrine()
  1781.             ->getRepository(Token::class)
  1782.             ->findOneBy(['token' => $request->query->get('token')]);
  1783.         if (!$token) {
  1784.             return new Response(json_encode([
  1785.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1786.                 "status" => 404,
  1787.             ]), 404);
  1788.         }
  1789.         // get token age
  1790.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1791.         // if the token if older than 7 days
  1792.         if ($dateDiff->7) {
  1793.             $entityManager->remove($token);
  1794.             $entityManager->flush();
  1795.             return $this->json([
  1796.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1797.                 'path' => 'src/Controller/ClientController.php',
  1798.                 "status" => 401,
  1799.             ], 401);
  1800.         }
  1801.         if ($audio != $token->getIdAudio()) {
  1802.             return new Response(json_encode([
  1803.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1804.                 "status" => 404,
  1805.             ]), 404);
  1806.         }
  1807.         /** @var Rdv[] */
  1808.         $rdvs $this->getDoctrine()
  1809.             ->getRepository(Rdv::class)
  1810.             ->findBy(['id_audio' => $audio->getId()]);
  1811.         return new Response(json_encode(([
  1812.             "content" => count($rdvs),
  1813.             "status" => 200,
  1814.         ])));
  1815.     }
  1816.     /**
  1817.      * @Route("/audio/{id}/rdvsDate/count", name="getCountAudioRdvsBetweenDate", methods={"GET","HEAD"})
  1818.      */
  1819.     public function getCountAudioRdvsBetweenDate(Request $requestAudio $audio)
  1820.     {
  1821.         if (!$request->query->get('token')) {
  1822.             return new Response(json_encode([
  1823.                 "message" => "Pas de token n'a été spécifié",
  1824.                 "status" => 401,
  1825.             ]), 401);
  1826.         }
  1827.         $entityManager $this->getDoctrine()->getManager();
  1828.         /** @var Token */
  1829.         $token $this->getDoctrine()
  1830.             ->getRepository(Token::class)
  1831.             ->findOneBy(['token' => $request->query->get('token')]);
  1832.         if (!$token) {
  1833.             return new Response(json_encode([
  1834.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1835.                 "status" => 404,
  1836.             ]), 404);
  1837.         }
  1838.         // get token age
  1839.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1840.         // if the token if older than 7 days
  1841.         if ($dateDiff->7) {
  1842.             $entityManager->remove($token);
  1843.             $entityManager->flush();
  1844.             return $this->json([
  1845.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1846.                 'path' => 'src/Controller/ClientController.php',
  1847.                 "status" => 401,
  1848.             ], 401);
  1849.         }
  1850.         if ($audio != $token->getIdAudio()) {
  1851.             return new Response(json_encode([
  1852.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1853.                 "status" => 404,
  1854.             ]), 404);
  1855.         }
  1856.         /** @var Rdv[] */
  1857.         $allRdvs $this->getDoctrine()
  1858.             ->getRepository(Rdv::class)
  1859.             ->findOnlyRdvAudioBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1860.         /** @var Rdv[] */
  1861.         $rdvs $this->getDoctrine()
  1862.             ->getRepository(Rdv::class)
  1863.             ->findOnlyRdvAudioWithoutTestBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1864.         /** @var Rdv[] */
  1865.         $rdvsWithTest $this->getDoctrine()
  1866.             ->getRepository(Rdv::class)
  1867.             ->findOnlyRdvAudioWithTestBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1868.         /** @var Rdv[] */
  1869.         $allRdvsCanceled $this->getDoctrine()
  1870.             ->getRepository(Rdv::class)
  1871.             ->findCanceledRdvAudioBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1872.         /** @var Rdv[] */
  1873.         $allRdvsCanceledCentre $this->getDoctrine()
  1874.             ->getRepository(Rdv::class)
  1875.             ->findCanceledRdvCentreBetweenDate(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1876.         /** @var Rdv[] */
  1877.         $rdvsClosed $this->getDoctrine()
  1878.             ->getRepository(Rdv::class)
  1879.             ->findClosedRdvBetweenDate(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1880.         $myLead 0;
  1881.         $rdvsCanceled $this->getDoctrine()
  1882.             ->getRepository(Rdv::class)
  1883.             ->findCanceledRdvAudioBetweenDateWithoutTest($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1884.         foreach ($rdvsCanceled as $rdvc) {
  1885.             if (!is_null($rdvc->getIdClient())) {
  1886.                 $rdvClient $this->getDoctrine()
  1887.                     ->getRepository(Rdv::class)
  1888.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1889.                 if (count($rdvClient) == 0) {
  1890.                     $myLead $myLead 1;
  1891.                 }
  1892.             }
  1893.         }
  1894.         $myLeadAdvanced 0;
  1895.         $rdvsCanceledA $this->getDoctrine()
  1896.             ->getRepository(Rdv::class)
  1897.             ->findCanceledRdvAudioBetweenDateWithTest($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1898.         foreach ($rdvsCanceledA as $rdvc) {
  1899.             if (!is_null($rdvc->getIdClient())) {
  1900.                 $rdvClient $this->getDoctrine()
  1901.                     ->getRepository(Rdv::class)
  1902.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1903.                 if (count($rdvClient) == 0) {
  1904.                     $myLeadAdvanced $myLeadAdvanced 1;
  1905.                 }
  1906.             }
  1907.         }
  1908.         /**** MY RDV Centre****/
  1909.         $myrdvCentre 0;
  1910.         $rdvs $this->getDoctrine()
  1911.             ->getRepository(Rdv::class)
  1912.             ->findRDVCentreBetweenDateWithoutTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1913.         $myrdvCentre count($rdvs);
  1914.         /**** MY RDV ADVANCED ****/
  1915.         $myRdvAdvancedCentre 0;
  1916.         $rdvsA $this->getDoctrine()
  1917.             ->getRepository(Rdv::class)
  1918.             ->findRDVCentreBetweenDateWithTestId(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1919.         $myRdvAdvancedCentre count($rdvsA);
  1920.         /**** FIRST RDV BY MOTIF PREMIER RDV ****/
  1921.         $myFirstRdv 0;
  1922.         $rdvsFirst $this->getDoctrine()
  1923.             ->getRepository(Rdv::class)
  1924.             ->findFirstRdv(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1925.         $myFirstRdv count($rdvsFirst);
  1926.         /****  RDV BY RECHERCHE RESULT VIA MYAUDIO ****/
  1927.         $myAudioRdv 0;
  1928.         $audioRdv $this->getDoctrine()
  1929.             ->getRepository(Rdv::class)
  1930.             ->findRdvMyAudio(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1931.         $myAudioRdv count($audioRdv);
  1932.         /****  RDV BY GENDER ****/
  1933.         $myRdvByGender 0;
  1934.         $audioRdvGender $this->getDoctrine()
  1935.             ->getRepository(Rdv::class)
  1936.             ->countMaleAndFemalePatient(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1937.         $myRdvByGender $audioRdvGender;
  1938.         /****  RDV BY AGE ****/
  1939.         $myRdvByAge 0;
  1940.         $audioRdvAge $this->getDoctrine()
  1941.             ->getRepository(Rdv::class)
  1942.             ->countClientsByAgeGroupsPatient(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1943.         $myRdvByAge $audioRdvAge;
  1944.         //  dd($myRdvByAge);
  1945.         /**** MY LEAD ****/
  1946.         $myLeadCentre 0;
  1947.         $rdvsCanceled $this->getDoctrine()
  1948.             ->getRepository(Rdv::class)
  1949.             ->findCanceledRdvCentreBetweenDateWithoutTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1950.         foreach ($rdvsCanceled as $rdvc) {
  1951.             if (!is_null($rdvc->getIdClient())) {
  1952.                 $rdvClient $this->getDoctrine()
  1953.                     ->getRepository(Rdv::class)
  1954.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1955.                 if (count($rdvClient) == 0) {
  1956.                     $myLeadCentre $myLeadCentre 1;
  1957.                 }
  1958.             }
  1959.         }
  1960.         /**** MY LEAD ADVANCED****/
  1961.         $myLeadAdvancedCentre 0;
  1962.         $rdvsCanceledA $this->getDoctrine()
  1963.             ->getRepository(Rdv::class)
  1964.             ->findCanceledRdvCentreBetweenDateWithTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1965.         foreach ($rdvsCanceledA as $rdvc) {
  1966.             if (!is_null($rdvc->getIdClient())) {
  1967.                 $rdvClient $this->getDoctrine()
  1968.                     ->getRepository(Rdv::class)
  1969.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1970.                 if (count($rdvClient) == 0) {
  1971.                     $myLeadAdvancedCentre $myLeadAdvancedCentre 1;
  1972.                 }
  1973.             }
  1974.         }
  1975.         return $this->json([
  1976.             "rdvs" => count($rdvs),
  1977.             "rdvsFromTest" => count($rdvsWithTest),
  1978.             "allRdvs" => count($allRdvs),
  1979.             "rdvsCanceled" => count($allRdvsCanceled),
  1980.             "rdvsClosed" => $rdvsClosed,
  1981.             "myRdvByGender" => $myRdvByGender,
  1982.             "myLead" => $myLead,
  1983.             "myRdvByAge" => $myRdvByAge,
  1984.             "myAudioRdv" => $myAudioRdv,
  1985.             "myLeadAdvanced" => $myLeadAdvanced,
  1986.             "myRDVCentre" => $myrdvCentre,
  1987.             "myRDVAdancedCentre" => $myRdvAdvancedCentre,
  1988.             "myLeadCentre" => $myLeadCentre,
  1989.             "myLeadAdvancedCentre" => $myLeadAdvancedCentre,
  1990.             "rdvsCanceledCentre" => count($allRdvsCanceledCentre),
  1991.             "myFirstRdv" => $myFirstRdv,
  1992.             "status" => 200,
  1993.         ]);
  1994.     }
  1995.     /**
  1996.      * @Route("/rdvs/old/clientTemp/{id}", name="getOldRdvsByClientTempId", methods={"GET","HEAD"})
  1997.      */
  1998.     public function getOldRdvsByClientTempId(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  1999.     {
  2000.         if (!$request->query->get('token')) {
  2001.             return new Response(json_encode([
  2002.                 "message" => "Pas de token n'a été spécifié",
  2003.                 "status" => 401,
  2004.             ]), 401);
  2005.         }
  2006.         $entityManager $this->getDoctrine()->getManager();
  2007.         /** @var Token */
  2008.         $token $this->getDoctrine()
  2009.             ->getRepository(Token::class)
  2010.             ->findOneBy(['token' => $request->query->get('token')]);
  2011.         if (!$token) {
  2012.             return new Response(json_encode([
  2013.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2014.                 "status" => 404,
  2015.             ]), 404);
  2016.         }
  2017.         // get token age
  2018.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2019.         // if the token if older than 7 days
  2020.         if ($dateDiff->7) {
  2021.             $entityManager->remove($token);
  2022.             $entityManager->flush();
  2023.             return $this->json([
  2024.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2025.                 'path' => 'src/Controller/ClientController.php',
  2026.                 "status" => 401,
  2027.             ], 401);
  2028.         }
  2029.         if ($clientTemp->getIdAudio() != $token->getIdAudio()) {
  2030.             return new Response(json_encode([
  2031.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2032.                 "status" => 404,
  2033.             ]), 404);
  2034.         }
  2035.         if ($request->query->get('audio')) {
  2036.             /** @var ActivityRepository */
  2037.             $activityRepo $this->getDoctrine()->getRepository(Rdv::class);
  2038.             if ($request->query->get('limit')) {
  2039.                 /** @var Rdv[] */
  2040.                 $rdvs $activityRepo
  2041.                     ->findLastsOldRdvsWithLimitTemp($request->query->get('limit'), $clientTemp->getId(), $request->query->get('audio'), new DateTime());
  2042.                 $rdvResult = new ArrayCollection();
  2043.             } else {
  2044.                 /** @var Rdv[] */
  2045.                 $rdvs $activityRepo
  2046.                     ->findOldRdvsTemp($clientTemp->getId(), $request->query->get('audio'), new DateTime());
  2047.                 $rdvResult = new ArrayCollection();
  2048.             }
  2049.             foreach ($rdvs as $rdv) {
  2050.                 if ($rdv->getIdEtat()->getId() != 1) {
  2051.                     continue;
  2052.                 }
  2053.                 /** @var AudioMotif */
  2054.                 $audioMotif $this->getDoctrine()
  2055.                     ->getRepository(AudioMotif::class)
  2056.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  2057.                 if (!$audioMotif) {
  2058.                     continue;
  2059.                 }
  2060.                 $duration '';
  2061.                 if (is_null($rdv->getDuration())) {
  2062.                     $duration $audioMotif->getDuration();
  2063.                 } else {
  2064.                     $duration $rdv->getDuration();
  2065.                 }
  2066.                 $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  2067.                 /** @var Rdv[] */
  2068.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2069.                     ->findAllReviewsCentre($rdvCentre->getId());
  2070.                 $rdvItem = [
  2071.                     "id" => $rdv->getId(),
  2072.                     "motif_id" => $rdv->getIdMotif()->getId(),
  2073.                     "duration" => $duration,
  2074.                     "color" => $audioMotif->getColor(),
  2075.                     "audio_id" => $rdv->getIdAudio()->getId(),
  2076.                     "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2077.                     "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2078.                     "client_id_temp" => $rdv->getIdClientTemp()->getId(),
  2079.                     "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2080.                     "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2081.                     "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2082.                     "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2083.                     "testclient" => $rdv->getTestClient() ? [
  2084.                         "result" => $rdv->getTestClient()->getResultTonal(),
  2085.                         "date" => $rdv->getTestClient()->getDate(),
  2086.                         "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  2087.                     ] : null,
  2088.                     "name" => $rdvCentre->getName(),
  2089.                     "phone" => $rdvCentre->getPhone(),
  2090.                     "imgUrl" => $rdvCentre->getImgUrl(),
  2091.                     "address" => $rdvCentre->getAddress(),
  2092.                     "postale" => $rdvCentre->getPostale(),
  2093.                     "city" => $rdvCentre->getCity(),
  2094.                     "etat_id" => $rdvCentre->getId(),
  2095.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2096.                     "nbrReview" => count($centreRdvs),
  2097.                     "acceptedCurrency" => "CB Chèque",
  2098.                     "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2099.                     "note" => $rdv->getNote(),
  2100.                     "comment" => $rdv->getComment(),
  2101.                     "review" => $rdv->getReview(),
  2102.                 ];
  2103.                 $rdvResult->add($rdvItem);
  2104.             }
  2105.         }
  2106.         if (count($rdvResult) > 0) {
  2107.             return new Response(json_encode(([
  2108.                 "rdv" => $rdvResult->toArray(),
  2109.                 "status" => 200,
  2110.             ])));
  2111.         } else {
  2112.             return new Response(json_encode(([
  2113.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  2114.                 'path' => 'src/Controller/RdvController.php',
  2115.                 "status" => 404,
  2116.             ])));
  2117.         }
  2118.     }
  2119.     /**
  2120.      * @Route("/rdvs/old/clientTemp/{id}/centre", name="getOldRdvsByClientTempIdByCentre", methods={"GET","HEAD"})
  2121.      */
  2122.     public function getOldRdvsByClientTempIdByCentre(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2123.     {
  2124.         if (!$request->query->get('token')) {
  2125.             return new Response(json_encode([
  2126.                 "message" => "Pas de token n'a été spécifié",
  2127.                 "status" => 401,
  2128.             ]), 401);
  2129.         }
  2130.         $entityManager $this->getDoctrine()->getManager();
  2131.         /** @var Token */
  2132.         $token $this->getDoctrine()
  2133.             ->getRepository(Token::class)
  2134.             ->findOneBy(['token' => $request->query->get('token')]);
  2135.         if (!$token) {
  2136.             return new Response(json_encode([
  2137.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2138.                 "status" => 404,
  2139.             ]), 404);
  2140.         }
  2141.         // get token age
  2142.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2143.         // if the token if older than 7 days
  2144.         if ($dateDiff->7) {
  2145.             $entityManager->remove($token);
  2146.             $entityManager->flush();
  2147.             return $this->json([
  2148.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2149.                 'path' => 'src/Controller/ClientController.php',
  2150.                 "status" => 401,
  2151.             ], 401);
  2152.         }
  2153.         $audioCentre $this->getDoctrine()
  2154.             ->getRepository(AudioCentre::class)
  2155.             ->findOneBy(['id_audio' => $token->getIdAudio()]);
  2156.         // we add the multi-centre so we wil desable the autorisation 
  2157.         /*
  2158.         if ($clientTemp->getIdCentre() != $audioCentre->getIdCentre()) {
  2159.             return new Response(json_encode([
  2160.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2161.                 "status" => 404,
  2162.             ]), 404);
  2163.         }
  2164. */
  2165.         /** @var ActivityRepository */
  2166.         $activityRepo $this->getDoctrine()->getRepository(Rdv::class);
  2167.         if ($request->query->get('limit')) {
  2168.             /** @var Rdv[] */
  2169.             $rdvs $activityRepo
  2170.                 ->findLastsOldRdvsWithLimitTempByCentre($request->query->get('limit'), $clientTemp->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  2171.             $rdvResult = new ArrayCollection();
  2172.         } else {
  2173.             /** @var Rdv[] */
  2174.             $rdvs $activityRepo
  2175.                 ->findOldRdvsTempByCentre($clientTemp->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  2176.             $rdvResult = new ArrayCollection();
  2177.         }
  2178.         foreach ($rdvs as $rdv) {
  2179.             /*if ($rdv->getIdEtat()->getId() != 1) {
  2180.                 continue;
  2181.             }*/
  2182.             /** @var AudioMotif */
  2183.             $audioMotif $this->getDoctrine()
  2184.                 ->getRepository(AudioMotif::class)
  2185.                 ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  2186.             if (!$audioMotif) {
  2187.                 continue;
  2188.             }
  2189.             $duration '';
  2190.             if (is_null($rdv->getDuration())) {
  2191.                 $duration $audioMotif->getDuration();
  2192.             } else {
  2193.                 $duration $rdv->getDuration();
  2194.             }
  2195.             $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  2196.             /** @var Rdv[] */
  2197.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2198.                 ->findAllReviewsCentre($rdvCentre->getId());
  2199.             $rdvItem = [
  2200.                 "id" => $rdv->getId(),
  2201.                 "motif_id" => $rdv->getIdMotif()->getId(),
  2202.                 "duration" => $duration,
  2203.                 "color" => $audioMotif->getColor(),
  2204.                 "audio_id" => $rdv->getIdAudio()->getId(),
  2205.                 "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2206.                 "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2207.                 "client_id_temp" => $rdv->getIdClientTemp()->getId(),
  2208.                 "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2209.                 "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2210.                 "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2211.                 "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2212.                 "testclient" => $rdv->getTestClient() ? [
  2213.                     "result" => $rdv->getTestClient()->getResultTonal(),
  2214.                     "date" => $rdv->getTestClient()->getDate(),
  2215.                     "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  2216.                 ] : null,
  2217.                 "name" => $rdvCentre->getName(),
  2218.                 "phone" => $rdvCentre->getPhone(),
  2219.                 "imgUrl" => $rdvCentre->getImgUrl(),
  2220.                 "address" => $rdvCentre->getAddress(),
  2221.                 "postale" => $rdvCentre->getPostale(),
  2222.                 "city" => $rdvCentre->getCity(),
  2223.                 "etat_id" => $rdvCentre->getId(),
  2224.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2225.                 "nbrReview" => count($centreRdvs),
  2226.                 "acceptedCurrency" => "CB Chèque",
  2227.                 "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2228.                 "note" => $rdv->getNote(),
  2229.                 "comment" => $rdv->getComment(),
  2230.                 "review" => $rdv->getReview(),
  2231.                 "status" => $rdv->getIdEtat()->getLibelle()
  2232.             ];
  2233.             $rdvResult->add($rdvItem);
  2234.         }
  2235.         if (count($rdvResult) > 0) {
  2236.             return new Response(json_encode(([
  2237.                 "rdv" => $rdvResult->toArray(),
  2238.                 "status" => 200,
  2239.             ])));
  2240.         } else {
  2241.             return new Response(json_encode(([
  2242.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  2243.                 'path' => 'src/Controller/RdvController.php',
  2244.                 "status" => 404,
  2245.             ])));
  2246.         }
  2247.     }
  2248.     /**
  2249.      * @Route("/rdvs/clientTemp/{id}", name="getRdvsByClientTempID", methods={"GET","HEAD"})
  2250.      */
  2251.     public function getRdvsByClientTempID(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2252.     {
  2253.         if (!$request->query->get('token')) {
  2254.             return new Response(json_encode([
  2255.                 "message" => "Pas de token n'a été spécifié",
  2256.                 "status" => 401,
  2257.             ]), 401);
  2258.         }
  2259.         $entityManager $this->getDoctrine()->getManager();
  2260.         /** @var Token */
  2261.         $token $this->getDoctrine()
  2262.             ->getRepository(Token::class)
  2263.             ->findOneBy(['token' => $request->query->get('token')]);
  2264.         if (!$token) {
  2265.             return new Response(json_encode([
  2266.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2267.                 "status" => 404,
  2268.             ]), 404);
  2269.         }
  2270.         // get token age
  2271.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2272.         // if the token if older than 7 days
  2273.         if ($dateDiff->7) {
  2274.             $entityManager->remove($token);
  2275.             $entityManager->flush();
  2276.             return $this->json([
  2277.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2278.                 'path' => 'src/Controller/ClientController.php',
  2279.                 "status" => 401,
  2280.             ], 401);
  2281.         }
  2282.         if ($clientTemp->getIdAudio() != $token->getIdAudio()) {
  2283.             return new Response(json_encode([
  2284.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2285.                 "status" => 404,
  2286.             ]), 404);
  2287.         }
  2288.         /** @var Rdv[] */
  2289.         $rdvs $this->getDoctrine()
  2290.             ->getRepository(Rdv::class)
  2291.             ->findBy(['id_client_temp' => $clientTemp->getId(), 'id_audio' => $token->getIdAudio()]);
  2292.         $rdvResult = new ArrayCollection();
  2293.         if ($request->query->get('old')) {
  2294.             $oldRdvResult = new ArrayCollection();
  2295.         }
  2296.         foreach ($rdvs as $rdv) {
  2297.             if ($rdv->getIdEtat()->getId() != null) {
  2298.                 if ($rdv->getIdEtat()->getId() == 1) {
  2299.                     /** @var AudioMotif */
  2300.                     $audioMotif $this->getDoctrine()
  2301.                         ->getRepository(AudioMotif::class)
  2302.                         ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $token->getIdAudio()]);
  2303.                     /** @var Rdv[] */
  2304.                     $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2305.                         ->findAllReviewsCentre($rdv->getIdCentre()->getId());
  2306.                     $duration '';
  2307.                     if (is_null($rdv->getDuration())) {
  2308.                         $duration $audioMotif->getDuration();
  2309.                     } else {
  2310.                         $duration $rdv->getDuration();
  2311.                     }
  2312.                     $rdvItem = [
  2313.                         "id" => $rdv->getId(),
  2314.                         "motif_id" => $rdv->getIdMotif()->getId(),
  2315.                         "duration" => $duration,
  2316.                         "color" => $audioMotif->getColor(),
  2317.                         "audio_id" => $rdv->getIdAudio()->getId(),
  2318.                         "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2319.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2320.                         "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  2321.                         "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2322.                         "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2323.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2324.                         "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2325.                         "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2326.                         "nbrReview" => count($centreRdvs),
  2327.                         "acceptedCurrency" => "CB Chèque",
  2328.                         "name" => $rdv->getIdCentre()->getName(),
  2329.                         "imgUrl" => $rdv->getIdCentre()->getImgUrl(),
  2330.                         "address" => $rdv->getIdCentre()->getAddress(),
  2331.                         "phone" => $rdv->getIdCentre()->getPhone(),
  2332.                         "etat_id" => $rdv->getIdEtat()->getId(),
  2333.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2334.                         "comment" => $rdv->getComment(),
  2335.                         "note" => $rdv->getNote(),
  2336.                         "review" => $rdv->getReview(),
  2337.                     ];
  2338.                     if ($rdv->getDate() >= new DateTime()) {
  2339.                         $rdvResult->add($rdvItem);
  2340.                     } else if ($request->query->get('old')) {
  2341.                         $oldRdvResult->add($rdvItem);
  2342.                     }
  2343.                 }
  2344.             }
  2345.         }
  2346.         if ($request->query->get('old')) {
  2347.             if (count($rdvResult) > || count($oldRdvResult) > 0) {
  2348.                 return new Response(json_encode(([
  2349.                     "rdv" => $rdvResult->toArray(),
  2350.                     "oldRdv" => $oldRdvResult->toArray(),
  2351.                     "status" => 200,
  2352.                 ])));
  2353.             } else {
  2354.                 return new Response(json_encode(([
  2355.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2356.                     'path' => 'src/Controller/RdvController.php',
  2357.                     "status" => 404,
  2358.                 ])));
  2359.             }
  2360.         } else {
  2361.             if (count($rdvResult) > 0) {
  2362.                 return new Response(json_encode(([
  2363.                     "content" => $rdvResult->toArray(),
  2364.                     "status" => 200,
  2365.                 ])));
  2366.             } else {
  2367.                 return new Response(json_encode(([
  2368.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2369.                     'path' => 'src/Controller/RdvController.php',
  2370.                     "status" => 404,
  2371.                 ])));
  2372.             }
  2373.         }
  2374.     }
  2375.     /**
  2376.      * @Route("/rdvs/clientTemp/{id}/centre", name="getRdvsByClientTempIDByCentre", methods={"GET","HEAD"})
  2377.      */
  2378.     public function getRdvsByClientTempIDByCentre(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2379.     {
  2380.         if (!$request->query->get('token')) {
  2381.             return new Response(json_encode([
  2382.                 "message" => "Pas de token n'a été spécifié",
  2383.                 "status" => 401,
  2384.             ]), 401);
  2385.         }
  2386.         $entityManager $this->getDoctrine()->getManager();
  2387.         /** @var Token */
  2388.         $token $this->getDoctrine()
  2389.             ->getRepository(Token::class)
  2390.             ->findOneBy(['token' => $request->query->get('token')]);
  2391.         if (!$token) {
  2392.             return new Response(json_encode([
  2393.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2394.                 "status" => 404,
  2395.             ]), 404);
  2396.         }
  2397.         // get token age
  2398.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2399.         // if the token if older than 7 days
  2400.         if ($dateDiff->7) {
  2401.             $entityManager->remove($token);
  2402.             $entityManager->flush();
  2403.             return $this->json([
  2404.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2405.                 'path' => 'src/Controller/ClientController.php',
  2406.                 "status" => 401,
  2407.             ], 401);
  2408.         }
  2409.         $audioCentre $this->getDoctrine()
  2410.             ->getRepository(AudioCentre::class)
  2411.             ->findOneBy(['id_audio' => $token->getIdAudio()]);
  2412.         // we add the multi-centre so we wil desable the autorisation 
  2413.         /*    
  2414.         if ($clientTemp->getIdCentre() != $audioCentre->getIdCentre()) {
  2415.             return new Response(json_encode([
  2416.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2417.                 "status" => 404,
  2418.             ]), 404);
  2419.         }*/
  2420.         /** @var Rdv[] */
  2421.         $rdvs $this->getDoctrine()
  2422.             ->getRepository(Rdv::class)
  2423.             ->findBy(['id_client_temp' => $clientTemp->getId(), 'id_centre' => $audioCentre->getIdCentre()]);
  2424.         $rdvResult = new ArrayCollection();
  2425.         if ($request->query->get('old')) {
  2426.             $oldRdvResult = new ArrayCollection();
  2427.         }
  2428.         foreach ($rdvs as $rdv) {
  2429.             if ($rdv->getIdEtat()->getId() != null) {
  2430.                 if ($rdv->getIdEtat()->getId() != 6) {
  2431.                     // if ($rdv->getIdEtat()->getId() == 1) {
  2432.                     /** @var AudioMotif */
  2433.                     $audioMotif $this->getDoctrine()
  2434.                         ->getRepository(AudioMotif::class)
  2435.                         ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  2436.                     /** @var Rdv[] */
  2437.                     $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2438.                         ->findAllReviewsCentre($rdv->getIdCentre()->getId());
  2439.                     $duration '';
  2440.                     if (is_null($rdv->getDuration())) {
  2441.                         $duration $audioMotif->getDuration();
  2442.                     } else {
  2443.                         $duration $rdv->getDuration();
  2444.                     }
  2445.                     $rdvItem = [
  2446.                         "id" => $rdv->getId(),
  2447.                         "motif_id" => $rdv->getIdMotif()->getId(),
  2448.                         "duration" => $duration,
  2449.                         "color" => $audioMotif->getColor(),
  2450.                         "audio_id" => $rdv->getIdAudio()->getId(),
  2451.                         "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2452.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2453.                         "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  2454.                         "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2455.                         "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2456.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2457.                         "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2458.                         "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2459.                         "nbrReview" => count($centreRdvs),
  2460.                         "acceptedCurrency" => "CB Chèque",
  2461.                         "name" => $rdv->getIdCentre()->getName(),
  2462.                         "imgUrl" => $rdv->getIdCentre()->getImgUrl(),
  2463.                         "address" => $rdv->getIdCentre()->getAddress(),
  2464.                         "phone" => $rdv->getIdCentre()->getPhone(),
  2465.                         "etat_id" => $rdv->getIdEtat()->getId(),
  2466.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2467.                         "comment" => $rdv->getComment(),
  2468.                         "note" => $rdv->getNote(),
  2469.                         "review" => $rdv->getReview(),
  2470.                         "status" => $rdv->getIdEtat()->getLibelle()
  2471.                     ];
  2472.                     if ($rdv->getDate() >= new DateTime()) {
  2473.                         $rdvResult->add($rdvItem);
  2474.                     } else if ($request->query->get('old')) {
  2475.                         $oldRdvResult->add($rdvItem);
  2476.                     }
  2477.                 }
  2478.             }
  2479.         }
  2480.         if ($request->query->get('old')) {
  2481.             if (count($rdvResult) > || count($oldRdvResult) > 0) {
  2482.                 return new Response(json_encode(([
  2483.                     "rdv" => $rdvResult->toArray(),
  2484.                     "oldRdv" => $oldRdvResult->toArray(),
  2485.                     "status" => 200,
  2486.                 ])));
  2487.             } else {
  2488.                 return new Response(json_encode(([
  2489.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2490.                     'path' => 'src/Controller/RdvController.php',
  2491.                     "status" => 404,
  2492.                 ])));
  2493.             }
  2494.         } else {
  2495.             if (count($rdvResult) > 0) {
  2496.                 return new Response(json_encode(([
  2497.                     "content" => $rdvResult->toArray(),
  2498.                     "status" => 200,
  2499.                 ])));
  2500.             } else {
  2501.                 return new Response(json_encode(([
  2502.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2503.                     'path' => 'src/Controller/RdvController.php',
  2504.                     "status" => 404,
  2505.                 ])));
  2506.             }
  2507.         }
  2508.     }
  2509.     /**
  2510.      * @Route("/rdv", name="postRdv", methods={"POST"})
  2511.      */
  2512.     public function postRdv(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSmsAppointmentCallService $Callservice): Response
  2513.     {
  2514.         $data json_decode($request->getContent(), true);
  2515.         if (!isset($data["token"])) {
  2516.             return new Response(json_encode([
  2517.                 "message" => "Pas de token n'a été spécifié",
  2518.                 "status" => 401,
  2519.             ]), 401);
  2520.         }
  2521.         $entityManager $this->getDoctrine()->getManager();
  2522.         /** @var Token */
  2523.         $token $this->getDoctrine()
  2524.             ->getRepository(Token::class)
  2525.             ->findOneBy(['token' => $data["token"]]);
  2526.         if (!$token) {
  2527.             return new Response(json_encode([
  2528.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2529.                 "status" => 404,
  2530.             ]), 404);
  2531.         }
  2532.         // get token age
  2533.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2534.         // if the token if older than 7 days
  2535.         if ($dateDiff->7) {
  2536.             $entityManager->remove($token);
  2537.             $entityManager->flush();
  2538.             return $this->json([
  2539.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2540.                 'path' => 'src/Controller/ClientController.php',
  2541.                 "status" => 401,
  2542.             ], 401);
  2543.         }
  2544.         // makes the rdv
  2545.         $rdv = new Rdv();
  2546.         if ($token->getIdAudio()) {
  2547.             //if the token if for an audio
  2548.             $audio $token->getIdAudio();
  2549.             if ((isset($data["client_id"]))) {
  2550.                 $client $this->getDoctrine()
  2551.                     ->getRepository(Client::class)
  2552.                     ->findOneBy(['id' => $data["client_id"]]);
  2553.             } else {
  2554.                 $client $this->getDoctrine()
  2555.                     ->getRepository(ClientTemp::class)
  2556.                     ->findOneBy(['id' => $data["client_id_temp"]]);
  2557.             }
  2558.             if ($client == null) {
  2559.                 return new Response(json_encode(([
  2560.                     'message' => 'Error, no client found at this id',
  2561.                     'path' => 'src/Controller/RdvController.php',
  2562.                     "status" => 400,
  2563.                 ])), 400);
  2564.             }
  2565.         } elseif ($token->getIdClient()) {
  2566.             //if the token if for a client
  2567.             $client $token->getIdClient();
  2568.             /** @var ActivityRepository */
  2569.             $activityRepo $this->getDoctrine();
  2570.             /** @var TestClient */
  2571.             $testClient $activityRepo
  2572.                 ->getRepository(TestClient::class)
  2573.                 ->getLatestTestClient($client);
  2574.             // add the test to the rdv if the client had one
  2575.             if ($testClient)
  2576.             // add the test to the rdv if the test isn't already on another rdv
  2577.             {
  2578.                 if (!$testClient->getRdv()) {
  2579.                     $rdv->setTestClient($testClient);
  2580.                 }
  2581.             }
  2582.             /** @var Audio */
  2583.             $audio $this->getDoctrine()
  2584.                 ->getRepository(Audio::class)
  2585.                 ->findOneBy(['id' => $data["audio_id"]]);
  2586.             if (isset($data["proche_id"])) {
  2587.                 $proche $this->getDoctrine()
  2588.                     ->getRepository(Proches::class)
  2589.                     ->findOneBy(['id' => $data["proche_id"], "id_client" => $client]);
  2590.             }
  2591.             if (!$audio) {
  2592.                 return new Response(json_encode(([
  2593.                     'message' => "Erreur, pas d'audio n'a été trouvé à cette id.",
  2594.                     'path' => 'src/Controller/RdvController.php',
  2595.                 ])), 400);
  2596.             }
  2597.             /** @var ClientBlocked */
  2598.             $clientBlocked $this->getDoctrine()
  2599.                 ->getRepository(ClientBlocked::class)
  2600.                 ->findOneBy(["id_audio" => $audio"id_client" => $client]);
  2601.             if ($clientBlocked) {
  2602.                 return new Response(json_encode(([
  2603.                     'message' => 'Erreur, vous avez été bloqué par cette audioprothésiste.',
  2604.                     'path' => 'src/Controller/RdvController.php',
  2605.                 ])), 400);
  2606.             }
  2607.             // set the rdv test
  2608.         } else {
  2609.             return new Response(json_encode(([
  2610.                 'message' => "Erreur, ce token n'est pas celui d'un client ou audioprothèsiste.",
  2611.                 'path' => 'src/Controller/RdvController.php',
  2612.             ])), 400);
  2613.         }
  2614.         $rdv->setIdAudio($audio);
  2615.         if (isset($proche)) {
  2616.             $rdv->setIdProche($proche);
  2617.         }
  2618.         if (isset($data["client_id_temp"])) {
  2619.             $rdv->setIdClientTemp($client);
  2620.         } else {
  2621.             $rdv->setIdClient($client);
  2622.         }
  2623.         if (isset($data["isMyaudio"])) {
  2624.             $rdv->setIsMyaudio(true);
  2625.         }
  2626.         if (isset($data["isRdvLead"])) {
  2627.             $rdv->setIsRdvLp(true);
  2628.         }
  2629.         if (isset($data["isRdvRapide"])) {
  2630.             $rdv->setIsRdvRapide(true);
  2631.         }
  2632.         if (isset($data["duree"])) {
  2633.             $rdv->setDuration($data["duree"]);
  2634.         }
  2635.         if (isset($data["color"])) {
  2636.             $rdv->setColor($data["color"]);
  2637.         }
  2638.         if (isset($data["lead"])) {
  2639.             $lead $this->getDoctrine()
  2640.                 ->getRepository(LeadRdv::class)
  2641.                 ->find($data["lead"]);
  2642.             $lead->setRdv($rdv);
  2643.             $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
  2644.             if ($leadStatus) {
  2645.                 $lead->setLeadStatus($leadStatus);
  2646.             }
  2647.         }
  2648.         /** @var Centre */
  2649.         if (isset($data["centre_id"])) {
  2650.             $centre $this->getDoctrine()
  2651.                 ->getRepository(Centre::class)
  2652.                 ->findOneBy(['id' => $data["centre_id"]]);
  2653.             if ($centre == null) {
  2654.                 return new Response(json_encode(([
  2655.                     'message' => 'Error, no centre found at this id',
  2656.                     'path' => 'src/Controller/RdvController.php',
  2657.                     "status" => 400,
  2658.                 ])), 400);
  2659.             }
  2660.             /** @var AudioCentre */
  2661.             $liaison $this->getDoctrine()
  2662.                 ->getRepository(AudioCentre::class)
  2663.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  2664.             if ($liaison == null) {
  2665.                 return new Response(json_encode(([
  2666.                     'message' => 'Error, audio isnt part of the centre',
  2667.                     'path' => 'src/Controller/RdvController.php',
  2668.                     "status" => 400,
  2669.                 ])), 400);
  2670.             }
  2671.             $rdv->setIdCentre($centre);
  2672.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  2673.             // tries to set the lieu if it's an audio indie
  2674.             $lieu $this->getDoctrine()
  2675.                 ->getRepository(Lieu::class)
  2676.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  2677.             if ($lieu == null) {
  2678.                 return new Response(json_encode(([
  2679.                     'message' => 'Error, no lieu found at this id',
  2680.                     'path' => 'src/Controller/RdvController.php',
  2681.                     "status" => 400,
  2682.                 ])), 400);
  2683.             }
  2684.             $rdv->setIdLieu($lieu);
  2685.         } else {
  2686.             return new Response(json_encode(([
  2687.                 'message' => 'Error, no lieu/centre id',
  2688.                 'path' => 'src/Controller/RdvController.php',
  2689.                 "status" => 400,
  2690.             ])), 400);
  2691.         }
  2692.         /** @var Motif */
  2693.         $motif $this->getDoctrine()
  2694.             ->getRepository(Motif::class)
  2695.             ->find($data["motif_id"]);
  2696.         if ($motif == null) {
  2697.             return new Response(json_encode(([
  2698.                 'message' => 'Error, no motif found at this id',
  2699.                 'path' => 'src/Controller/RdvController.php',
  2700.                 "status" => 400,
  2701.             ])), 400);
  2702.         }
  2703.         /** @var AudioMotif */
  2704.         $audioMotif $this->getDoctrine()
  2705.             ->getRepository(AudioMotif::class)
  2706.             ->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
  2707.         if ($audioMotif == null) {
  2708.             return new Response(json_encode(([
  2709.                 'message' => 'Error, no motif of this id found at this audio',
  2710.                 'path' => 'src/Controller/RdvController.php',
  2711.                 "status" => 400,
  2712.             ])), 400);
  2713.         }
  2714.         // remove the taken schedule by rdv to make sure there is no overlap
  2715.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  2716.         if (isset($data["note"])) {
  2717.             $rdv->setNote($data["note"]);
  2718.         }
  2719.         // test if the audio is available
  2720.         if ($audio->getIsIndie()) {
  2721.             if (isset($data["centre_id"])) {
  2722.                 if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  2723.                     return new Response(json_encode(([
  2724.                         'message' => 'Error, no horaire found for this audio',
  2725.                         'path' => 'src/Controller/RdvController.php',
  2726.                         "status" => 400,
  2727.                     ])), 400);
  2728.                 }
  2729.                 if ($publicFunction->calculScheduleFitDate($audio\DateTime::createFromFormat("d/m/Y H:i"$data["date"]), $audioMotif->getDuration(), $centre) == false) {
  2730.                     return new Response(json_encode(([
  2731.                         'message' => 'Error, no timestamp found at this time. Line n°' __LINE__,
  2732.                         'path' => 'src/Controller/RdvController.php',
  2733.                         "status" => 400,
  2734.                     ])), 400);
  2735.                 }
  2736.                 $remplacant_id $publicFunction->checkIfRemplacant($liaison->getHoraire(), $date);
  2737.             } else {
  2738.                 if ($lieu->getHoraire() == null || $lieu->getHoraire() == []) {
  2739.                     return new Response(json_encode(([
  2740.                         'message' => 'Error, no horaire found for this audio',
  2741.                         'path' => 'src/Controller/RdvController.php',
  2742.                         "status" => 400,
  2743.                     ])), 400);
  2744.                 }
  2745.                 if ($publicFunction->calculScheduleFitDate($audio\DateTime::createFromFormat("d/m/Y H:i"$data["date"]), $audioMotif->getDuration(), null$lieu) == false) {
  2746.                     return new Response(json_encode(([
  2747.                         'message' => 'Error, no timestamp found at this time. Line n°' __LINE__,
  2748.                         'path' => 'src/Controller/RdvController.php',
  2749.                         "status" => 400,
  2750.                     ])), 400);
  2751.                 }
  2752.                 $remplacant_id $publicFunction->checkIfRemplacant($lieu->getHoraire(), $date);
  2753.             }
  2754.         } else {
  2755.             if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  2756.                 return new Response(json_encode(([
  2757.                     'message' => 'Error, no horaire found for this audio',
  2758.                     'path' => 'src/Controller/RdvController.php',
  2759.                     "status" => 400,
  2760.                 ])), 400);
  2761.             }
  2762.             /*  if (!$publicFunction->calculScheduleFitDate($audio, \DateTime::createFromFormat("d/m/Y H:i", $data["date"]), $audioMotif->getDuration(), $centre))
  2763.                 return new Response(json_encode(([
  2764.                     'message' => "Error, no timestamp found at this time. Motif size: {$audioMotif->getDuration()} Line n°" . __LINE__,
  2765.                     'path' => 'src/Controller/RdvController.php',
  2766.                     "status" => 400,
  2767.                 ])), 400);*/
  2768.             $remplacant_id $publicFunction->checkIfRemplacant($liaison->getHoraire(), \DateTime::createFromFormat("d/m/Y H:i"$data["date"]));
  2769.         }
  2770.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  2771.         $existingRdv $this->getDoctrine()
  2772.             ->getRepository(Rdv::class)
  2773.             ->findOneBy([
  2774.                 'date' => $date,
  2775.                 'id_audio' => $audio,
  2776.                 'id_centre' => $rdv->getIdCentre() ?? null,
  2777.                 'id_lieu' => $rdv->getIdLieu()   ?? null,
  2778.             ]);
  2779.         if ($existingRdv) {
  2780.             return new Response(json_encode([
  2781.                 'message' => 'Un rendez-vous est déjà pris pour cette date et ce créneau.',
  2782.                 'status' => 400,
  2783.             ]), 400);
  2784.         }
  2785.         $rdv->setDate($date);
  2786.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  2787.         /** @var EtatRdv */
  2788.         $etat $this->getDoctrine()
  2789.             ->getRepository(EtatRdv::class)
  2790.             ->findOneBy(['id' => $data["etat_id"]]);
  2791.         if ($etat == null) {
  2792.             return new Response(json_encode(([
  2793.                 'message' => 'Error, no etat found at this id',
  2794.                 'path' => 'src/Controller/RdvController.php',
  2795.                 "status" => 400,
  2796.             ])), 400);
  2797.         }
  2798.         $rdv->setIdEtat($etat);
  2799.         $rdv->setIdMotif($motif);
  2800.         $rdv->setIsAbsence(0);
  2801.         $rdv->setCacher(0);
  2802.         if ($remplacant_id != -1) {
  2803.             $remplacant $this->getDoctrine()
  2804.                 ->getRepository(Remplacant::class)
  2805.                 ->find($remplacant_id);
  2806.             $rdv->setRemplacant($remplacant);
  2807.         }
  2808.         $entityManager $this->getDoctrine()->getManager();
  2809.         $entityManager->persist($rdv);
  2810.         $entityManager->flush();
  2811.         /// SMSEMAIL A décommenter pour autoriser l'envoi de sms / email à la création de rdv par l'audio / le client SMSEMAIL ///
  2812.         $date $rdv->getDate();
  2813.         $smsDate $date->format('d-m-Y H:i');
  2814.         $locale 'fr_FR';
  2815.         $formatter = new IntlDateFormatter(
  2816.             $locale,
  2817.             IntlDateFormatter::FULL,
  2818.             IntlDateFormatter::SHORT,
  2819.             null,
  2820.             IntlDateFormatter::GREGORIAN,
  2821.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  2822.         );
  2823.         $smsDateLongFormat $formatter->format($date);
  2824.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  2825.         $client->setIdCentre($rdv->getIdCentre());
  2826.         $client->setIdAudio($rdv->getIdAudio());
  2827.         $entityManager->persist($client);
  2828.         $entityManager->flush();
  2829.         // client notif mail Sms
  2830.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  2831.         $frenchDate ucfirst($frenchDate);
  2832.         $responses = [
  2833.             'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
  2834.             'situations' => (isset($data['situations']) && !empty($data['situations'])) ? implode(", "$data['situations']) : null,
  2835.             'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
  2836.             'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
  2837.             'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
  2838.             'ordonance' => isset($data['ordonnance']) ? $data['ordonnance'] : null,
  2839.             'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
  2840.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  2841.         ];
  2842.         $paramsSourceLead = [
  2843.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  2844.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  2845.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  2846.         ];
  2847.         $params = array(
  2848.             "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  2849.             "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  2850.             "date" => $smsDateLongFormat,
  2851.             "RdvDate" => $smsDateLongFormat,
  2852.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  2853.             "centerName" => $rdv->getIdCentre()->getName(),
  2854.             "prenom" => $client->getName(),
  2855.             "centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  2856.             "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  2857.             'motif' => $rdv->getIdMotif()->getTitre(),
  2858.             "centerCity" => $rdv->getIdCentre()->getCity(),
  2859.             "audioName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  2860.             'titre' => "Votre rendez-vous est validé le " substr($smsDate010) . " à "  substr($smsDate1115),
  2861.             "position" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  2862.             "address" => $rdv->getIdCentre()->getAddress(),
  2863.             "postal" => $rdv->getIdCentre()->getPostale(),
  2864.             "city" => $rdv->getIdCentre()->getCity(),
  2865.             "clientEmail" => $client->getMail(),
  2866.             "clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
  2867.             "clientAddress" => $client->getAddress(),
  2868.             "clientPostal" => $client->getPostal(),
  2869.             "clientCity" => $client->getCity(),
  2870.             "audioName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  2871.             "frenchDate" => $frenchDate,
  2872.             "heure" => substr($smsDate1115),
  2873.             "centerName" => $rdv->getIdCentre()->getName(),
  2874.             "audioMail" => $rdv->getIdAudio()->getMail(),
  2875.             "modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
  2876.         );
  2877.         $paramsPatient $params;
  2878.         $isNew false;
  2879.         if (isset($data["isLead"]) && isset($data["passwordGenerated"]) != null) {
  2880.             $subject "✅Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  2881.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject189);
  2882.             $isNew true;
  2883.         } else {
  2884.             $subject "Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  2885.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject181);
  2886.         }
  2887.         $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.";
  2888.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  2889.         // audio Notif mail SMS
  2890.         $birthday $rdv->getIdClient()->getBirthdate();
  2891.         $params = array(
  2892.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  2893.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  2894.             "date" => substr($smsDate010),
  2895.             "heure" => substr($smsDate1115),
  2896.             "mail" => $client->getMail(),
  2897.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  2898.             'telClient' => $client->getPhone(),
  2899.             'phone' => $client->getPhone(),
  2900.             'clientCivilite' => $client->getCivilite(),
  2901.             'clientNom' => $client->getLastname(),
  2902.             'clientPrenom' => $client->getName(),
  2903.             'clientPostal' => $client->getPostal(),
  2904.             'clientMail' => $client->getMail(),
  2905.             'clientPhone' => $client->getPhone(),
  2906.             'motif' => $rdv->getIdMotif()->getTitre(),
  2907.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  2908.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  2909.             'centerName' => $rdv->getIdCentre()->getName(),
  2910.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  2911.             'centerCity' => $rdv->getIdCentre()->getCity(),
  2912.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  2913.             'idPatient' => $client->getId(),
  2914.             'proUrl' => "{$_ENV['BASE_logiciel']}",
  2915.             'frenchDate' => $frenchDate,
  2916.             'responses' => $responses,
  2917.         );
  2918.         $templateEmail 182;
  2919.         if (!empty($data['canMove'])) {
  2920.             $templateEmail 197;
  2921.         }
  2922.         $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  2923.         $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  2924.         if ($rdv->getIdAudio()->getConfirmRdvMail()) {
  2925.             $subject "✅Nouveau Rendez-vous My Audio le " $frenchDate " à " substr($smsDate1115);
  2926.             $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject$templateEmail);
  2927.         }
  2928.         if ($rdv->getIdAudio()->getConfirmRdvSms()) {
  2929.             $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.";
  2930.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  2931.         }
  2932.         // send notif to admin
  2933.         $paramsAdmin = array(
  2934.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  2935.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  2936.             "RdvDate" => substr($smsDate010),
  2937.             "heure" => substr($smsDate1115),
  2938.             "clientMail" => $client->getMail(),
  2939.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  2940.             'telClient' => $client->getPhone(),
  2941.             'clientNom' => $client->getLastname(),
  2942.             'clientPrenom' => $client->getName(),
  2943.             'clientCivilite' => $client->getCivilite(),
  2944.             'clientPostal' => $client->getPostal(),
  2945.             'clientPhone' => $client->getPhone(),
  2946.             'motif' => $rdv->getIdMotif()->getTitre(),
  2947.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  2948.             'centerName' => $rdv->getIdCentre()->getName(),
  2949.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  2950.             'centerCity' => $rdv->getIdCentre()->getCity(),
  2951.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  2952.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  2953.             'date' => substr($smsDate010),
  2954.             'urlApi' => "{$_ENV['BASE_API']}",
  2955.             'clientId' => $client->getId(),
  2956.             'centerId' => $rdv->getIdCentre()->getId(),
  2957.             'frenchDate' => $frenchDate,
  2958.             'responses' => $responses,
  2959.             'paramsSourceLead' => $paramsSourceLead
  2960.         );
  2961.         $subject "Nouveau RDV MA | RR - " $rdv->getIdCentre()->getName();
  2962.         $templateEmail 183;
  2963.         if (!empty($data['canMove'])) {
  2964.             $templateEmail 190;
  2965.         }
  2966.         if (!isset($data["isLead"])) {
  2967.             $publicFunction->sendEmail($paramsAdmin"lead.myaudio@gmail.com""my audio"$subject$templateEmail);
  2968.         }
  2969.         //$publicFunction->sendEmail($paramsAdmin,"testpation1254@yopmail.com","my audio", 'Nouveau RDV à My Audio Pro', $templateEmail);
  2970.         $publicFunction->sendEmail($paramsAdmin"contact@myaudio.fr""my audio"$subject$templateEmail);
  2971.         $publicFunction->sendEmail($paramsAdmin"lead.myaudio@gmail.com""my audio"$subject$templateEmail);
  2972.         // google calendar post
  2973.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  2974.             ->findBy(array('audio' => $audio->getId()));
  2975.         $data['rdv'] = $rdv->getId();
  2976.         if (isset($data['clientRdvLp']) && !empty($data['clientRdvLp'])) {
  2977.             $rdvLead $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
  2978.             if ($rdvLead) {
  2979.                 $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
  2980.                 if ($leadStatus) {
  2981.                     $rdvLead->setLeadStatus($leadStatus);
  2982.                     $rdvLead->setRdv($rdv);
  2983.                     $this->entityManager->flush();
  2984.                 }
  2985.             }
  2986.         }
  2987.         foreach ($synchronisations as $synchronisation) {
  2988.             if (!$synchronisation->getIsDeleted()) {
  2989.                 $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  2990.                 $googleCalendar->createEvent($synchronisation$data);
  2991.             }
  2992.         }
  2993.         if (isset($data["isMyaudio"]) || isset($data["isRdvLead"]) || isset($data["isRdvRapide"])) {
  2994.             try {
  2995.                 $Callservice->handleCallCenterAfterRdv(
  2996.                     $rdv
  2997.                 );
  2998.                 $rdv->setIsNotificationRdvCallSent(1);
  2999.                 $this->entityManager->flush();
  3000.             } catch (\Exception $e) {
  3001.                 $this->logger->error("Erreur lors de l'appel de notification pour le RDV #{$rdv->getId()}: " $e->getMessage());
  3002.             }
  3003.         }
  3004.         // After successfully creating the RDV
  3005.         $this->mercure->publishRdvUpdate($rdv'created');
  3006.         return new Response(json_encode(([
  3007.             "id" => $rdv->getId(),
  3008.             "motif_id" => $rdv->getIdMotif()->getId(),
  3009.             "audio_id" => $rdv->getIdAudio()->getId(),
  3010.             "remplacant_id" => $remplacant_id == -null $remplacant_id,
  3011.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  3012.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  3013.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  3014.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  3015.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  3016.             "testclient" => $rdv->getTestClient() ? [
  3017.                 "result" => $rdv->getTestClient()->getResultTonal(),
  3018.                 "date" => $rdv->getTestClient()->getDate(),
  3019.                 "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  3020.             ] : null,
  3021.             "duration" => $audioMotif->getDuration(),
  3022.             "consigne" => $audioMotif->getConsigne(),
  3023.             "etat_id" => $rdv->getIdEtat()->getId(),
  3024.             "date" => $rdv->getDate(),
  3025.             "comment" => $rdv->getComment(),
  3026.             "centerName" => $rdv->getIdCentre()->getName(),
  3027.             "review" => $rdv->getReview(),
  3028.             "note" => $rdv->getNote(),
  3029.             "status" => 200,
  3030.             "paramsPatient" => $paramsPatient,
  3031.             "isNew" => $isNew,
  3032.         ])));
  3033.     }
  3034.     /**
  3035.      * @Route("/rdv/v2", name="postRdvV2", methods={"POST"})
  3036.      *
  3037.      * Version optimisée de la prise de rendez-vous pour les clients via le site
  3038.      * Gestion complète: validation, création RDV, notifications email/SMS
  3039.      */
  3040.     public function postRdvV2(
  3041.         Request $request,
  3042.         PublicFunction $publicFunction,
  3043.         GoogleCalendarService $googleCalendar,
  3044.         AppointmentCallService $callService
  3045.     ): JsonResponse {
  3046.         try {
  3047.             $data json_decode($request->getContent(), true);
  3048.             // Validation du token et récupération du client
  3049.             $validationResult $this->validateTokenAndGetClient($data);
  3050.             if ($validationResult instanceof Response) {
  3051.                 return new JsonResponse(json_decode($validationResult->getContent(), true), $validationResult->getStatusCode());
  3052.             }
  3053.             ['client' => $client'token' => $token] = $validationResult;
  3054.             // Récupération et validation de l'audio
  3055.             $audio $this->entityManager->getRepository(Audio::class)->find($data['audio_id'] ?? null);
  3056.             if (!$audio) {
  3057.                 return new JsonResponse([
  3058.                     'message' => "Aucun audioprothésiste trouvé avec cet ID.",
  3059.                     'status' => 404
  3060.                 ], 404);
  3061.             }
  3062.             // Vérification du blocage client
  3063.             $clientBlocked $this->entityManager->getRepository(ClientBlocked::class)
  3064.                 ->findOneBy(['id_audio' => $audio'id_client' => $client]);
  3065.             if ($clientBlocked) {
  3066.                 return new JsonResponse([
  3067.                     'message' => 'Vous avez été bloqué par cet audioprothésiste.',
  3068.                     'status' => 403
  3069.                 ], 403);
  3070.             }
  3071.             // Validation du centre/lieu
  3072.             $locationResult $this->validateLocation($data$audio);
  3073.             if ($locationResult instanceof Response) {
  3074.                 return new JsonResponse(json_decode($locationResult->getContent(), true), $locationResult->getStatusCode());
  3075.             }
  3076.             ['centre' => $centre'lieu' => $lieu'liaison' => $liaison] = $locationResult;
  3077.             // Validation du motif
  3078.             $motifResult $this->validateMotif($data$audio);
  3079.             if ($motifResult instanceof Response) {
  3080.                 return new JsonResponse(json_decode($motifResult->getContent(), true), $motifResult->getStatusCode());
  3081.             }
  3082.             ['motif' => $motif'audioMotif' => $audioMotif] = $motifResult;
  3083.             // Validation de la disponibilité
  3084.             $date \DateTime::createFromFormat("d/m/Y H:i"$data['date']);
  3085.             if (!$date) {
  3086.                 return new JsonResponse([
  3087.                     'message' => 'Format de date invalide. Utilisez le format: d/m/Y H:i',
  3088.                     'status' => 400
  3089.                 ], 400);
  3090.             }
  3091.             $availabilityResult $this->validateAvailability(
  3092.                 $audio,
  3093.                 $date,
  3094.                 $audioMotif->getDuration(),
  3095.                 $centre,
  3096.                 $lieu,
  3097.                 $liaison,
  3098.                 $publicFunction
  3099.             );
  3100.             if ($availabilityResult instanceof Response) {
  3101.                 return new JsonResponse(json_decode($availabilityResult->getContent(), true), $availabilityResult->getStatusCode());
  3102.             }
  3103.             $remplacant_id $availabilityResult;
  3104.             // Création du rendez-vous
  3105.             $rdv $this->createAppointment($data$client$audio$centre$lieu$motif$audioMotif$date$remplacant_id);
  3106.             // Envoi des notifications
  3107.             $this->sendNotifications($rdv$client$audio$publicFunction$data);
  3108.             // Synchronisation Google Calendar
  3109.             $this->syncGoogleCalendar($audio$rdv$googleCalendar$data);
  3110.             // Notification call center si nécessaire
  3111.             if (isset($data['isMyaudio']) || isset($data['isRdvLead']) || isset($data['isRdvRapide'])) {
  3112.                 try {
  3113.                     $callService->handleCallCenterAfterRdv($rdv);
  3114.                     $rdv->setIsNotificationRdvCallSent(1);
  3115.                     $this->entityManager->flush();
  3116.                 } catch (\Exception $e) {
  3117.                     $this->logger->error("Erreur notification call center RDV #{$rdv->getId()}: " $e->getMessage());
  3118.                 }
  3119.             }
  3120.             // Réponse finale
  3121.             return new JsonResponse([
  3122.                 'success' => true,
  3123.                 'message' => 'Rendez-vous créé avec succès',
  3124.                 'rdv' => [
  3125.                     'id' => $rdv->getId(),
  3126.                     'date' => $rdv->getDate()->format('d/m/Y H:i'),
  3127.                     'motif' => $motif->getTitre(),
  3128.                     'duration' => $audioMotif->getDuration(),
  3129.                     'centre' => $centre $centre->getName() : null,
  3130.                     'lieu' => $lieu $lieu->getName() : null,
  3131.                     'audio' => $audio->getName() . ' ' $audio->getLastName(),
  3132.                 ],
  3133.                 'status' => 201
  3134.             ], 201);
  3135.         } catch (\Exception $e) {
  3136.             $this->logger->error("Erreur lors de la création du RDV: " $e->getMessage());
  3137.             return new JsonResponse([
  3138.                 'success' => false,
  3139.                 'message' => 'Une erreur est survenue lors de la création du rendez-vous.',
  3140.                 'error' => $e->getMessage(),
  3141.                 'status' => 500
  3142.             ], 500);
  3143.         }
  3144.     }
  3145.     /**
  3146.      * Valide le token et récupère le client associé
  3147.      */
  3148.     private function validateTokenAndGetClient(array $data)
  3149.     {
  3150.         if (!isset($data['token'])) {
  3151.             return new Response(json_encode([
  3152.                 'message' => "Aucun token n'a été spécifié",
  3153.                 'status' => 401
  3154.             ]), 401);
  3155.         }
  3156.         $token $this->entityManager->getRepository(Token::class)
  3157.             ->findOneBy(['token' => $data['token']]);
  3158.         if (!$token) {
  3159.             return new Response(json_encode([
  3160.                 'message' => "Token invalide. Veuillez vous reconnecter.",
  3161.                 'status' => 404
  3162.             ]), 404);
  3163.         }
  3164.         // Vérification de l'âge du token
  3165.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  3166.         if ($dateDiff->7) {
  3167.             $this->entityManager->remove($token);
  3168.             $this->entityManager->flush();
  3169.             return new Response(json_encode([
  3170.                 'message' => 'Token expiré. Veuillez vous reconnecter.',
  3171.                 'status' => 401
  3172.             ]), 401);
  3173.         }
  3174.         // Récupération du client
  3175.         $client $token->getIdClient();
  3176.         if (!$client) {
  3177.             return new Response(json_encode([
  3178.                 'message' => "Ce token n'est pas associé à un client.",
  3179.                 'status' => 400
  3180.             ]), 400);
  3181.         }
  3182.         return ['client' => $client'token' => $token];
  3183.     }
  3184.     /**
  3185.      * Valide le centre ou lieu du rendez-vous
  3186.      */
  3187.     private function validateLocation(array $dataAudio $audio)
  3188.     {
  3189.         $centre null;
  3190.         $lieu null;
  3191.         $liaison null;
  3192.         if (isset($data['centre_id'])) {
  3193.             $centre $this->entityManager->getRepository(Centre::class)->find($data['centre_id']);
  3194.             if (!$centre) {
  3195.                 return new Response(json_encode([
  3196.                     'message' => 'Aucun centre trouvé avec cet ID',
  3197.                     'status' => 404
  3198.                 ]), 404);
  3199.             }
  3200.             $liaison $this->entityManager->getRepository(AudioCentre::class)
  3201.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  3202.             if (!$liaison) {
  3203.                 return new Response(json_encode([
  3204.                     'message' => "L'audioprothésiste n'est pas rattaché à ce centre",
  3205.                     'status' => 400
  3206.                 ]), 400);
  3207.             }
  3208.         } elseif (isset($data['lieu_id']) && $audio->getIsIndie()) {
  3209.             $lieu $this->entityManager->getRepository(Lieu::class)
  3210.                 ->findOneBy(['id' => $data['lieu_id'], 'id_gerant' => $audio->getId()]);
  3211.             if (!$lieu) {
  3212.                 return new Response(json_encode([
  3213.                     'message' => 'Aucun lieu trouvé avec cet ID',
  3214.                     'status' => 404
  3215.                 ]), 404);
  3216.             }
  3217.         } else {
  3218.             return new Response(json_encode([
  3219.                 'message' => 'Veuillez spécifier un centre ou un lieu',
  3220.                 'status' => 400
  3221.             ]), 400);
  3222.         }
  3223.         return ['centre' => $centre'lieu' => $lieu'liaison' => $liaison];
  3224.     }
  3225.     /**
  3226.      * Valide le motif du rendez-vous
  3227.      */
  3228.     private function validateMotif(array $dataAudio $audio)
  3229.     {
  3230.         if (!isset($data['motif_id'])) {
  3231.             return new Response(json_encode([
  3232.                 'message' => 'Aucun motif spécifié',
  3233.                 'status' => 400
  3234.             ]), 400);
  3235.         }
  3236.         $motif $this->entityManager->getRepository(Motif::class)->find($data['motif_id']);
  3237.         if (!$motif) {
  3238.             return new Response(json_encode([
  3239.                 'message' => 'Aucun motif trouvé avec cet ID',
  3240.                 'status' => 404
  3241.             ]), 404);
  3242.         }
  3243.         $audioMotif $this->entityManager->getRepository(AudioMotif::class)
  3244.             ->findOneBy(['id_audio' => $audio->getId(), 'id_motif' => $data['motif_id']]);
  3245.         if (!$audioMotif) {
  3246.             return new Response(json_encode([
  3247.                 'message' => "Ce motif n'est pas disponible pour cet audioprothésiste",
  3248.                 'status' => 400
  3249.             ]), 400);
  3250.         }
  3251.         return ['motif' => $motif'audioMotif' => $audioMotif];
  3252.     }
  3253.     /**
  3254.      * Valide la disponibilité du créneau
  3255.      */
  3256.     private function validateAvailability(
  3257.         Audio $audio,
  3258.         \DateTime $date,
  3259.         int $duration,
  3260.         ?Centre $centre,
  3261.         ?Lieu $lieu,
  3262.         ?AudioCentre $liaison,
  3263.         PublicFunction $publicFunction
  3264.     ) {
  3265.         // Vérification qu'il n'y a pas déjà un RDV à cette date
  3266.         $existingRdv $this->entityManager->getRepository(Rdv::class)
  3267.             ->findOneBy([
  3268.                 'date' => $date,
  3269.                 'id_audio' => $audio,
  3270.                 'id_centre' => $centre,
  3271.                 'id_lieu' => $lieu,
  3272.             ]);
  3273.         if ($existingRdv) {
  3274.             return new Response(json_encode([
  3275.                 'message' => 'Un rendez-vous existe déjà à ce créneau',
  3276.                 'status' => 409
  3277.             ]), 409);
  3278.         }
  3279.         // Vérification de la disponibilité selon le type d'audio
  3280.         if ($audio->getIsIndie()) {
  3281.             if ($centre && $liaison) {
  3282.                 if (!$liaison->getHoraire() || $liaison->getHoraire() == []) {
  3283.                     return new Response(json_encode([
  3284.                         'message' => 'Aucun horaire configuré pour cet audioprothésiste',
  3285.                         'status' => 400
  3286.                     ]), 400);
  3287.                 }
  3288.                 if (!$publicFunction->calculScheduleFitDate($audio$date$duration$centre)) {
  3289.                     return new Response(json_encode([
  3290.                         'message' => 'Créneau non disponible',
  3291.                         'status' => 400
  3292.                     ]), 400);
  3293.                 }
  3294.                 return $publicFunction->checkIfRemplacant($liaison->getHoraire(), $date);
  3295.             } else {
  3296.                 if (!$lieu->getHoraire() || $lieu->getHoraire() == []) {
  3297.                     return new Response(json_encode([
  3298.                         'message' => 'Aucun horaire configuré pour ce lieu',
  3299.                         'status' => 400
  3300.                     ]), 400);
  3301.                 }
  3302.                 if (!$publicFunction->calculScheduleFitDate($audio$date$durationnull$lieu)) {
  3303.                     return new Response(json_encode([
  3304.                         'message' => 'Créneau non disponible',
  3305.                         'status' => 400
  3306.                     ]), 400);
  3307.                 }
  3308.                 return $publicFunction->checkIfRemplacant($lieu->getHoraire(), $date);
  3309.             }
  3310.         } else {
  3311.             if (!$liaison || !$liaison->getHoraire() || $liaison->getHoraire() == []) {
  3312.                 return new Response(json_encode([
  3313.                     'message' => 'Aucun horaire configuré',
  3314.                     'status' => 400
  3315.                 ]), 400);
  3316.             }
  3317.             return $publicFunction->checkIfRemplacant($liaison->getHoraire(), $date);
  3318.         }
  3319.     }
  3320.     /**
  3321.      * Crée le rendez-vous en base de données
  3322.      */
  3323.     private function createAppointment(
  3324.         array $data,
  3325.         Client $client,
  3326.         Audio $audio,
  3327.         ?Centre $centre,
  3328.         ?Lieu $lieu,
  3329.         Motif $motif,
  3330.         AudioMotif $audioMotif,
  3331.         \DateTime $date,
  3332.         int $remplacant_id
  3333.     ): Rdv {
  3334.         $rdv = new Rdv();
  3335.         $rdv->setIdClient($client);
  3336.         $rdv->setIdAudio($audio);
  3337.         $rdv->setIdCentre($centre);
  3338.         $rdv->setIdLieu($lieu);
  3339.         $rdv->setIdMotif($motif);
  3340.         $rdv->setDate($date);
  3341.         $rdv->setDateCreation(new \DateTime());
  3342.         // Toujours mettre isMyaudio à true pour les RDV clients via le site
  3343.         $rdv->setIsMyaudio(true);
  3344.         $rdv->setIsRdvLp(isset($data['isRdvLead']));
  3345.         $rdv->setIsRdvRapide(isset($data['isRdvRapide']));
  3346.         $rdv->setIsAbsence(0);
  3347.         $rdv->setCacher(0);
  3348.         // Récupération du dernier test client si disponible
  3349.         $testClient $this->entityManager->getRepository(TestClient::class)
  3350.             ->getLatestTestClient($client);
  3351.         if ($testClient && !$testClient->getRdv()) {
  3352.             $rdv->setTestClient($testClient);
  3353.         }
  3354.         // Gestion proche si spécifié
  3355.         if (isset($data['proche_id'])) {
  3356.             $proche $this->entityManager->getRepository(Proches::class)
  3357.                 ->findOneBy(['id' => $data['proche_id'], 'id_client' => $client]);
  3358.             if ($proche) {
  3359.                 $rdv->setIdProche($proche);
  3360.             }
  3361.         }
  3362.         // Durée : utilise celle du motif par défaut ou celle fournie dans les données
  3363.         $rdv->setDuration($data['duree'] ?? $audioMotif->getDuration());
  3364.         // Couleur personnalisée
  3365.         if (isset($data['color'])) {
  3366.             $rdv->setColor($data['color']);
  3367.         }
  3368.         // Note
  3369.         if (isset($data['note'])) {
  3370.             $rdv->setNote($data['note']);
  3371.         }
  3372.         // État du rendez-vous
  3373.         $etat $this->entityManager->getRepository(EtatRdv::class)
  3374.             ->find($data['etat_id'] ?? 1); // État par défaut : 1
  3375.         if ($etat) {
  3376.             $rdv->setIdEtat($etat);
  3377.         }
  3378.         // Remplaçant si applicable
  3379.         if ($remplacant_id != -1) {
  3380.             $remplacant $this->entityManager->getRepository(Remplacant::class)->find($remplacant_id);
  3381.             if ($remplacant) {
  3382.                 $rdv->setRemplacant($remplacant);
  3383.             }
  3384.         }
  3385.         // Gestion lead
  3386.         if (isset($data['lead'])) {
  3387.             $lead $this->entityManager->getRepository(LeadRdv::class)->find($data['lead']);
  3388.             if ($lead) {
  3389.                 $lead->setRdv($rdv);
  3390.                 $leadStatus $this->entityManager->getRepository(LeadStatus::class)
  3391.                     ->findOneBy(['slug' => 'rdv_valider']);
  3392.                 if ($leadStatus) {
  3393.                     $lead->setLeadStatus($leadStatus);
  3394.                 }
  3395.             }
  3396.         }
  3397.         // Mise à jour du client avec centre et audio
  3398.         $client->setIdCentre($centre);
  3399.         $client->setIdAudio($audio);
  3400.         $this->entityManager->persist($client);
  3401.         $this->entityManager->persist($rdv);
  3402.         $this->entityManager->flush();
  3403.         return $rdv;
  3404.     }
  3405.     /**
  3406.      * Envoie toutes les notifications (email + SMS) au client, audio et admin
  3407.      */
  3408.     private function sendNotifications(Rdv $rdvClient $clientAudio $audioPublicFunction $publicFunction, array $data): void
  3409.     {
  3410.         $date $rdv->getDate();
  3411.         $smsDate $date->format('d-m-Y H:i');
  3412.         $formatter = new IntlDateFormatter(
  3413.             'fr_FR',
  3414.             IntlDateFormatter::FULL,
  3415.             IntlDateFormatter::SHORT,
  3416.             null,
  3417.             IntlDateFormatter::GREGORIAN,
  3418.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  3419.         );
  3420.         $smsDateLongFormat $formatter->format($date);
  3421.         $frenchDate ucfirst(preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat));
  3422.         // === Notification CLIENT ===
  3423.         $this->sendClientNotification($rdv$client$smsDate$smsDateLongFormat$frenchDate$publicFunction$data);
  3424.         // === Notification AUDIO ===
  3425.         if ($audio->getConfirmRdvMail() || $audio->getConfirmRdvSms()) {
  3426.             $this->sendAudioNotification($rdv$client$audio$smsDate$frenchDate$publicFunction$data);
  3427.         }
  3428.         // === Notification ADMIN ===
  3429.         $this->sendAdminNotification($rdv$client$smsDate$frenchDate$publicFunction$data);
  3430.     }
  3431.     /**
  3432.      * Envoie les notifications au client (email + SMS)
  3433.      */
  3434.     private function sendClientNotification(
  3435.         Rdv $rdv,
  3436.         Client $client,
  3437.         string $smsDate,
  3438.         string $smsDateLongFormat,
  3439.         string $frenchDate,
  3440.         PublicFunction $publicFunction,
  3441.         array $data
  3442.     ): void {
  3443.         $centre $rdv->getIdCentre();
  3444.         $params = [
  3445.             'lienModifer' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  3446.             'lienAnnule' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  3447.             'date' => $smsDateLongFormat,
  3448.             'RdvDate' => $smsDateLongFormat,
  3449.             'telCentre' => $centre->getPhone(),
  3450.             'centerName' => $centre->getName(),
  3451.             'prenom' => $client->getName(),
  3452.             'centerAddress' => $centre->getAddress() . ' ' $centre->getPostale() . ' ' $centre->getCity(),
  3453.             'centerPostalCode' => $centre->getPostale(),
  3454.             'motif' => $rdv->getIdMotif()->getTitre(),
  3455.             'centerCity' => $centre->getCity(),
  3456.             'audioName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3457.             'titre' => 'Votre rendez-vous est validé le ' substr($smsDate010) . ' à ' substr($smsDate1115),
  3458.             'frenchDate' => $frenchDate,
  3459.             'heure' => substr($smsDate1115),
  3460.             'clientEmail' => $client->getMail(),
  3461.             'clientPassword' => $data['passwordGenerated'] ?? null,
  3462.             'modifUrl' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  3463.         ];
  3464.         // Email client
  3465.         $templateId = (isset($data['isLead']) && isset($data['passwordGenerated'])) ? 189 181;
  3466.         $subject '✅ Rendez-vous My Audio confirmé le ' $smsDateLongFormat;
  3467.         $publicFunction->sendEmail(
  3468.             $params,
  3469.             $client->getMail(),
  3470.             $client->getName() . ' ' $client->getLastName(),
  3471.             $subject,
  3472.             $templateId
  3473.         );
  3474.         // SMS client
  3475.         $smsMessage "Votre RDV est validé le " substr($smsDate010) . " à " substr($smsDate1115) .
  3476.                       ", en cas d'imprévu contactez votre centre " $centre->getPhone() .
  3477.                       " pour modifier votre consultation.\nNe pas répondre.";
  3478.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$smsMessage$client->getPhone());
  3479.     }
  3480.     /**
  3481.      * Envoie les notifications à l'audioprothésiste (email + SMS)
  3482.      */
  3483.     private function sendAudioNotification(
  3484.         Rdv $rdv,
  3485.         Client $client,
  3486.         Audio $audio,
  3487.         string $smsDate,
  3488.         string $frenchDate,
  3489.         PublicFunction $publicFunction,
  3490.         array $data
  3491.     ): void {
  3492.         $responses = [
  3493.             'rangeAge' => $data['rangeAge'] ?? null,
  3494.             'situations' => (isset($data['situations']) && !empty($data['situations'])) ? implode(", "$data['situations']) : null,
  3495.             'equipeAppareil' => $data['equipe'] ?? null,
  3496.             'durationEquipe' => $data['durationEquipe'] ?? null,
  3497.             'bilanAuditif' => $data['bilanAuditif'] ?? null,
  3498.             'ordonance' => $data['ordonnance'] ?? null,
  3499.             'dateOrdonance' => $data['dateOrdonance'] ?? null,
  3500.             'canMove' => $data['canMove'] ?? null,
  3501.         ];
  3502.         $params = [
  3503.             'lienModifer' => $_ENV['BASE_logiciel'] . 'rdv',
  3504.             'lienAnnule' => $_ENV['BASE_logiciel'] . 'rdv',
  3505.             'date' => substr($smsDate010),
  3506.             'heure' => substr($smsDate1115),
  3507.             'audioproName' => $audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastName(),
  3508.             'phone' => $client->getPhone(),
  3509.             'clientCivilite' => $client->getCivilite(),
  3510.             'clientNom' => $client->getLastname(),
  3511.             'clientPrenom' => $client->getName(),
  3512.             'clientPostal' => $client->getPostal(),
  3513.             'clientMail' => $client->getMail(),
  3514.             'clientPhone' => $client->getPhone(),
  3515.             'motif' => $rdv->getIdMotif()->getTitre(),
  3516.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  3517.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  3518.             'centerName' => $rdv->getIdCentre()->getName(),
  3519.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  3520.             'centerCity' => $rdv->getIdCentre()->getCity(),
  3521.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  3522.             'idPatient' => $client->getId(),
  3523.             'proUrl' => $_ENV['BASE_logiciel'],
  3524.             'frenchDate' => $frenchDate,
  3525.             'responses' => $responses,
  3526.         ];
  3527.         $templateEmail = !empty($data['canMove']) ? 197 182;
  3528.         $mailAudio $audio->getMailNotif() ?? $audio->getMail();
  3529.         $phoneAudio $audio->getPhoneNotif() ?? $audio->getPhone();
  3530.         // Email audio
  3531.         if ($audio->getConfirmRdvMail()) {
  3532.             $subject '✅ Nouveau Rendez-vous My Audio le ' $frenchDate ' à ' substr($smsDate1115);
  3533.             $publicFunction->sendEmail($params$mailAudio$audio->getName() . ' ' $audio->getLastName(), $subject$templateEmail);
  3534.         }
  3535.         // SMS audio
  3536.         if ($audio->getConfirmRdvSms()) {
  3537.             $smsMessage "Vous avez un nouveau RDV le " substr($smsDate010) . " à " substr($smsDate1115) .
  3538.                           ", en cas d'aléas contactez votre patient " $client->getPhone() .
  3539.                           " pour modifier votre consultation.\nNe pas répondre.";
  3540.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$smsMessage$phoneAudio);
  3541.         }
  3542.     }
  3543.     /**
  3544.      * Envoie les notifications à l'admin
  3545.      */
  3546.     private function sendAdminNotification(
  3547.         Rdv $rdv,
  3548.         Client $client,
  3549.         string $smsDate,
  3550.         string $frenchDate,
  3551.         PublicFunction $publicFunction,
  3552.         array $data
  3553.     ): void {
  3554.         $responses = [
  3555.             'rangeAge' => $data['rangeAge'] ?? null,
  3556.             'situations' => (isset($data['situations']) && !empty($data['situations'])) ? implode(", "$data['situations']) : null,
  3557.             'equipeAppareil' => $data['equipe'] ?? null,
  3558.             'durationEquipe' => $data['durationEquipe'] ?? null,
  3559.             'bilanAuditif' => $data['bilanAuditif'] ?? null,
  3560.             'ordonance' => $data['ordonnance'] ?? null,
  3561.             'dateOrdonance' => $data['dateOrdonance'] ?? null,
  3562.             'canMove' => $data['canMove'] ?? null,
  3563.         ];
  3564.         $paramsSourceLead = [
  3565.             'trafficSource' => $data['traffic_source'] ?? null,
  3566.             'articleName' => $data['article_name'] ?? null,
  3567.             'lpVersion' => $data['lp_version'] ?? null,
  3568.         ];
  3569.         $paramsAdmin = [
  3570.             'lienModifer' => $_ENV['BASE_logiciel'] . 'rdv',
  3571.             'lienAnnule' => $_ENV['BASE_logiciel'] . 'rdv',
  3572.             'RdvDate' => substr($smsDate010),
  3573.             'heure' => substr($smsDate1115),
  3574.             'clientMail' => $client->getMail(),
  3575.             'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3576.             'telClient' => $client->getPhone(),
  3577.             'clientNom' => $client->getLastname(),
  3578.             'clientPrenom' => $client->getName(),
  3579.             'clientCivilite' => $client->getCivilite(),
  3580.             'clientPostal' => $client->getPostal(),
  3581.             'clientPhone' => $client->getPhone(),
  3582.             'motif' => $rdv->getIdMotif()->getTitre(),
  3583.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  3584.             'centerName' => $rdv->getIdCentre()->getName(),
  3585.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  3586.             'centerCity' => $rdv->getIdCentre()->getCity(),
  3587.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  3588.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  3589.             'date' => substr($smsDate010),
  3590.             'urlApi' => $_ENV['BASE_API'],
  3591.             'clientId' => $client->getId(),
  3592.             'centerId' => $rdv->getIdCentre()->getId(),
  3593.             'frenchDate' => $frenchDate,
  3594.             'responses' => $responses,
  3595.             'paramsSourceLead' => $paramsSourceLead,
  3596.         ];
  3597.         $subject 'Nouveau RDV MA | RR - ' $rdv->getIdCentre()->getName();
  3598.         $templateEmail = !empty($data['canMove']) ? 190 183;
  3599.         if (!isset($data['isLead'])) {
  3600.             $publicFunction->sendEmail($paramsAdmin'lead.myaudio@gmail.com''my audio'$subject$templateEmail);
  3601.         }
  3602.         $publicFunction->sendEmail($paramsAdmin'contact@myaudio.fr''my audio'$subject$templateEmail);
  3603.     }
  3604.     /**
  3605.      * Synchronise le rendez-vous avec Google Calendar
  3606.      */
  3607.     private function syncGoogleCalendar(Audio $audioRdv $rdvGoogleCalendarService $googleCalendar, array $data): void
  3608.     {
  3609.         try {
  3610.             $synchronisations $this->entityManager->getRepository(SynchronisationSetting::class)
  3611.                 ->findBy(['audio' => $audio->getId()]);
  3612.             $data['rdv'] = $rdv->getId();
  3613.             foreach ($synchronisations as $synchronisation) {
  3614.                 if (!$synchronisation->getIsDeleted()) {
  3615.                     $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  3616.                     $googleCalendar->createEvent($synchronisation$data);
  3617.                 }
  3618.             }
  3619.         } catch (\Exception $e) {
  3620.             $this->logger->error("Erreur synchronisation Google Calendar pour RDV #{$rdv->getId()}: " $e->getMessage());
  3621.         }
  3622.     }
  3623.     /**
  3624.      * @Route("/rdv/{id}/v2", name="getRdvByIDV2", methods={"GET"})
  3625.      *
  3626.      * Version optimisée de getRdvByID
  3627.      * Retourne les informations complètes d'un rendez-vous
  3628.      */
  3629.     public function getRdvByIDV2(int $idRequest $requestPublicFunction $publicFunction): JsonResponse
  3630.     {
  3631.         try {
  3632.             // Validation du token
  3633.             $token $request->query->get('token');
  3634.             if (!$token) {
  3635.                 return new JsonResponse([
  3636.                     'message' => "Aucun token n'a été spécifié",
  3637.                     'status' => 401
  3638.                 ], 401);
  3639.             }
  3640.             $tokenEntity $this->entityManager->getRepository(Token::class)
  3641.                 ->findOneBy(['token' => $token]);
  3642.             if (!$tokenEntity) {
  3643.                 return new JsonResponse([
  3644.                     'message' => "Token invalide. Veuillez vous reconnecter.",
  3645.                     'status' => 404
  3646.                 ], 404);
  3647.             }
  3648.             // Vérification de l'âge du token
  3649.             $dateDiff $tokenEntity->getCreationDate()->diff(new DateTime());
  3650.             if ($dateDiff->7) {
  3651.                 $this->entityManager->remove($tokenEntity);
  3652.                 $this->entityManager->flush();
  3653.                 return new JsonResponse([
  3654.                     'message' => 'Token expiré. Veuillez vous reconnecter.',
  3655.                     'status' => 401
  3656.                 ], 401);
  3657.             }
  3658.             // Récupération du RDV
  3659.             $rdv $this->entityManager->getRepository(Rdv::class)->find($id);
  3660.             if (!$rdv) {
  3661.                 return new JsonResponse([
  3662.                     'message' => "Aucun rendez-vous trouvé avec cet ID",
  3663.                     'status' => 404
  3664.                 ], 404);
  3665.             }
  3666.             // Vérification des droits d'accès
  3667.             $client $tokenEntity->getIdClient();
  3668.             $audio $tokenEntity->getIdAudio();
  3669.             if ($rdv->getIdClient() != $client && $rdv->getIdAudio() != $audio) {
  3670.                 return new JsonResponse([
  3671.                     'message' => "Vous n'êtes pas autorisé à consulter ce rendez-vous",
  3672.                     'status' => 403
  3673.                 ], 403);
  3674.             }
  3675.             // Construction de la réponse
  3676.             $response $this->buildRdvResponse($rdv$publicFunction);
  3677.             return new JsonResponse([
  3678.                 'success' => true,
  3679.                 'rdv' => $response,
  3680.                 'status' => 200
  3681.             ], 200);
  3682.         } catch (\Exception $e) {
  3683.             $this->logger->error("Erreur lors de la récupération du RDV #{$id}: " $e->getMessage());
  3684.             return new JsonResponse([
  3685.                 'success' => false,
  3686.                 'message' => 'Une erreur est survenue lors de la récupération du rendez-vous.',
  3687.                 'error' => $e->getMessage(),
  3688.                 'status' => 500
  3689.             ], 500);
  3690.         }
  3691.     }
  3692.     /**
  3693.      * Construit la réponse complète pour un rendez-vous
  3694.      */
  3695.     private function buildRdvResponse(Rdv $rdvPublicFunction $publicFunction): array
  3696.     {
  3697.         $rdvCentre $rdv->getIdLieu() ?: $rdv->getIdCentre();
  3698.         $audio $rdv->getIdAudio();
  3699.         $centre $rdv->getIdCentre();
  3700.         // Récupération de la liaison audio-centre
  3701.         $liaison null;
  3702.         if ($centre) {
  3703.             $liaison $this->entityManager->getRepository(AudioCentre::class)
  3704.                 ->findOneBy(['id_audio' => $audio'id_centre' => $centre'isConfirmed' => true]);
  3705.         }
  3706.         // Informations de base du RDV
  3707.         $rdvData = [
  3708.             'id' => $rdv->getId(),
  3709.             'date' => $rdv->getDate()->format('Y-m-d H:i:s'),
  3710.             'dateCreation' => $rdv->getDateCreation() ? $rdv->getDateCreation()->format('Y-m-d H:i:s') : null,
  3711.             'duration' => $rdv->getDuration(),
  3712.             'note' => $rdv->getNote(),
  3713.             'comment' => $rdv->getComment(),
  3714.             'review' => $rdv->getReview(),
  3715.             'isMyaudio' => $rdv->getIsMyaudio(),
  3716.             'isRdvLp' => $rdv->getIsRdvLp(),
  3717.             'isRdvRapide' => $rdv->getIsRdvRapide(),
  3718.             'isAbsence' => $rdv->getIsAbsence(),
  3719.             'motif' => [
  3720.                 'id' => $rdv->getIdMotif()->getId(),
  3721.                 'titre' => $rdv->getIdMotif()->getTitre(),
  3722.             ],
  3723.             'etat' => [
  3724.                 'id' => $rdv->getIdEtat()->getId(),
  3725.                 'libelle' => $rdv->getIdEtat()->getLibelle(),
  3726.             ],
  3727.             'client' => $this->buildClientData($rdv),
  3728.             'proche' => $rdv->getIdProche() ? [
  3729.                 'id' => $rdv->getIdProche()->getId(),
  3730.                 'name' => $rdv->getIdProche()->getName(),
  3731.                 'lastname' => $rdv->getIdProche()->getLastname(),
  3732.             ] : null,
  3733.             'testClient' => $rdv->getTestClient() ? [
  3734.                 'result' => $rdv->getTestClient()->getResultTonal(),
  3735.                 'date' => $rdv->getTestClient()->getDate()->format('Y-m-d H:i:s'),
  3736.                 'device' => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  3737.             ] : null,
  3738.             'audio' => $this->buildAudioData($rdv$publicFunction),
  3739.             'centre' => $this->buildCentreData($rdv$rdvCentre$liaison$publicFunction),
  3740.             'remplacant' => $rdv->getRemplacant() ? [
  3741.                 'id' => $rdv->getRemplacant()->getId(),
  3742.                 'civilite' => $rdv->getRemplacant()->getCivilite(),
  3743.                 'name' => $rdv->getRemplacant()->getName(),
  3744.                 'lastname' => $rdv->getRemplacant()->getLastname(),
  3745.                 'imgUrl' => $rdv->getRemplacant()->getImgUrl(),
  3746.             ] : null,
  3747.         ];
  3748.         return $rdvData;
  3749.     }
  3750.     /**
  3751.      * Construit les données du client
  3752.      */
  3753.     private function buildClientData(Rdv $rdv): ?array
  3754.     {
  3755.         $client $rdv->getIdClient() ?: $rdv->getIdClientTemp();
  3756.         if (!$client) {
  3757.             return null;
  3758.         }
  3759.         return [
  3760.             'id' => $client->getId(),
  3761.             'civilite' => $client->getCivilite(),
  3762.             'name' => $client->getName(),
  3763.             'lastname' => $client->getLastname(),
  3764.             'mail' => $client->getMail(),
  3765.             'phone' => $client->getPhone(),
  3766.             'address' => $client->getAddress(),
  3767.             'postal' => $client->getPostal(),
  3768.             'city' => $client->getCity(),
  3769.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format('Y-m-d') : null,
  3770.         ];
  3771.     }
  3772.     /**
  3773.      * Construit les données de l'audio
  3774.      */
  3775.     private function buildAudioData(Rdv $rdvPublicFunction $publicFunction): array
  3776.     {
  3777.         $audio $rdv->getIdAudio();
  3778.         $remplacant $rdv->getRemplacant();
  3779.         // Récupération des reviews audio
  3780.         $audioRdvs $this->entityManager->getRepository(Rdv::class)
  3781.             ->findBy(['id_audio' => $audio->getId()]);
  3782.         $reviewsAudio array_filter($audioRdvs, function($r) {
  3783.             return $r->getReview() !== null && $r->getComment() !== null;
  3784.         });
  3785.         // Motifs
  3786.         $motifs $this->entityManager->getRepository(AudioMotif::class)
  3787.             ->findBy(['id_audio' => $audio->getId()]);
  3788.         $motifsData array_map(function($motif) {
  3789.             return [
  3790.                 'id' => $motif->getIdMotif()->getId(),
  3791.                 'titre' => $motif->getIdMotif()->getTitre(),
  3792.                 'consigne' => $motif->getConsigne(),
  3793.                 'duration' => $motif->getDuration(),
  3794.             ];
  3795.         }, $motifs);
  3796.         // Spécialités
  3797.         $specialities $this->entityManager->getRepository(AudioSpecialite::class)
  3798.             ->findBy(['id_audio' => $audio->getId()]);
  3799.         $specialitiesData array_map(function($spec) {
  3800.             return [
  3801.                 'id' => $spec->getIdSpecialite()->getId(),
  3802.                 'titre' => $spec->getIdSpecialite()->getLibelle(),
  3803.             ];
  3804.         }, $specialities);
  3805.         return [
  3806.             'id' => $remplacant $remplacant->getId() : $audio->getId(),
  3807.             'civilite' => $remplacant $remplacant->getCivilite() : $audio->getCivilite(),
  3808.             'name' => $remplacant $remplacant->getName() : $audio->getName(),
  3809.             'lastname' => $remplacant $remplacant->getLastname() : $audio->getLastname(),
  3810.             'imgUrl' => $remplacant $remplacant->getImgUrl() : $audio->getImgUrl(),
  3811.             'mail' => $remplacant $remplacant->getMail() : $audio->getMail(),
  3812.             'phone' => $remplacant $remplacant->getPhone() : $audio->getPhone(),
  3813.             'adeli' => $audio->getAdeli(),
  3814.             'pin' => $audio->getPin(),
  3815.             'description' => $audio->getDescription(),
  3816.             'averageRating' => $publicFunction->calculateRating($reviewsAudio),
  3817.             'nbrReview' => count($reviewsAudio),
  3818.             'motifs' => array_values($motifsData),
  3819.             'specialities' => array_values($specialitiesData),
  3820.         ];
  3821.     }
  3822.     /**
  3823.      * Construit les données du centre
  3824.      */
  3825.     private function buildCentreData(Rdv $rdv$rdvCentre, ?AudioCentre $liaisonPublicFunction $publicFunction): array
  3826.     {
  3827.         // Récupération des reviews centre
  3828.         $centreRdvs $this->entityManager->getRepository(Rdv::class)
  3829.             ->findBy($rdv->getIdCentre() ? ['id_centre' => $rdvCentre->getId()] : ['id_lieu' => $rdvCentre->getId()]);
  3830.         $reviewsCentre array_filter($centreRdvs, function($r) {
  3831.             return $r->getReview() !== null && $r->getComment() !== null;
  3832.         });
  3833.         // Accès centre
  3834.         $accessCentre $this->entityManager->getRepository(AccessCentre::class)
  3835.             ->findOneBy($rdv->getIdCentre() ? ['id_centre' => $rdvCentre] : ['id_lieu' => $rdvCentre]);
  3836.         // Prestations
  3837.         if ($rdv->getIdCentre()) {
  3838.             $prestations $this->entityManager->getRepository(CentrePrestation::class)
  3839.                 ->findBy(['id_centre' => $rdvCentre->getId()]);
  3840.         } else {
  3841.             $prestations $this->entityManager->getRepository(LieuPrestation::class)
  3842.                 ->findBy(['id_lieu' => $rdvCentre]);
  3843.         }
  3844.         $prestationsData array_map(function($prest) {
  3845.             return [
  3846.                 'id' => $prest->getIdPrestation()->getId(),
  3847.                 'titre' => $prest->getIdPrestation()->getLibelle(),
  3848.             ];
  3849.         }, $prestations);
  3850.         // Mutuelles (uniquement pour centres)
  3851.         $mutuellesData = [];
  3852.         if ($rdv->getIdCentre()) {
  3853.             $mutuelles $this->entityManager->getRepository(CentreMutuelle::class)
  3854.                 ->findBy(['id_centre' => $rdvCentre]);
  3855.             $mutuellesData array_map(function($mut) {
  3856.                 return [
  3857.                     'id' => $mut->getIdMutuelle()->getId(),
  3858.                     'titre' => $mut->getIdMutuelle()->getLibelle(),
  3859.                 ];
  3860.             }, $mutuelles);
  3861.         }
  3862.         // Tiers
  3863.         if ($rdv->getIdCentre()) {
  3864.             $tiers $this->entityManager->getRepository(CentreTier::class)
  3865.                 ->findBy(['id_centre' => $rdvCentre->getId()]);
  3866.         } else {
  3867.             $tiers $this->entityManager->getRepository(LieuTier::class)
  3868.                 ->findBy(['id_lieu' => $rdvCentre]);
  3869.         }
  3870.         $tiersData array_map(function($tier) {
  3871.             return [
  3872.                 'id' => $tier->getIdTier()->getId(),
  3873.                 'titre' => $tier->getIdTier()->getLibelle(),
  3874.             ];
  3875.         }, $tiers);
  3876.         // Horaire
  3877.         $schedule null;
  3878.         if ($rdv->getIdAudio()->getIsIndie() == false) {
  3879.             $schedule $rdv->getIdCentre() ? $rdv->getIdCentre()->getHoraire() : null;
  3880.         } else {
  3881.             $schedule $rdv->getIdLieu() ? $rdv->getIdLieu()->getHoraire() : ($liaison $liaison->getHoraire() : null);
  3882.         }
  3883.         return [
  3884.             'id' => $rdvCentre->getId(),
  3885.             'audio_id' => $rdvCentre->getIdGerant()->getId(),
  3886.             'name' => $rdvCentre->getName(),
  3887.             'imgUrl' => $rdvCentre->getImgUrl(),
  3888.             'isRdvDomicile' => $rdv->getIdCentre() ? $rdvCentre->getIsRdvDomicile() : $rdv->getIdAudio()->getIsRdvDomicileIndie(),
  3889.             'address' => $rdvCentre->getAddress(),
  3890.             'postal' => $rdvCentre->getPostale(),
  3891.             'city' => $rdvCentre->getCity(),
  3892.             'finess' => $rdvCentre->getFiness(),
  3893.             'siret' => $rdvCentre->getSiret(),
  3894.             'website' => $rdvCentre->getWebsite(),
  3895.             'phone' => $rdvCentre->getPhone(),
  3896.             'isHandicap' => $rdvCentre->getIsHandicap(),
  3897.             'longitude' => $rdvCentre->getLongitude(),
  3898.             'latitude' => $rdvCentre->getLatitude(),
  3899.             'description' => $rdv->getIdCentre() ? $rdv->getIdCentre()->getDescription() : null,
  3900.             'averageRating' => $publicFunction->calculateRating($reviewsCentre),
  3901.             'nbrReview' => count($reviewsCentre),
  3902.             'isLieu' => $rdv->getIdLieu() !== null,
  3903.             'schedule' => $schedule,
  3904.             'access' => $accessCentre ? [
  3905.                 'tram' => $accessCentre->getTram(),
  3906.                 'rer' => $accessCentre->getRer(),
  3907.                 'metro' => $accessCentre->getMetro(),
  3908.                 'bus' => $accessCentre->getBus(),
  3909.                 'parkingPublic' => $accessCentre->getParkingPublic(),
  3910.                 'parkingPrivate' => $accessCentre->getParkingPrivate(),
  3911.                 'other' => $accessCentre->getOther(),
  3912.             ] : null,
  3913.             'prestations' => array_values($prestationsData),
  3914.             'mutuelles' => array_values($mutuellesData),
  3915.             'tiers' => array_values($tiersData),
  3916.         ];
  3917.     }
  3918.     /**
  3919.      * @Route("/rdv/{id}/v2", name="editRdvByIDV2", methods={"PUT", "PATCH"})
  3920.      *
  3921.      * Version optimisée de editRdvByID pour les clients
  3922.      * Gestion complète: modification RDV, notifications email/SMS, Google Calendar
  3923.      */
  3924.     public function editRdvByIDV2(
  3925.         int $id,
  3926.         Request $request,
  3927.         PublicFunction $publicFunction,
  3928.         GoogleCalendarService $googleCalendar
  3929.     ): JsonResponse {
  3930.         try {
  3931.             $data json_decode($request->getContent(), true);
  3932.             // Validation du token et récupération du client
  3933.             $validationResult $this->validateTokenAndGetClient($data);
  3934.             if ($validationResult instanceof Response) {
  3935.                 return new JsonResponse(json_decode($validationResult->getContent(), true), $validationResult->getStatusCode());
  3936.             }
  3937.             ['client' => $client] = $validationResult;
  3938.             // Récupération du RDV
  3939.             $rdv $this->entityManager->getRepository(Rdv::class)->find($id);
  3940.             if (!$rdv) {
  3941.                 return new JsonResponse([
  3942.                     'message' => "Aucun rendez-vous trouvé avec cet ID",
  3943.                     'status' => 404
  3944.                 ], 404);
  3945.             }
  3946.             // Vérification des droits (seulement le client peut modifier son RDV)
  3947.             if ($rdv->getIdClient() != $client) {
  3948.                 return new JsonResponse([
  3949.                     'message' => "Vous n'êtes pas autorisé à modifier ce rendez-vous",
  3950.                     'status' => 403
  3951.                 ], 403);
  3952.             }
  3953.             // Sauvegarde des anciennes valeurs pour les notifications
  3954.             $oldDate $rdv->getDate();
  3955.             $oldDuration $rdv->getDuration();
  3956.             // Traitement de la modification
  3957.             $isModified false;
  3958.             $isCancelled false;
  3959.             // Modification de la date
  3960.             if (isset($data['date'])) {
  3961.                 $newDate \DateTime::createFromFormat("d/m/Y H:i"$data['date']);
  3962.                 if (!$newDate) {
  3963.                     return new JsonResponse([
  3964.                         'message' => 'Format de date invalide. Utilisez le format: d/m/Y H:i',
  3965.                         'status' => 400
  3966.                     ], 400);
  3967.                 }
  3968.                 // Vérification de la disponibilité
  3969.                 $audioMotif $this->entityManager->getRepository(AudioMotif::class)
  3970.                     ->findOneBy(['id_audio' => $rdv->getIdAudio(), 'id_motif' => $rdv->getIdMotif()]);
  3971.                 if (!$audioMotif) {
  3972.                     return new JsonResponse([
  3973.                         'message' => "Le motif n'est plus disponible pour cet audioprothésiste",
  3974.                         'status' => 400
  3975.                     ], 400);
  3976.                 }
  3977.                 // Vérification qu'il n'y a pas déjà un RDV à cette nouvelle date
  3978.                 $existingRdv $this->entityManager->getRepository(Rdv::class)
  3979.                     ->findOneBy([
  3980.                         'date' => $newDate,
  3981.                         'id_audio' => $rdv->getIdAudio(),
  3982.                         'id_centre' => $rdv->getIdCentre(),
  3983.                         'id_lieu' => $rdv->getIdLieu(),
  3984.                     ]);
  3985.                 if ($existingRdv && $existingRdv->getId() !== $rdv->getId()) {
  3986.                     return new JsonResponse([
  3987.                         'message' => 'Un rendez-vous existe déjà à ce créneau',
  3988.                         'status' => 409
  3989.                     ], 409);
  3990.                 }
  3991.                 $rdv->setDateOldRdv($oldDate);
  3992.                 $rdv->setDate($newDate);
  3993.                 $isModified true;
  3994.             }
  3995.             // Modification de la durée
  3996.             if (isset($data['duree']) && $data['duree'] !== $oldDuration) {
  3997.                 $rdv->setDuration($data['duree']);
  3998.                 $isModified true;
  3999.             }
  4000.             // Modification de la note
  4001.             if (isset($data['note'])) {
  4002.                 $rdv->setNote($data['note']);
  4003.             }
  4004.             // Gestion de l'annulation (état 2 = annulé)
  4005.             if (isset($data['etat_id']) && $data['etat_id'] == 2) {
  4006.                 $etat $this->entityManager->getRepository(EtatRdv::class)->find(2);
  4007.                 if ($etat) {
  4008.                     $rdv->setIdEtat($etat);
  4009.                     $isCancelled true;
  4010.                     // Suppression des événements Google Calendar
  4011.                     $this->deleteGoogleCalendarEvents($rdv$googleCalendar);
  4012.                 }
  4013.             }
  4014.             // Persistance des modifications
  4015.             $rdv->setGoogleAgendaImported(false);
  4016.             $this->entityManager->flush();
  4017.             // Envoi des notifications
  4018.             if ($isModified && !$isCancelled) {
  4019.                 $this->sendModificationNotifications($rdv$client$oldDate$publicFunction$data);
  4020.                 $this->updateGoogleCalendarEvents($rdv$googleCalendar$data);
  4021.             } elseif ($isCancelled) {
  4022.                 $this->sendCancellationNotifications($rdv$client$publicFunction$data);
  4023.             }
  4024.             // Réponse
  4025.             return new JsonResponse([
  4026.                 'success' => true,
  4027.                 'message' => $isCancelled 'Rendez-vous annulé avec succès' 'Rendez-vous modifié avec succès',
  4028.                 'rdv' => [
  4029.                     'id' => $rdv->getId(),
  4030.                     'date' => $rdv->getDate()->format('Y-m-d H:i:s'),
  4031.                     'duration' => $rdv->getDuration(),
  4032.                     'note' => $rdv->getNote(),
  4033.                     'etat' => [
  4034.                         'id' => $rdv->getIdEtat()->getId(),
  4035.                         'libelle' => $rdv->getIdEtat()->getLibelle(),
  4036.                     ],
  4037.                 ],
  4038.                 'status' => 200
  4039.             ], 200);
  4040.         } catch (\Exception $e) {
  4041.             $this->logger->error("Erreur lors de la modification du RDV #{$id}: " $e->getMessage());
  4042.             return new JsonResponse([
  4043.                 'success' => false,
  4044.                 'message' => 'Une erreur est survenue lors de la modification du rendez-vous.',
  4045.                 'error' => $e->getMessage(),
  4046.                 'status' => 500
  4047.             ], 500);
  4048.         }
  4049.     }
  4050.     /**
  4051.      * Envoie les notifications de modification de RDV
  4052.      */
  4053.     private function sendModificationNotifications(
  4054.         Rdv $rdv,
  4055.         Client $client,
  4056.         \DateTime $oldDate,
  4057.         PublicFunction $publicFunction,
  4058.         array $data
  4059.     ): void {
  4060.         $date $rdv->getDate();
  4061.         $smsDate $date->format('d-m-Y H:i');
  4062.         $formatter = new IntlDateFormatter(
  4063.             'fr_FR',
  4064.             IntlDateFormatter::FULL,
  4065.             IntlDateFormatter::SHORT,
  4066.             null,
  4067.             IntlDateFormatter::GREGORIAN,
  4068.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  4069.         );
  4070.         $smsDateLongFormat $formatter->format($date);
  4071.         $frenchDate ucfirst(preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat));
  4072.         // Notification CLIENT
  4073.         $paramsClient = [
  4074.             'lienModifer' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  4075.             'lienAnnule' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  4076.             'date' => $smsDateLongFormat,
  4077.             'heure' => substr($smsDate1115),
  4078.             'motif' => $rdv->getIdMotif()->getTitre(),
  4079.             'centerName' => $rdv->getIdCentre()->getName(),
  4080.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4081.             'centerPostalCode' => $rdv->getIdCentre()->getPostale(),
  4082.             'audioMail' => $rdv->getIdAudio()->getMail(),
  4083.             'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4084.             'centerCity' => $rdv->getIdCentre()->getCity(),
  4085.             'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4086.             'titre' => 'Votre rendez-vous est modifié pour le',
  4087.             'frenchDate' => $frenchDate,
  4088.         ];
  4089.         $subject "🔀 Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  4090.         $publicFunction->sendEmail(
  4091.             $paramsClient,
  4092.             $client->getMail(),
  4093.             $client->getName() . ' ' $client->getLastName(),
  4094.             $subject,
  4095.             184
  4096.         );
  4097.         // SMS client si demandé
  4098.         if (isset($data['sms']) && $data['sms']) {
  4099.             $smsMessage "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) .
  4100.                           ", en cas d'imprévu contactez votre centre " $rdv->getIdCentre()->getPhone() .
  4101.                           " pour modifier votre consultation.\nNe pas répondre.";
  4102.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$smsMessage$client->getPhone());
  4103.         }
  4104.         // Notification AUDIO
  4105.         $audio $rdv->getIdAudio();
  4106.         if ($audio->getModifRdvMail() || $audio->getModifRdvSms()) {
  4107.             $paramsAudio = [
  4108.                 'lienModifer' => $_ENV['BASE_logiciel'] . 'rdv',
  4109.                 'lienAnnule' => $_ENV['BASE_logiciel'] . 'rdv',
  4110.                 'date' => substr($smsDate010),
  4111.                 'frenchDate' => $frenchDate,
  4112.                 'heure' => substr($smsDate1115),
  4113.                 'motif' => $rdv->getIdMotif()->getTitre(),
  4114.                 'clientPhone' => $client->getPhone(),
  4115.                 'clientNom' => $client->getLastname(),
  4116.                 'clientPrenom' => $client->getName(),
  4117.                 'clientCivilite' => $client->getCivilite(),
  4118.                 'clientPostal' => $client->getPostal(),
  4119.                 'clientMail' => $client->getMail(),
  4120.                 'centerName' => $rdv->getIdCentre()->getName(),
  4121.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4122.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  4123.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4124.                 'idPatient' => $client->getId(),
  4125.                 'proUrl' => $_ENV['BASE_logiciel'],
  4126.                 'audioproName' => $audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastName(),
  4127.                 'titre' => 'Votre rendez-vous est modifié pour le :'
  4128.             ];
  4129.             $mailAudio $audio->getMailNotif() ?? $audio->getMail();
  4130.             if ($audio->getModifRdvMail()) {
  4131.                 $subjectAudio "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  4132.                 $publicFunction->sendEmail($paramsAudio$mailAudio$audio->getName() . ' ' $audio->getLastName(), $subjectAudio186);
  4133.             }
  4134.         }
  4135.     }
  4136.     /**
  4137.      * Envoie les notifications d'annulation de RDV
  4138.      */
  4139.     private function sendCancellationNotifications(
  4140.         Rdv $rdv,
  4141.         Client $client,
  4142.         PublicFunction $publicFunction,
  4143.         array $data
  4144.     ): void {
  4145.         $date $rdv->getDate();
  4146.         $smsDate $date->format('d-m-Y H:i');
  4147.         // Notification CLIENT
  4148.         $paramsClient = [
  4149.             'date' => substr($smsDate010),
  4150.             'lien' => $_ENV['BASE_client'] . 'search',
  4151.             'heure' => substr($smsDate1115),
  4152.             'patientName' => $client->getLastName(),
  4153.             'titre' => 'Votre rendez-vous est annulé :',
  4154.             'centerName' => $rdv->getIdCentre()->getName(),
  4155.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4156.             'centerCity' => $rdv->getIdCentre()->getCity(),
  4157.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4158.             'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4159.             'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4160.             'audioMail' => $rdv->getIdAudio()->getMail(),
  4161.             'motif' => $rdv->getIdMotif()->getTitre(),
  4162.         ];
  4163.         $subject "❌ Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  4164.         $publicFunction->sendEmail($paramsClient$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  4165.         // SMS client si demandé
  4166.         if (isset($data['sms']) && $data['sms']) {
  4167.             $smsMessage "Votre RDV a été annulé, contactez votre centre " $rdv->getIdCentre()->getPhone() .
  4168.                           " pour prendre un autre RDV.\nNe pas répondre.";
  4169.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$smsMessage$client->getPhone());
  4170.         }
  4171.         // Notification AUDIO
  4172.         $audio $rdv->getIdAudio();
  4173.         if ($audio->getModifRdvMail()) {
  4174.             $paramsAudio = [
  4175.                 'date' => substr($smsDate010),
  4176.                 'lien' => $_ENV['BASE_client'] . 'search',
  4177.                 'heure' => substr($smsDate1115),
  4178.                 'patientName' => $client->getLastName(),
  4179.                 'titre' => 'Votre rendez-vous est annulé :',
  4180.                 'centerName' => $rdv->getIdCentre()->getName(),
  4181.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4182.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  4183.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4184.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4185.                 'audioproName' => $audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastName(),
  4186.                 'audioMail' => $audio->getMail(),
  4187.                 'motif' => $rdv->getIdMotif()->getTitre(),
  4188.             ];
  4189.             $mailAudio $audio->getMailNotif() ?? $audio->getMail();
  4190.             $subjectAudio "❌ Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  4191.             $publicFunction->sendEmail($paramsAudio$mailAudio$audio->getName() . ' ' $audio->getLastName(), $subjectAudio188);
  4192.         }
  4193.     }
  4194.     /**
  4195.      * Supprime les événements Google Calendar associés au RDV
  4196.      */
  4197.     private function deleteGoogleCalendarEvents(Rdv $rdvGoogleCalendarService $googleCalendar): void
  4198.     {
  4199.         try {
  4200.             $rdvEvents $this->entityManager->getRepository(RdvEvent::class)
  4201.                 ->findBy(['rdv' => $rdv]);
  4202.             foreach ($rdvEvents as $rdvEvent) {
  4203.                 $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4204.                 $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  4205.                 $this->entityManager->remove($rdvEvent);
  4206.             }
  4207.             $this->entityManager->flush();
  4208.         } catch (\Exception $e) {
  4209.             $this->logger->error("Erreur suppression événements Google Calendar pour RDV #{$rdv->getId()}: " $e->getMessage());
  4210.         }
  4211.     }
  4212.     /**
  4213.      * Met à jour les événements Google Calendar
  4214.      */
  4215.     private function updateGoogleCalendarEvents(Rdv $rdvGoogleCalendarService $googleCalendar, array $data): void
  4216.     {
  4217.         try {
  4218.             $rdvEvents $this->entityManager->getRepository(RdvEvent::class)
  4219.                 ->findBy(['rdv' => $rdv]);
  4220.             $data['rdv'] = $rdv->getId();
  4221.             if ($rdv->getIdClient() !== null) {
  4222.                 $data['client_id'] = $rdv->getIdClient()->getId();
  4223.             }
  4224.             foreach ($rdvEvents as $rdvEvent) {
  4225.                 $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4226.                 $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  4227.             }
  4228.         } catch (\Exception $e) {
  4229.             $this->logger->error("Erreur mise à jour événements Google Calendar pour RDV #{$rdv->getId()}: " $e->getMessage());
  4230.         }
  4231.     }
  4232.     /**
  4233.      * @Route("/rdv/{id}/trusteduser", name="contactTrustedUser", methods={"POST"})
  4234.      */
  4235.     public function contactTrustedUser(Request $requestPublicFunction $publicFunction)
  4236.     {
  4237.         $pastDate $rdv->getDate();
  4238.         $data json_decode($request->getContent(), true);
  4239.         $entityManager $this->getDoctrine()->getManager();
  4240.         if (!isset($data["token"])) {
  4241.             return new Response(json_encode([
  4242.                 "message" => "Pas de token n'a été spécifié",
  4243.                 "status" => 401,
  4244.             ]), 401);
  4245.         }
  4246.         /** @var Token */
  4247.         $token $this->getDoctrine()
  4248.             ->getRepository(Token::class)
  4249.             ->findOneBy(['token' => $data["token"]]);
  4250.         if (!$token) {
  4251.             return new Response(json_encode([
  4252.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4253.                 "status" => 404,
  4254.             ]), 404);
  4255.         }
  4256.         // get token age
  4257.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4258.         // if the token if older than 7 days
  4259.         if ($dateDiff->7) {
  4260.             $entityManager->remove($token);
  4261.             $entityManager->flush();
  4262.             return $this->json([
  4263.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4264.                 'path' => 'src/Controller/ClientController.php',
  4265.                 "status" => 401,
  4266.             ], 401);
  4267.         }
  4268.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  4269.             return new Response(json_encode([
  4270.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  4271.                 "status" => 404,
  4272.             ]), 404);
  4273.         }
  4274.         if (isset($data["date"])) {
  4275.             // remove the taken schedule by rdv to make sure there is no overlap
  4276.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4277.             $audioMotif $this->getDoctrine()
  4278.                 ->getRepository(AudioMotif::class)
  4279.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  4280.             if ($audioMotif == null) {
  4281.                 return new Response(json_encode(([
  4282.                     'message' => 'Error, no motif of this id found at this audio',
  4283.                     'path' => 'src/Controller/RdvController.php',
  4284.                     "status" => 400,
  4285.                 ])), 400);
  4286.             }
  4287.             if ($rdv->getIdAudio()->getIsIndie()) {
  4288.                 if ($rdv->getIdCentre()) {
  4289.                     // regular centre audio indie
  4290.                     /** @var AudioCentre */
  4291.                     $liaison $this->getDoctrine()
  4292.                         ->getRepository(AudioCentre::class)
  4293.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  4294.                     if ($liaison == null) {
  4295.                         return new Response(json_encode(([
  4296.                             'message' => 'Error, audio isnt part of the centre',
  4297.                             'path' => 'src/Controller/RdvController.php',
  4298.                             "status" => 400,
  4299.                         ])), 400);
  4300.                     }
  4301.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  4302.                         return new Response(json_encode(([
  4303.                             'message' => 'Error, no horaire found for this audio',
  4304.                             'path' => 'src/Controller/RdvController.php',
  4305.                             "status" => 400,
  4306.                         ])), 400);
  4307.                     }
  4308.                     // if ($publicFunction->calculScheduleFitDate($liaison->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), $rdv->getIdCentre()) == false) {
  4309.                     //     return new Response(json_encode(([
  4310.                     //         'message' => 'Error, no timestamp found at this time',
  4311.                     //         'path' => 'src/Controller/RdvController.php',
  4312.                     //         "status" => 400,
  4313.                     //     ])),400);
  4314.                     // }
  4315.                 } else {
  4316.                     // lieu audio indie
  4317.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  4318.                         return new Response(json_encode(([
  4319.                             'message' => 'Error, no horaire found for this audio',
  4320.                             'path' => 'src/Controller/RdvController.php',
  4321.                             "status" => 400,
  4322.                         ])), 400);
  4323.                     }
  4324.                     // if ($publicFunction->calculScheduleFitDate($rdv->getIdLieu()->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), null, $rdv->getIdLieu()) == false) {
  4325.                     //     return new Response(json_encode(([
  4326.                     //         'message' => 'Error, no timestamp found at this time',
  4327.                     //         'path' => 'src/Controller/RdvController.php',
  4328.                     //         "status" => 400,
  4329.                     //     ])),400);
  4330.                     // }
  4331.                 }
  4332.             } else {
  4333.                 // regular centre
  4334.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  4335.                     return new Response(json_encode(([
  4336.                         'message' => 'Error, no horaire found for this audio',
  4337.                         'path' => 'src/Controller/RdvController.php',
  4338.                         "status" => 400,
  4339.                     ])), 400);
  4340.                 }
  4341.                 // if ($publicFunction->calculScheduleFitDate($rdv->getIdCentre()->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), $rdv->getIdCentre()) == false) {
  4342.                 //     return new Response(json_encode(([
  4343.                 //         'message' => 'Error, no timestamp found at this time',
  4344.                 //         'path' => 'src/Controller/RdvController.php',
  4345.                 //         "status" => 400,
  4346.                 //     ])),400);
  4347.                 // }
  4348.             }
  4349.             $rdv->setDate($date);
  4350.         }
  4351.         $date $rdv->getDate();
  4352.         $smsDate $date->format('d-m-Y H:i');
  4353.         $oldDate $pastDate->format('d-m-Y H:i');
  4354.         $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>");
  4355.         return new Response(json_encode(([
  4356.             "id" => $rdv->getId(),
  4357.             "status" => 200,
  4358.         ])));
  4359.     }
  4360.     /**
  4361.      * @Route("/rdv/{id}", name="editRdvByID", methods={"PUT"})
  4362.      */
  4363.     public function editRdvByID(PublicFunction $publicFunctionRdv $rdvRequest $requestGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  4364.     {
  4365.         $pastDate $rdv->getDate();
  4366.         $pastDuration $rdv->getDuration();
  4367.         $data json_decode($request->getContent(), true);
  4368.         $entityManager $this->getDoctrine()->getManager();
  4369.         if (!isset($data["token"])) {
  4370.             return new Response(json_encode([
  4371.                 "message" => "Pas de token n'a été spécifié",
  4372.                 "status" => 401,
  4373.             ]), 401);
  4374.         }
  4375.         /** @var Token */
  4376.         $token $this->getDoctrine()
  4377.             ->getRepository(Token::class)
  4378.             ->findOneBy(['token' => $data["token"]]);
  4379.         if (!$token) {
  4380.             return new Response(json_encode([
  4381.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4382.                 "status" => 404,
  4383.             ]), 404);
  4384.         }
  4385.         // get token age
  4386.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4387.         // if the token if older than 7 days
  4388.         if ($dateDiff->7) {
  4389.             $entityManager->remove($token);
  4390.             $entityManager->flush();
  4391.             return $this->json([
  4392.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4393.                 'path' => 'src/Controller/ClientController.php',
  4394.                 "status" => 401,
  4395.             ], 401);
  4396.         }
  4397.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  4398.             return new Response(json_encode([
  4399.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  4400.                 "status" => 404,
  4401.             ]), 404);
  4402.         }
  4403.         if (isset($data["etat_id"])) {
  4404.             $etat $this->getDoctrine()
  4405.                 ->getRepository(EtatRdv::class)
  4406.                 ->findOneBy(['id' => $data["etat_id"]]);
  4407.             if ($etat == null) {
  4408.                 return new Response(json_encode(([
  4409.                     'message' => 'Error, no etat found at this id',
  4410.                     'path' => 'src/Controller/TrustedUserController.php',
  4411.                     "status" => 400,
  4412.                 ])), 400);
  4413.             }
  4414.             $rdv->setIdEtat($etat);
  4415.         }
  4416.         if (isset($data["audio_id"])) {
  4417.             $audio $this->getDoctrine()
  4418.                 ->getRepository(Audio::class)
  4419.                 ->findOneBy(['id' => $data["audio_id"]]);
  4420.             if ($audio == null) {
  4421.                 return new Response(json_encode(([
  4422.                     'message' => 'Error, no audio found at this id',
  4423.                     'path' => 'src/Controller/TrustedUserController.php',
  4424.                     "status" => 400,
  4425.                 ])), 400);
  4426.             }
  4427.             $rdv->setIdAudio($audio);
  4428.         }
  4429.         if (isset($data["motif_id"])) {
  4430.             $motif $this->getDoctrine()
  4431.                 ->getRepository(Motif::class)
  4432.                 ->find($data["motif_id"]);
  4433.             if ($motif == null) {
  4434.                 return new Response(json_encode(([
  4435.                     'message' => 'Error, no motif found at this id',
  4436.                     'path' => 'src/Controller/TrustedUserController.php',
  4437.                     "status" => 400,
  4438.                 ])), 400);
  4439.             }
  4440.             $rdv->setIdMotif($motif);
  4441.         }
  4442.         if (isset($data["client_id"])) {
  4443.             $client $this->getDoctrine()
  4444.                 ->getRepository(Client::class)
  4445.                 ->findOneBy(['id' => $data["client_id"]]);
  4446.             if ($client == null) {
  4447.                 return new Response(json_encode(([
  4448.                     'message' => 'Error, no client found at this id',
  4449.                     'path' => 'src/Controller/TrustedUserController.php',
  4450.                     "status" => 400,
  4451.                 ])), 400);
  4452.             }
  4453.             $rdv->setIdClient($client);
  4454.         }
  4455.         // set client status
  4456.         if (isset($data["client_status_id"])) {
  4457.             $status $this->getDoctrine()
  4458.                 ->getRepository(ClientStatus::class)
  4459.                 ->findOneBy(['id' => $data["client_status_id"]]);
  4460.             if ($status == null) {
  4461.                 return new Response(json_encode(([
  4462.                     'message' => 'Error, no status found at this id',
  4463.                     'path' => 'src/Controller/TrustedUserController.php',
  4464.                     "status" => 400,
  4465.                 ])), 400);
  4466.             }
  4467.             $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  4468.             $client->setClientStatus($status);
  4469.             $client->setLastUpdateStatus(new \DateTimeImmutable);
  4470.         }
  4471.         if (isset($data["date"])) {
  4472.             $submittedDate $data['date'] ?? null;
  4473.             $newDate \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4474.             $currentDate $rdv->getDate();
  4475.             if (!$currentDate || $currentDate->format('d/m/Y H:i') !== $newDate->format('d/m/Y H:i')) {
  4476.                 $rdv->setDateOldRdv($currentDate);
  4477.             }
  4478.             // remove the taken schedule by rdv to make sure there is no overlap
  4479.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4480.             $dateInput \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4481.             $audioMotif $this->getDoctrine()
  4482.                 ->getRepository(AudioMotif::class)
  4483.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  4484.             if ($audioMotif == null) {
  4485.                 return new Response(json_encode(([
  4486.                     'message' => 'Error, no motif of this id found at this audio',
  4487.                     'path' => 'src/Controller/RdvController.php',
  4488.                     "status" => 400,
  4489.                 ])), 400);
  4490.             }
  4491.             if ($rdv->getIdAudio()->getIsIndie()) {
  4492.                 if ($rdv->getIdCentre()) {
  4493.                     // regular centre audio indie
  4494.                     /** @var AudioCentre */
  4495.                     $liaison $this->getDoctrine()
  4496.                         ->getRepository(AudioCentre::class)
  4497.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  4498.                     if ($liaison == null) {
  4499.                         return new Response(json_encode(([
  4500.                             'message' => 'Error, audio isnt part of the centre',
  4501.                             'path' => 'src/Controller/RdvController.php',
  4502.                             "status" => 400,
  4503.                         ])), 400);
  4504.                     }
  4505.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  4506.                         return new Response(json_encode(([
  4507.                             'message' => 'Error, no horaire found for this audio',
  4508.                             'path' => 'src/Controller/RdvController.php',
  4509.                             "status" => 400,
  4510.                         ])), 400);
  4511.                     }
  4512.                 } else {
  4513.                     // lieu audio indie
  4514.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  4515.                         return new Response(json_encode(([
  4516.                             'message' => 'Error, no horaire found for this audio',
  4517.                             'path' => 'src/Controller/RdvController.php',
  4518.                             "status" => 400,
  4519.                         ])), 400);
  4520.                     }
  4521.                 }
  4522.             } else {
  4523.                 // regular centre
  4524.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  4525.                     return new Response(json_encode(([
  4526.                         'message' => 'Error, no horaire found for this audio',
  4527.                         'path' => 'src/Controller/RdvController.php',
  4528.                         "status" => 400,
  4529.                     ])), 400);
  4530.                 }
  4531.             }
  4532.             $rdv->setDate($date);
  4533.         }
  4534.         if (isset($data["comment"]) && $token->getIdClient()) {
  4535.             $rdv->setComment($data["comment"]);
  4536.         }
  4537.         if (isset($data["review"]) && $token->getIdClient()) {
  4538.             $rdv->setReview($data["review"]);
  4539.         }
  4540.         if (isset($data["note"])) {
  4541.             $rdv->setNote($data["note"]);
  4542.         }
  4543.         if (isset($data["duree"])) {
  4544.             $rdv->setDuration($data["duree"]);
  4545.         }
  4546.         ////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
  4547.         $date $rdv->getDate();
  4548.         $smsDate $date->format('d-m-Y H:i');
  4549.         $oldDate $pastDate->format('d-m-Y H:i');
  4550.         $locale 'fr_FR';
  4551.         $formatter = new IntlDateFormatter(
  4552.             $locale,
  4553.             IntlDateFormatter::FULL,
  4554.             IntlDateFormatter::SHORT,
  4555.             null,
  4556.             IntlDateFormatter::GREGORIAN,
  4557.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  4558.         );
  4559.         $smsDateLongFormat $formatter->format($date);
  4560.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  4561.         $frenchDate ucfirst($frenchDate);
  4562.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  4563.         // notif client
  4564.         if ($rdv->getIdEtat()->getId() != 2) {
  4565.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  4566.                 if ($data["sms"]) {
  4567.                     $params = array(
  4568.                         "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4569.                         "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4570.                         "date" => $smsDateLongFormat,
  4571.                         "heure" => substr($smsDate1115),
  4572.                         "motif" => $rdv->getIdMotif()->getTitre(),
  4573.                         "centerName" => $rdv->getIdCentre()->getName(),
  4574.                         "centerAddress" => $rdv->getIdCentre()->getAddress(),
  4575.                         "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  4576.                         "audioMail" => $rdv->getIdAudio()->getMail(),
  4577.                         "centerPhone" => $rdv->getIdCentre()->getPhone(),
  4578.                         "centerCity" => $rdv->getIdCentre()->getCity(),
  4579.                         "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  4580.                         'titre' => 'Votre rendez-vous est modifié pour le',
  4581.                         'frenchDate' => $frenchDate,
  4582.                     );
  4583.                     $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  4584.                     $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  4585.                     $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.";
  4586.                     $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  4587.                 }
  4588.             }
  4589.         }
  4590.         //     //// == suppression
  4591.         else if ($rdv->getIdEtat()->getId() == 2) {
  4592.             // delete google agenda event
  4593.             $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  4594.                 ->findBy(array('rdv' => $rdv));
  4595.             foreach ($rdvEvents as $rdvEvent) {
  4596.                 $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4597.                 if ($googleCalendar) {
  4598.                     $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  4599.                     $entityManager->remove($rdvEvent);
  4600.                     $entityManager->flush();
  4601.                 }
  4602.             }
  4603.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  4604.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {                   
  4605.             $params = array(
  4606.                 "date" => substr($smsDate010),
  4607.                 "lien" => "{$_ENV['BASE_client']}search",
  4608.                 "heure" => substr($smsDate1115),
  4609.                 "patientName" => $client->getLastName(),
  4610.                 'titre' => 'Votre rendez-vous est annulé :',
  4611.                 'centerName' => $rdv->getIdCentre()->getName(),
  4612.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4613.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  4614.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4615.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4616.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4617.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  4618.                 'motif' => $rdv->getIdMotif()->getTitre(),
  4619.             );
  4620.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  4621.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  4622.             if ($data["sms"]) {
  4623.                 $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  4624.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  4625.             }
  4626.             //}
  4627.         }
  4628.         // set center
  4629.         if (isset($data["centre_id"])) {
  4630.             $entityManager $this->getDoctrine()->getManager();
  4631.             $centreId $data["centre_id"];
  4632.             $centre $entityManager->getRepository(Centre::class)->find($centreId);
  4633.             if (!$centre) {
  4634.                 return $this->json([
  4635.                     'message' => 'Error, no Centre found with this ID',
  4636.                     'path' => 'src/Controller/YourController.php',
  4637.                 ]);
  4638.             }
  4639.             $rdv->setIdCentre($centre);
  4640.         }
  4641.         $rdv->setGoogleAgendaImported(false);
  4642.         //notif Audio
  4643.         if ($rdv->getIdEtat()->getId() != 2) {
  4644.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  4645.                 if ($data["sms"]) {
  4646.                     $params = array(
  4647.                         "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  4648.                         "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  4649.                         "date" => substr($smsDate010),
  4650.                         "frenchDate" => $frenchDate,
  4651.                         "heure" => substr($smsDate1115),
  4652.                         'motif' => $rdv->getIdMotif()->getTitre(),
  4653.                         'clientPhone' => $client->getPhone(),
  4654.                         'clientNom' => $client->getLastname(),
  4655.                         'clientPrenom' => $client->getName(),
  4656.                         'clientCivilite' => $client->getCivilite(),
  4657.                         'clientPostal' => $client->getPostal(),
  4658.                         'clientMail' => $client->getMail(),
  4659.                         'centerName' => $rdv->getIdCentre()->getName(),
  4660.                         'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4661.                         'centerCity' => $rdv->getIdCentre()->getCity(),
  4662.                         'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4663.                         'idPatient' => $client->getId(),
  4664.                         'proUrl' => "{$_ENV['BASE_logiciel']}",
  4665.                         'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4666.                         'titre' => 'Votre rendez-vous est modifié pour le :'
  4667.                     );
  4668.                     $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  4669.                     $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  4670.                     if ($rdv->getIdAudio()->getModifRdvMail()) {
  4671.                         $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  4672.                         $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  4673.                     }
  4674.                     if ($rdv->getIdAudio()->getModifRdvSms()) {
  4675.                         // we ignore the sms send to the audio for the case he modify the rdv (so lets commented)
  4676.                         $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.";
  4677.                         //$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  4678.                     }
  4679.                 }
  4680.             }
  4681.         } else if ($rdv->getIdEtat()->getId() == 2) {
  4682.             if ($data["sms"]) {
  4683.                 $params = array(
  4684.                     "date" => substr($smsDate010),
  4685.                     "lien" => "{$_ENV['BASE_client']}search",
  4686.                     "heure" => substr($smsDate1115),
  4687.                     "patientName" => $client->getLastName(),
  4688.                     'titre' => 'Votre rendez-vous est annulé :',
  4689.                     'centerName' => $rdv->getIdCentre()->getName(),
  4690.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4691.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  4692.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4693.                     'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4694.                     'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4695.                     'audioMail' => $rdv->getIdAudio()->getMail(),
  4696.                     'motif' => $rdv->getIdMotif()->getTitre(),
  4697.                 );
  4698.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  4699.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  4700.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  4701.                     $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  4702.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject188);
  4703.                 }
  4704.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  4705.                     $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.";
  4706.                     // $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  4707.                 }
  4708.             }
  4709.         }
  4710.         $entityManager->flush();
  4711.         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"]))) {
  4712.             if (is_null($rdv->getIdClientTemp())) {
  4713.                 $clientRDV $this->getDoctrine()
  4714.                     ->getRepository(Client::class)
  4715.                     ->findOneBy(['id' => $rdv->getIdClient()->getId()]);
  4716.                 $clientRDV->setName($data["prenom_patient"]);
  4717.                 $clientRDV->setLastname($data["nom_patient"]);
  4718.                 $clientRDV->setMail($data["mail_patient"]);
  4719.                 $clientRDV->setPhone($data["portable_patient"]);
  4720.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  4721.             } else {
  4722.                 $clientRDV $this->getDoctrine()
  4723.                     ->getRepository(ClientTemp::class)
  4724.                     ->findOneBy(['id' => $rdv->getIdClientTemp()->getId()]);
  4725.                 $clientRDV->setName($data["prenom_patient"]);
  4726.                 $clientRDV->setLastname($data["nom_patient"]);
  4727.                 $clientRDV->setMail($data["mail_patient"]);
  4728.                 $clientRDV->setPhone($data["portable_patient"]);
  4729.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  4730.             }
  4731.             if (!empty($data["birthday_patient"])) {
  4732.                 $birth \DateTime::createFromFormat("Y-m-d"$data["birthday_patient"]);
  4733.                 $clientRDV->setBirthdate($birth);
  4734.             }
  4735.             $entityManager->flush();
  4736.         }
  4737.         if (is_null($rdv->getIdClient())) {
  4738.             $prenom_patient $rdv->getIdClientTemp()->getName();
  4739.             $nom_patient $rdv->getIdClientTemp()->getLastname();
  4740.             $mail_patient $rdv->getIdClientTemp()->getMail();
  4741.             $portable_patient $rdv->getIdClientTemp()->getPhone();
  4742.             $fixe_patient $rdv->getIdClientTemp()->getPhoneFixe();
  4743.             $birthday $rdv->getIdClientTemp()->getBirthdate();
  4744.         } elseif (is_null($rdv->getIdClientTemp())) {
  4745.             $prenom_patient =  $rdv->getIdClient()->getName();
  4746.             $nom_patient $rdv->getIdClient()->getLastname();
  4747.             $mail_patient $rdv->getIdClient()->getMail();
  4748.             $portable_patient $rdv->getIdClient()->getPhone();
  4749.             $fixe_patient $rdv->getIdClient()->getPhoneFixe();
  4750.             $birthday $rdv->getIdClient()->getBirthdate();
  4751.         } else {
  4752.             $prenom_patient "";
  4753.             $nom_patient "";
  4754.             $mail_patient "";
  4755.             $portable_patient "";
  4756.             $fixe_patient "";
  4757.             $birthday "";
  4758.         }
  4759.         /* generate sms notif on update */
  4760.         // update sms notification     
  4761.         $rdvSms->updateRdvSms($rdv);
  4762.         // google calendar update
  4763.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  4764.             ->findBy(array('audio' => $rdv->getIdAudio()));
  4765.         $data['rdv'] = $rdv->getId();
  4766.         if ($rdv->getIdClient() !== null) {
  4767.             $data["client_id"] = $rdv->getIdClient()->getId();
  4768.         }
  4769.         if ($rdv->getIdClientTemp() !== null) {
  4770.             $data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
  4771.         }
  4772.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  4773.             ->findBy(array('rdv' => $rdv));
  4774.         foreach ($rdvEvents as $rdvEvent) {
  4775.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4776.             $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  4777.         }
  4778.         $synchronisationCosium $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $rdv->getIdAudio()->getId()]);
  4779.         $cosiumCenter $this->getDoctrine()->getRepository(CosiumCenter::class)->findOneBy(["synchronisationCosium" => $synchronisationCosium"center" => $rdv->getIdCentre()]);
  4780.         if ($cosiumCenter) {
  4781.             $this->clientCosiumService->deleteRdv($synchronisationCosium$rdv);
  4782.             $this->clientCosiumService->createAgenda($synchronisationCosium$rdv$cosiumCenter);
  4783.         }
  4784.         // After successfully updating the RDV
  4785.         $this->mercure->publishRdvUpdate($rdv'updated');
  4786.         return new Response(json_encode(([
  4787.             "id" => $rdv->getId(),
  4788.             "motif_id" => $rdv->getIdMotif()->getId(),
  4789.             "motif_libelle" => $rdv->getIdMotif()->getTitre(),
  4790.             "audio_id" => $rdv->getIdAudio()->getId(),
  4791.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  4792.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  4793.             "fullName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  4794.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  4795.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  4796.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  4797.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  4798.             "centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
  4799.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  4800.             "etat_id" => $rdv->getIdEtat()->getId(),
  4801.             "date" => $rdv->getDate(),
  4802.             "comment" => $rdv->getComment(),
  4803.             "note" => $rdv->getNote(),
  4804.             "review" => $rdv->getReview(),
  4805.             "clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
  4806.             "prenom_patient" => $prenom_patient,
  4807.             "nom_patient" => $nom_patient,
  4808.             "mail_patient" => $mail_patient,
  4809.             "portable_patient" => $portable_patient,
  4810.             "fixe_patient" => $fixe_patient,
  4811.             "birthday" => $birthday,
  4812.             "status" => 200,
  4813.         ])));
  4814.     }
  4815.     /**
  4816.      * @Route("/rdv-by-patient/{id}", name="editRdvByIDFromPatient", methods={"PUT"})
  4817.      */
  4818.     public function editRdvByIDFromPatient(PublicFunction $publicFunctionRdv $rdvRequest $request): Response
  4819.     {
  4820.         $pastDate $rdv->getDate();
  4821.         $pastDuration $rdv->getDuration();
  4822.         $data json_decode($request->getContent(), true);
  4823.         $entityManager $this->getDoctrine()->getManager();
  4824.         if (!isset($data["token"])) {
  4825.             return new Response(json_encode([
  4826.                 "message" => "Pas de token n'a été spécifié",
  4827.                 "status" => 401,
  4828.             ]), 401);
  4829.         }
  4830.         /** @var Token */
  4831.         $token $this->getDoctrine()
  4832.             ->getRepository(Token::class)
  4833.             ->findOneBy(['token' => $data["token"]]);
  4834.         if (!$token) {
  4835.             return new Response(json_encode([
  4836.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4837.                 "status" => 404,
  4838.             ]), 404);
  4839.         }
  4840.         // get token age
  4841.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4842.         // if the token if older than 7 days
  4843.         if ($dateDiff->7) {
  4844.             $entityManager->remove($token);
  4845.             $entityManager->flush();
  4846.             return $this->json([
  4847.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4848.                 'path' => 'src/Controller/ClientController.php',
  4849.                 "status" => 401,
  4850.             ], 401);
  4851.         }
  4852.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  4853.             return new Response(json_encode([
  4854.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  4855.                 "status" => 404,
  4856.             ]), 404);
  4857.         }
  4858.         if (isset($data["etat_id"])) {
  4859.             $etat $this->getDoctrine()
  4860.                 ->getRepository(EtatRdv::class)
  4861.                 ->findOneBy(['id' => $data["etat_id"]]);
  4862.             if ($etat == null) {
  4863.                 return new Response(json_encode(([
  4864.                     'message' => 'Error, no etat found at this id',
  4865.                     'path' => 'src/Controller/TrustedUserController.php',
  4866.                     "status" => 400,
  4867.                 ])), 400);
  4868.             }
  4869.             $rdv->setIdEtat($etat);
  4870.         }
  4871.         if (isset($data["audio_id"])) {
  4872.             $audio $this->getDoctrine()
  4873.                 ->getRepository(Audio::class)
  4874.                 ->findOneBy(['id' => $data["audio_id"]]);
  4875.             if ($audio == null) {
  4876.                 return new Response(json_encode(([
  4877.                     'message' => 'Error, no audio found at this id',
  4878.                     'path' => 'src/Controller/TrustedUserController.php',
  4879.                     "status" => 400,
  4880.                 ])), 400);
  4881.             }
  4882.             $rdv->setIdAudio($audio);
  4883.         }
  4884.         if (isset($data["motif_id"])) {
  4885.             $motif $this->getDoctrine()
  4886.                 ->getRepository(Motif::class)
  4887.                 ->find($data["motif_id"]);
  4888.             if ($motif == null) {
  4889.                 return new Response(json_encode(([
  4890.                     'message' => 'Error, no motif found at this id',
  4891.                     'path' => 'src/Controller/TrustedUserController.php',
  4892.                     "status" => 400,
  4893.                 ])), 400);
  4894.             }
  4895.             $rdv->setIdMotif($motif);
  4896.         }
  4897.         if (isset($data["client_id"])) {
  4898.             $client $this->getDoctrine()
  4899.                 ->getRepository(Client::class)
  4900.                 ->findOneBy(['id' => $data["client_id"]]);
  4901.             if ($client == null) {
  4902.                 return new Response(json_encode(([
  4903.                     'message' => 'Error, no client found at this id',
  4904.                     'path' => 'src/Controller/TrustedUserController.php',
  4905.                     "status" => 400,
  4906.                 ])), 400);
  4907.             }
  4908.             $rdv->setIdClient($client);
  4909.         }
  4910.         if (isset($data["date"])) {
  4911.             // remove the taken schedule by rdv to make sure there is no overlap
  4912.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4913.             $dateInput \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4914.             $audioMotif $this->getDoctrine()
  4915.                 ->getRepository(AudioMotif::class)
  4916.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  4917.             if ($audioMotif == null) {
  4918.                 return new Response(json_encode(([
  4919.                     'message' => 'Error, no motif of this id found at this audio',
  4920.                     'path' => 'src/Controller/RdvController.php',
  4921.                     "status" => 400,
  4922.                 ])), 400);
  4923.             }
  4924.             if ($rdv->getIdAudio()->getIsIndie()) {
  4925.                 if ($rdv->getIdCentre()) {
  4926.                     // regular centre audio indie
  4927.                     /** @var AudioCentre */
  4928.                     $liaison $this->getDoctrine()
  4929.                         ->getRepository(AudioCentre::class)
  4930.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  4931.                     if ($liaison == null) {
  4932.                         return new Response(json_encode(([
  4933.                             'message' => 'Error, audio isnt part of the centre',
  4934.                             'path' => 'src/Controller/RdvController.php',
  4935.                             "status" => 400,
  4936.                         ])), 400);
  4937.                     }
  4938.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  4939.                         return new Response(json_encode(([
  4940.                             'message' => 'Error, no horaire found for this audio',
  4941.                             'path' => 'src/Controller/RdvController.php',
  4942.                             "status" => 400,
  4943.                         ])), 400);
  4944.                     }
  4945.                 } else {
  4946.                     // lieu audio indie
  4947.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  4948.                         return new Response(json_encode(([
  4949.                             'message' => 'Error, no horaire found for this audio',
  4950.                             'path' => 'src/Controller/RdvController.php',
  4951.                             "status" => 400,
  4952.                         ])), 400);
  4953.                     }
  4954.                 }
  4955.             } else {
  4956.                 // regular centre
  4957.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  4958.                     return new Response(json_encode(([
  4959.                         'message' => 'Error, no horaire found for this audio',
  4960.                         'path' => 'src/Controller/RdvController.php',
  4961.                         "status" => 400,
  4962.                     ])), 400);
  4963.                 }
  4964.             }
  4965.             $rdv->setDate($date);
  4966.         }
  4967.         if (isset($data["comment"]) && $token->getIdClient()) {
  4968.             $rdv->setComment($data["comment"]);
  4969.         }
  4970.         if (isset($data["review"]) && $token->getIdClient()) {
  4971.             $rdv->setReview($data["review"]);
  4972.         }
  4973.         if (isset($data["note"])) {
  4974.             $rdv->setNote($data["note"]);
  4975.         }
  4976.         if (isset($data["duree"])) {
  4977.             $rdv->setDuration($data["duree"]);
  4978.         }
  4979.         ////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
  4980.         $date $rdv->getDate();
  4981.         $smsDate $date->format('d-m-Y H:i');
  4982.         $oldDate $pastDate->format('d-m-Y H:i');
  4983.         $locale 'fr_FR';
  4984.         $formatter = new IntlDateFormatter(
  4985.             $locale,
  4986.             IntlDateFormatter::FULL,
  4987.             IntlDateFormatter::SHORT,
  4988.             null,
  4989.             IntlDateFormatter::GREGORIAN,
  4990.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  4991.         );
  4992.         $smsDateLongFormat $formatter->format($date);
  4993.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  4994.         $frenchDate ucfirst($frenchDate);
  4995.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  4996.         // notif client
  4997.         if ($rdv->getIdEtat()->getId() != 2) {
  4998.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  4999.                 $params = array(
  5000.                     "lienModifier" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5001.                     "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5002.                     "date" => $smsDateLongFormat,
  5003.                     "heure" => substr($smsDate1115),
  5004.                     "motif" => $rdv->getIdMotif()->getTitre(),
  5005.                     "centerName" => $rdv->getIdCentre()->getName(),
  5006.                     "centerAddress" => $rdv->getIdCentre()->getAddress(),
  5007.                     "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  5008.                     "audioMail" => $rdv->getIdAudio()->getMail(),
  5009.                     "centerPhone" => $rdv->getIdCentre()->getPhone(),
  5010.                     "centerCity" => $rdv->getIdCentre()->getCity(),
  5011.                     "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  5012.                     'titre' => 'Votre rendez-vous est modifié pour le',
  5013.                     'frenchDate' => $frenchDate,
  5014.                 );
  5015.                 $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  5016.                 $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  5017.                 $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.";
  5018.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5019.             }
  5020.         }
  5021.         //     //// == suppression
  5022.         else if ($rdv->getIdEtat()->getId() == 2) {
  5023.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  5024.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {                   
  5025.             $params = array(
  5026.                 "date" => substr($smsDate010),
  5027.                 "lien" => "{$_ENV['BASE_client']}audioprothesiste/{$rdv->getIdCentre()->getCity()}/{$rdv->getIdCentre()->getPostale()}/{$rdv->getIdCentre()->getName()}/prise-de-rdv-audioprothesiste-rapide/{$rdv->getIdCentre()->getId()}",
  5028.                 "heure" => substr($smsDate1115),
  5029.                 "patientName" => $client->getLastName(),
  5030.                 'titre' => 'Votre rendez-vous est annulé :',
  5031.                 'centerName' => $rdv->getIdCentre()->getName(),
  5032.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5033.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  5034.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5035.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  5036.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5037.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  5038.                 'motif' => $rdv->getIdMotif()->getTitre(),
  5039.             );
  5040.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  5041.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject203);
  5042.             $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  5043.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5044.             //}
  5045.         }
  5046.         // set center
  5047.         if (isset($data["centre_id"])) {
  5048.             $entityManager $this->getDoctrine()->getManager();
  5049.             $centreId $data["centre_id"];
  5050.             $centre $entityManager->getRepository(Centre::class)->find($centreId);
  5051.             if (!$centre) {
  5052.                 return $this->json([
  5053.                     'message' => 'Error, no Centre found with this ID',
  5054.                     'path' => 'src/Controller/YourController.php',
  5055.                 ]);
  5056.             }
  5057.             $rdv->setIdCentre($centre);
  5058.         }
  5059.         $rdv->setGoogleAgendaImported(false);
  5060.         //notif Audio
  5061.         if ($rdv->getIdEtat()->getId() != 2) {
  5062.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  5063.                 $params = array(
  5064.                     "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  5065.                     "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  5066.                     "date" => $pastDate->format("y-m-d"),
  5067.                     "heure" => $pastDate->format("H:i"),
  5068.                     'clientPhone' => $client->getPhone(),
  5069.                     'clientCivilite' => $client->getCivilite(),
  5070.                     'clientNom' => $client->getLastname(),
  5071.                     'clientPrenom' => $client->getName(),
  5072.                     'clientPostal' => $client->getPostal(),
  5073.                     'clientMail' => $client->getMail(),
  5074.                     "birthdate" => $rdv->getIdClient()->getBirthdate()->format("y-m-d"),
  5075.                     "mail" => $rdv->getIdClient()->getMail(),
  5076.                     "phone" => $rdv->getIdClient()->getPhone(),
  5077.                     "motif" => $rdv->getIdMotif()->getTitre(),
  5078.                     "address" => $rdv->getIdCentre()->getAddress(),
  5079.                     "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getLastName() . ' ' $rdv->getIdAudio()->getName(),
  5080.                     "newRdvDate" => substr($smsDate010),
  5081.                     "newRdvHour" => substr($smsDate1115),
  5082.                     "centerName" => $rdv->getIdCentre()->getName(),
  5083.                     "centerAddress" => $rdv->getIdCentre()->getAddress(),
  5084.                     "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  5085.                     'titre' => "Modification de Rendez-vous My Audio de {$rdv->getIdClient()->getLastname()}",
  5086.                     "urlPro" => "{$_ENV['BASE_logiciel']}",
  5087.                     "idPatient" => $rdv->getIdClient()->getId(),
  5088.                 );
  5089.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  5090.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  5091.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  5092.                     $subject "🔀 Rendez-vous My Audio modifié par " $client->getCivilite() . " " $client->getName() . " " $client->getLastname();
  5093.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject185);
  5094.                 }
  5095.                 $subjectMyAudio "🔀 Le patient " $client->getCivilite() . " " $client->getName() . " " $client->getLastname() . "  a modifié son rendez-vous My Audio";
  5096.                 $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subjectMyAudio204);
  5097.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  5098.                     $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.";
  5099.                     $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  5100.                 }
  5101.             }
  5102.         } else if ($rdv->getIdEtat()->getId() == 2) {
  5103.             $params = array(
  5104.                 "date" => substr($smsDate010),
  5105.                 "heure" => substr($smsDate1115),
  5106.                 "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  5107.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5108.                 "motif" => $rdv->getIdMotif()->getTitre(),
  5109.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  5110.                 "centerPostal" => $rdv->getIdCentre()->getPostale(),
  5111.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  5112.                 "centerName" => $rdv->getIdCentre()->getName(),
  5113.                 "clientNom" => $rdv->getIdClient()->getLastname(),
  5114.                 "clientPrenom" => $rdv->getIdClient()->getName(),
  5115.                 "clientMail" => $rdv->getIdClient()->getMail(),
  5116.                 "clientPhone" => $rdv->getIdClient()->getPhone(),
  5117.                 'titre' => "Annulation du Rendez-vous avec le patient {$rdv->getIdClient()->getLastname()}",
  5118.                 "proUrl" => "{$_ENV['BASE_logiciel']}",
  5119.                 "idPatient" => $rdv->getIdClient()->getId(),
  5120.             );
  5121.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  5122.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  5123.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  5124.                 $subject "❌ Annulation du rendez-vous par le patient " $client->getCivilite() . " " $client->getName() . " " $client->getLastname();
  5125.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject187);
  5126.             }
  5127.             $subject "❌ Annulation du rendez-vous par le patient " $client->getCivilite() . " " $client->getName() . " " $client->getLastname();
  5128.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject195);
  5129.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  5130.                 $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.";
  5131.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  5132.             }
  5133.         }
  5134.         $entityManager->flush();
  5135.         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"]))) {
  5136.             $birth \DateTime::createFromFormat("Y-m-d"$data["birthday_patient"]);
  5137.             if (is_null($rdv->getIdClientTemp())) {
  5138.                 $clientRDV $this->getDoctrine()
  5139.                     ->getRepository(Client::class)
  5140.                     ->findOneBy(['id' => $rdv->getIdClient()->getId()]);
  5141.                 $clientRDV->setName($data["prenom_patient"]);
  5142.                 $clientRDV->setLastname($data["nom_patient"]);
  5143.                 $clientRDV->setBirthdate($birth);
  5144.                 $clientRDV->setMail($data["mail_patient"]);
  5145.                 $clientRDV->setPhone($data["portable_patient"]);
  5146.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  5147.             } else {
  5148.                 $clientRDV $this->getDoctrine()
  5149.                     ->getRepository(ClientTemp::class)
  5150.                     ->findOneBy(['id' => $rdv->getIdClientTemp()->getId()]);
  5151.                 $clientRDV->setName($data["prenom_patient"]);
  5152.                 $clientRDV->setLastname($data["nom_patient"]);
  5153.                 $clientRDV->setBirthdate($birth);
  5154.                 $clientRDV->setMail($data["mail_patient"]);
  5155.                 $clientRDV->setPhone($data["portable_patient"]);
  5156.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  5157.             }
  5158.             $entityManager->flush();
  5159.         }
  5160.         if (is_null($rdv->getIdClient())) {
  5161.             $prenom_patient $rdv->getIdClientTemp()->getName();
  5162.             $nom_patient $rdv->getIdClientTemp()->getLastname();
  5163.             $mail_patient $rdv->getIdClientTemp()->getMail();
  5164.             $portable_patient $rdv->getIdClientTemp()->getPhone();
  5165.             $fixe_patient $rdv->getIdClientTemp()->getPhoneFixe();
  5166.             $birthday $rdv->getIdClientTemp()->getBirthdate();
  5167.         } elseif (is_null($rdv->getIdClientTemp())) {
  5168.             $prenom_patient =  $rdv->getIdClient()->getName();
  5169.             $nom_patient $rdv->getIdClient()->getLastname();
  5170.             $mail_patient $rdv->getIdClient()->getMail();
  5171.             $portable_patient $rdv->getIdClient()->getPhone();
  5172.             $fixe_patient $rdv->getIdClient()->getPhoneFixe();
  5173.             $birthday $rdv->getIdClient()->getBirthdate();
  5174.         } else {
  5175.             $prenom_patient "";
  5176.             $nom_patient "";
  5177.             $mail_patient "";
  5178.             $portable_patient "";
  5179.             $fixe_patient "";
  5180.             $birthday "";
  5181.         }
  5182.         return new Response(json_encode(([
  5183.             "id" => $rdv->getId(),
  5184.             "motif_id" => $rdv->getIdMotif()->getId(),
  5185.             "motif_libelle" => $rdv->getIdMotif()->getTitre(),
  5186.             "audio_id" => $rdv->getIdAudio()->getId(),
  5187.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  5188.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  5189.             "fullName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  5190.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  5191.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  5192.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  5193.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  5194.             "centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
  5195.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  5196.             "etat_id" => $rdv->getIdEtat()->getId(),
  5197.             "date" => $rdv->getDate(),
  5198.             "comment" => $rdv->getComment(),
  5199.             "note" => $rdv->getNote(),
  5200.             "review" => $rdv->getReview(),
  5201.             "prenom_patient" => $prenom_patient,
  5202.             "nom_patient" => $nom_patient,
  5203.             "mail_patient" => $mail_patient,
  5204.             "portable_patient" => $portable_patient,
  5205.             "fixe_patient" => $fixe_patient,
  5206.             "birthday" => $birthday,
  5207.             "status" => 200,
  5208.         ])));
  5209.     }
  5210.     /**
  5211.      * @Route("/rdv/{id}/supp", name="suppRdvByID", methods={"PUT"})
  5212.      */
  5213.     public function suppRdvByID(PublicFunction $publicFunctionRdv $rdvRequest $requestGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  5214.     {
  5215.         $pastDate $rdv->getDate();
  5216.         $data json_decode($request->getContent(), true);
  5217.         $entityManager $this->getDoctrine()->getManager();
  5218.         if (!isset($data["token"])) {
  5219.             return new Response(json_encode([
  5220.                 "message" => "Pas de token n'a été spécifié",
  5221.                 "status" => 401,
  5222.             ]), 401);
  5223.         }
  5224.         /** @var Token */
  5225.         $token $this->getDoctrine()
  5226.             ->getRepository(Token::class)
  5227.             ->findOneBy(['token' => $data["token"]]);
  5228.         if (!$token) {
  5229.             return new Response(json_encode([
  5230.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5231.                 "status" => 404,
  5232.             ]), 404);
  5233.         }
  5234.         // get token age
  5235.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5236.         // if the token if older than 7 days
  5237.         if ($dateDiff->7) {
  5238.             $entityManager->remove($token);
  5239.             $entityManager->flush();
  5240.             return $this->json([
  5241.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5242.                 'path' => 'src/Controller/ClientController.php',
  5243.                 "status" => 401,
  5244.             ], 401);
  5245.         }
  5246.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  5247.             return new Response(json_encode([
  5248.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  5249.                 "status" => 404,
  5250.             ]), 404);
  5251.         }
  5252.         // delete google agenda event
  5253.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  5254.             ->findBy(array('rdv' => $rdv));
  5255.         //dd($rdvEvents);
  5256.         $synchronisationCosium $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $rdv->getIdAudio()->getId()]);
  5257.         $cosiumCenter $this->getDoctrine()->getRepository(CosiumCenter::class)->findBy(["synchronisationCosium" => $synchronisationCosium"center" => $rdv->getIdCentre()]);
  5258.         if ($cosiumCenter) {
  5259.             $this->clientCosiumService->deleteRdv($synchronisationCosium$rdv);
  5260.         }
  5261.         foreach ($rdvEvents as $rdvEvent) {
  5262.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  5263.             $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  5264.             $entityManager->remove($rdvEvent);
  5265.             $entityManager->flush();
  5266.         }
  5267.         $etat $this->getDoctrine()
  5268.             ->getRepository(EtatRdv::class)
  5269.             ->findOneBy(['id' => 2]);
  5270.         if ($etat == null) {
  5271.             return new Response(json_encode(([
  5272.                 'message' => 'Error, no etat found at this id',
  5273.                 'path' => 'src/Controller/TrustedUserController.php',
  5274.                 "status" => 400,
  5275.             ])), 400);
  5276.         }
  5277.         $rdv->setIdEtat($etat);
  5278.         $rdv->setCacher(1);
  5279.         ////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
  5280.         $date $rdv->getDate();
  5281.         $smsDate $date->format('d-m-Y H:i');
  5282.         $oldDate $pastDate->format('d-m-Y H:i');
  5283.         $locale 'fr_FR';
  5284.         $formatter = new IntlDateFormatter(
  5285.             $locale,
  5286.             IntlDateFormatter::FULL,
  5287.             IntlDateFormatter::SHORT,
  5288.             null,
  5289.             IntlDateFormatter::GREGORIAN,
  5290.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  5291.         );
  5292.         $smsDateLongFormat $formatter->format($date);
  5293.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  5294.         $frenchDate ucfirst($frenchDate);
  5295.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  5296.         // notif client
  5297.         if ($rdv->getIdEtat()->getId() != 2) {
  5298.             $params = array(
  5299.                 "lienModifier" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5300.                 "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5301.                 "date" => $smsDateLongFormat,
  5302.                 "heure" => substr($smsDate1115),
  5303.                 "motif" => $rdv->getIdMotif()->getTitre(),
  5304.                 "centerName" => $rdv->getIdCentre()->getName(),
  5305.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  5306.                 "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  5307.                 "audioMail" => $rdv->getIdAudio()->getMail(),
  5308.                 "centerPhone" => $rdv->getIdCentre()->getPhone(),
  5309.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  5310.                 "clientEmail" => $client->getMail(),
  5311.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  5312.                 'titre' => 'Votre rendez-vous est modifié pour le',
  5313.                 'frenchDate' => $frenchDate
  5314.             );
  5315.             $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  5316.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject205);
  5317.             $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.";
  5318.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5319.             // creer un mail de notif pour myAudio + créé le template LP | MA | RR - Modification du RDV - Centre Auditif - MyAudio
  5320.             $subjectMyaudio "Rendez-vous My Audio a été modifié par l'audioprothésiste " $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName();
  5321.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$client->getName() . ' ' $client->getLastName(), $subjectMyaudio206);
  5322.         }
  5323.         //     //// == suppression
  5324.         else if ($rdv->getIdEtat()->getId() == 2) {
  5325.             $params = array(
  5326.                 "date" => substr($smsDate010),
  5327.                 "lien" => "{$_ENV['BASE_client']}search",
  5328.                 "heure" => substr($smsDate1115),
  5329.                 "patientName" => $client->getLastName() . ' ' $client->getName(),
  5330.                 'titre' => 'Votre rendez-vous est annulé :',
  5331.                 'centerName' => $rdv->getIdCentre()->getName(),
  5332.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5333.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  5334.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5335.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  5336.                 "clientEmail" => $client->getMail() ?? '',
  5337.                 "clientPhone" => $client->getPhone() ?? '',
  5338.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5339.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  5340.                 'motif' => $rdv->getIdMotif()->getTitre(),
  5341.             );
  5342.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  5343.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  5344.             $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  5345.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5346.             // creer un mail de notif pour myAudio + créé le template LP | MA | RR - Annlation du RDV - Centre Auditif - MyAudio
  5347.             $subjectMyaudio $rdv->getIdCentre()->getName() . " a annulé un rendez-vous My Audio avec " $client->getName() . ' ' $client->getLastName();
  5348.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$client->getName() . ' ' $client->getLastName(), $subjectMyaudio207);
  5349.         }
  5350.         //notif Audio
  5351.         if ($rdv->getIdEtat()->getId() != 2) {
  5352.             $params = array(
  5353.                 "lienModifier" => "{$_ENV['BASE_logiciel']}rdv",
  5354.                 "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  5355.                 "date" => substr($smsDate010),
  5356.                 "frenchDate" => $frenchDate,
  5357.                 "heure" => substr($smsDate1115),
  5358.                 'motif' => $rdv->getIdMotif()->getTitre(),
  5359.                 'clientPhone' => $client->getPhone(),
  5360.                 'clientNom' => $client->getLastname(),
  5361.                 'clientPrenom' => $client->getName(),
  5362.                 'clientCivilite' => $client->getCivilite(),
  5363.                 'clientPostal' => $client->getPostal(),
  5364.                 'clientMail' => $client->getMail(),
  5365.                 'centerName' => $rdv->getIdCentre()->getName(),
  5366.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5367.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  5368.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5369.                 'idPatient' => $client->getId(),
  5370.                 'proUrl' => "{$_ENV['BASE_logiciel']}",
  5371.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5372.                 'titre' => 'Votre rendez-vous est modifié pour le :'
  5373.             );
  5374.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  5375.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  5376.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  5377.                 $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  5378.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  5379.             }
  5380.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  5381.                 $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.";
  5382.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  5383.             }
  5384.         } else if ($rdv->getIdEtat()->getId() == 2) {
  5385.             /* $params = array(  
  5386.                     "date" => substr($smsDate, 0, 10),
  5387.                     "lien"=> "{$_ENV['BASE_client']}search",
  5388.                     "heure" =>substr($smsDate, 11, 15),
  5389.                     "patientName" => $client->getLastName(),
  5390.                     'titre' => 'Votre rendez-vous est annulé :',
  5391.                     'centerName' => $rdv->getIdCentre()->getName(),
  5392.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5393.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  5394.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5395.                     'centerPhone' => $rdv->getIdCentre()->getPhone(),
  5396.                     'audioproName' => $rdv->getIdAudio()->getCivilite().' '. $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(),                    
  5397.                     'audioMail' => $rdv->getIdAudio()->getMail(),
  5398.                     'motif' => $rdv->getIdMotif()->getTitre(),
  5399.                 );
  5400.                 $subject = "Rendez-vous My Audio annulé avec " . $rdv->getIdCentre()->getName();
  5401.                 $publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(), $subject, 188 );
  5402.                 $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.";
  5403.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());
  5404.                 */
  5405.         }
  5406.         // delete sms notification     
  5407.         $rdvSms->deleteAssociatedRdvSms($rdv);
  5408.         // delete client device
  5409.         /*$clientDevice = $this->getDoctrine()->getRepository(ClientDevice::class)->findOneBy(['rdv' => $rdv]);
  5410. if($clientDevice)
  5411. {
  5412. if ($client instanceof Client) {
  5413.     $nextRdvs = $this->getDoctrine()
  5414.         ->getRepository(Rdv::class)
  5415.         ->findBy([
  5416.             "id_client" => $rdv->getIdClient(),
  5417.             "id_motif" => ['106', '107', '108', '109'] 
  5418.         ]);
  5419.         $client->setClientStatus(null);
  5420. } elseif ($client instanceof ClientTemp) {
  5421.  $nextRdvs = $this->getDoctrine()
  5422.         ->getRepository(Rdv::class)
  5423.         ->findBy([
  5424.             "id_client_temp" => $rdv->getIdClientTemp(),
  5425.             "id_motif" => ['106', '107', '108', '109'] 
  5426.         ]);
  5427.         $client->setClientStatus(null);
  5428.     } 
  5429.     $locale = 'fr_FR';
  5430.     $fmt = new IntlDateFormatter($locale, IntlDateFormatter::FULL, IntlDateFormatter::NONE);
  5431.     $fmt->setPattern("EEEE dd MMMM yyyy"); 
  5432.     if($nextRdvs){
  5433.     $params = array(  
  5434.                 "title" => "Affectation de votre appareil et programmation de vos rendez-vous",
  5435.                 "centerName" => "{$rdv->getIdCentre()->getName()}",
  5436.                 "audioName" => "{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastName()}",
  5437.                 "centerAddress" => "{$rdv->getIdCentre()->getAddress()}",
  5438.                 "device" => "{$clientDevice->getDevice()->getModel()}",
  5439.                 "ears" => "{$clientDevice->getSettingDevice()->getName()}",
  5440.                 "rdvOneDate" => "{$fmt->format($nextRdvs['0']->getDate())}",
  5441.                 "rdvOneHour" => "{$nextRdvs['0']->getDate()->format('H:i')}",
  5442.                 "rdvTwoDate" => "{$fmt->format($nextRdvs['1']->getDate())}",
  5443.                 "rdvTwoHour" => "{$nextRdvs['1']->getDate()->format('H:i')}",
  5444.                 "rdvThreeDate" => "{$fmt->format($nextRdvs['2']->getDate())}",
  5445.                 "rdvThreeHour" => "{$nextRdvs['2']->getDate()->format('H:i')}",
  5446.                 "rdvFourDate" => "{$fmt->format($nextRdvs['3']->getDate())}",
  5447.                 "rdvFourHour" => "{$nextRdvs['3']->getDate()->format('H:i')}",
  5448.             );
  5449.     
  5450.             $publicFunction->sendEmail($params, $client->getMail(), $client->getName().' '.$client->getLastName(), "Annulation de vos prochains RDV", 162 );
  5451.         }
  5452.     foreach($nextRdvs as $rdv)
  5453.     {
  5454.         $entityManager->remove($rdv);
  5455.     }
  5456.     $entityManager->persist($client);
  5457.     $entityManager->remove($clientDevice);
  5458.     $entityManager->flush();
  5459. }*/
  5460.         // Before deleting, publish the deletion event
  5461.         $this->mercure->publishRdvDeletion($rdv);
  5462.         $entityManager->flush();
  5463.         return new Response(json_encode(([
  5464.             "id" => $rdv->getId(),
  5465.             "motif_id" => $rdv->getIdMotif()->getId(),
  5466.             "motif_libelle" => $rdv->getIdMotif()->getTitre(),
  5467.             "audio_id" => $rdv->getIdAudio()->getId(),
  5468.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  5469.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  5470.             "fullName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  5471.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  5472.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  5473.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  5474.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  5475.             "centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
  5476.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  5477.             "etat_id" => $rdv->getIdEtat()->getId(),
  5478.             "date" => $rdv->getDate(),
  5479.             "comment" => $rdv->getComment(),
  5480.             "note" => $rdv->getNote(),
  5481.             "review" => $rdv->getReview(),
  5482.             "status" => 200,
  5483.         ])));
  5484.     }
  5485.     /**
  5486.      * @Route("/rdv/calendar", name="postRdvCalendar", methods={"POST"})
  5487.      */
  5488.     public function postRdvCalendar(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSmsPublisherInterface $publisher): Response
  5489.     {
  5490.         $data json_decode($request->getContent(), true);
  5491.         if (!isset($data["token"])) {
  5492.             return new Response(json_encode([
  5493.                 "message" => "Pas de token n'a été spécifié",
  5494.                 "status" => 401,
  5495.             ]), 401);
  5496.         }
  5497.         $entityManager $this->getDoctrine()->getManager();
  5498.         /** @var Token */
  5499.         $token $this->getDoctrine()
  5500.             ->getRepository(Token::class)
  5501.             ->findOneBy(['token' => $data["token"]]);
  5502.         if (!$token) {
  5503.             return new Response(json_encode([
  5504.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5505.                 "status" => 404,
  5506.             ]), 404);
  5507.         }
  5508.         // get token age
  5509.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5510.         // if the token if older than 7 days
  5511.         if ($dateDiff->7) {
  5512.             $entityManager->remove($token);
  5513.             $entityManager->flush();
  5514.             return $this->json([
  5515.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5516.                 'path' => 'src/Controller/ClientController.php',
  5517.                 "status" => 401,
  5518.             ], 401);
  5519.         }
  5520.         // makes the rdv
  5521.         $rdv = new Rdv();
  5522.         if ($token->getIdAudio()) {
  5523.             //if the token if for an audio
  5524.             $audio $token->getIdAudio();
  5525.             if ((isset($data["client_id"]))) {
  5526.                 $client $this->getDoctrine()
  5527.                     ->getRepository(Client::class)
  5528.                     ->findOneBy(['id' => $data["client_id"]]);
  5529.             } else {
  5530.                 $client $this->getDoctrine()
  5531.                     ->getRepository(ClientTemp::class)
  5532.                     ->findOneBy(['id' => $data["client_id_temp"]]);
  5533.             }
  5534.             if ($client == null) {
  5535.                 return new Response(json_encode(([
  5536.                     'message' => 'Error, no client found at this id',
  5537.                     'path' => 'src/Controller/RdvController.php',
  5538.                     "status" => 400,
  5539.                 ])), 400);
  5540.             }
  5541.         } elseif ($token->getIdClient()) {
  5542.             //if the token if for a client
  5543.             $client $token->getIdClient();
  5544.             /** @var Audio */
  5545.             $audio $this->getDoctrine()
  5546.                 ->getRepository(Audio::class)
  5547.                 ->findOneBy(['id' => $data["audio_id"]]);
  5548.             if (isset($data["proche_id"])) {
  5549.                 $proche $this->getDoctrine()
  5550.                     ->getRepository(Proches::class)
  5551.                     ->findOneBy(['id' => $data["proche_id"], "id_client" => $client]);
  5552.             }
  5553.             if ($audio == null) {
  5554.                 return new Response(json_encode(([
  5555.                     'message' => 'Error, no audio found at this id',
  5556.                     'path' => 'src/Controller/RdvController.php',
  5557.                     "status" => 400,
  5558.                 ])), 400);
  5559.             }
  5560.         } else {
  5561.             return new Response(json_encode(([
  5562.                 'message' => 'Error, token is not an audio token',
  5563.                 'path' => 'src/Controller/RdvController.php',
  5564.                 "status" => 400,
  5565.             ])), 400);
  5566.         }
  5567.         $rdv->setIdAudio($audio);
  5568.         if (isset($proche)) {
  5569.             $rdv->setIdProche($proche);
  5570.         }
  5571.         if (isset($data["client_id_temp"])) {
  5572.             $rdv->setIdClientTemp($client);
  5573.         } else {
  5574.             $rdv->setIdClient($client);
  5575.         }
  5576.         $rdv->setCacher(0);
  5577.         /** @var Centre */
  5578.         if (isset($data["centre_id"])) {
  5579.             $centre $this->getDoctrine()
  5580.                 ->getRepository(Centre::class)
  5581.                 ->findOneBy(['id' => $data["centre_id"]]);
  5582.             if ($centre == null) {
  5583.                 return new Response(json_encode(([
  5584.                     'message' => 'Error, no centre found at this id',
  5585.                     'path' => 'src/Controller/RdvController.php',
  5586.                     "status" => 400,
  5587.                 ])), 400);
  5588.             }
  5589.             /** @var AudioCentre */
  5590.             $liaison $this->getDoctrine()
  5591.                 ->getRepository(AudioCentre::class)
  5592.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  5593.             if ($liaison == null) {
  5594.                 return new Response(json_encode(([
  5595.                     'message' => 'Error, audio isnt part of the centre',
  5596.                     'path' => 'src/Controller/RdvController.php',
  5597.                     "status" => 400,
  5598.                 ])), 400);
  5599.             }
  5600.             $rdv->setIdCentre($centre);
  5601.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  5602.             // tries to set the lieu if it's an audio indie
  5603.             $lieu $this->getDoctrine()
  5604.                 ->getRepository(Lieu::class)
  5605.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  5606.             if ($lieu == null) {
  5607.                 return new Response(json_encode(([
  5608.                     'message' => 'Error, no lieu found at this id',
  5609.                     'path' => 'src/Controller/RdvController.php',
  5610.                     "status" => 400,
  5611.                 ])), 400);
  5612.             }
  5613.             $rdv->setIdLieu($lieu);
  5614.         } else {
  5615.             return new Response(json_encode(([
  5616.                 'message' => 'Error, no lieu/centre id',
  5617.                 'path' => 'src/Controller/RdvController.php',
  5618.                 "status" => 400,
  5619.             ])), 400);
  5620.         }
  5621.         /** @var Motif */
  5622.         $motif $this->getDoctrine()
  5623.             ->getRepository(Motif::class)
  5624.             ->find($data["motif_id"]);
  5625.         if ($motif == null) {
  5626.             return new Response(json_encode(([
  5627.                 'message' => 'Error, no motif found at this id',
  5628.                 'path' => 'src/Controller/RdvController.php',
  5629.                 "status" => 400,
  5630.             ])), 400);
  5631.         }
  5632.         /** @var AudioMotif */
  5633.         $audioMotif $this->getDoctrine()
  5634.             ->getRepository(AudioMotif::class)
  5635.             ->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
  5636.         if ($audioMotif == null) {
  5637.             return new Response(json_encode(([
  5638.                 'message' => 'Error, no motif of this id found at this audio',
  5639.                 'path' => 'src/Controller/RdvController.php',
  5640.                 "status" => 400,
  5641.             ])), 400);
  5642.         }
  5643.         // remove the taken schedule by rdv to make sure there is no overlap
  5644.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  5645.         if (isset($data["note"])) {
  5646.             $rdv->setNote($data["note"]);
  5647.         }
  5648.         // test if the audio is available
  5649.         /*   if (isset($data["lieu_id"]) && $audio->getIsIndie()){
  5650.             if ($publicFunction->calculScheduleFitDate($audio, $date, $audioMotif->getDuration(), null, $lieu) == false) {
  5651.                 return new Response(json_encode(([
  5652.                     'message' => 'Error, no timestamp found at this time',
  5653.                     'path' => 'src/Controller/RdvController.php',
  5654.                     "status" => 400,
  5655.                 ])), 400);
  5656.             }
  5657.         } else {
  5658.             if ($publicFunction->calculScheduleFitDate($audio, $date, $audioMotif->getDuration(), $centre , null) == true) {
  5659.                 return new Response(json_encode(([
  5660.                     'message' => 'Error, no timestamp found at this time',
  5661.                     'path' => 'src/Controller/RdvController.php',
  5662.                     "status" => 400,
  5663.                 ])), 400);
  5664.             }
  5665.         }*/
  5666.         $rdv->setDate($date);
  5667.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  5668.         /** @var EtatRdv */
  5669.         $etat $this->getDoctrine()
  5670.             ->getRepository(EtatRdv::class)
  5671.             ->findOneBy(['id' => $data["etat_id"]]);
  5672.         if ($etat == null) {
  5673.             return new Response(json_encode(([
  5674.                 'message' => 'Error, no etat found at this id',
  5675.                 'path' => 'src/Controller/RdvController.php',
  5676.                 "status" => 400,
  5677.             ])), 400);
  5678.         }
  5679.         $rdv->setIdEtat($etat);
  5680.         $rdv->setIdMotif($motif);
  5681.         $rdv->setDuration($data["duree"]);
  5682.         $rdv->setIsAbsence($data["is_absence"]);
  5683.         $entityManager $this->getDoctrine()->getManager();
  5684.         $entityManager->persist($rdv);
  5685.         $entityManager->flush();
  5686.         $date $rdv->getDate();
  5687.         $smsDate $date->format('d-m-Y H:i');
  5688.         $locale 'fr_FR';
  5689.         $formatter = new IntlDateFormatter(
  5690.             $locale,
  5691.             IntlDateFormatter::FULL,
  5692.             IntlDateFormatter::SHORT,
  5693.             null,
  5694.             IntlDateFormatter::GREGORIAN,
  5695.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  5696.         );
  5697.         $smsDateLongFormat $formatter->format($date);
  5698.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  5699.         // client notif mail Sms
  5700.         // we send parametre for the trait methid
  5701.         //$params = $this->emailNotificationService->prepareEmailParams($user);
  5702.         // send email notifcation
  5703.         //$this->emailNotificationService->sendEmail($params, 'admin@example.com', 'Nouvelle inscription à My Audio Pro', 1);
  5704.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  5705.         $frenchDate ucfirst($frenchDate);
  5706.         $params = array(
  5707.             "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5708.             "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5709.             "date" => $smsDateLongFormat,
  5710.             "prenom" => $client->getName(),
  5711.             //"heure" => $smsDatee,
  5712.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  5713.             "centerName" => $rdv->getIdCentre()->getName(),
  5714.             "centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  5715.             "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  5716.             "centerCity" => $rdv->getIdCentre()->getCity(),
  5717.             "motif" => $rdv->getIdMotif()->getTitre(),
  5718.             "RdvDate" => substr($smsDate010) . " à "  substr($smsDate1115),
  5719.             "audioName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  5720.             "clientMail" => $client->getMail(),
  5721.             "clientPhone" => $client->getPhone(),
  5722.             'titre' => "Votre rendez-vous est validé le " substr($smsDate010) . " à "  substr($smsDate1115),
  5723.             "address" => $rdv->getIdCentre()->getAddress(),
  5724.             "postal" => $rdv->getIdCentre()->getPostale(),
  5725.             "city" => $rdv->getIdCentre()->getCity(),
  5726.             "clientEmail" => $client->getMail(),
  5727.             "clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
  5728.             "clientAddress" => $client->getAddress(),
  5729.             "clientPostal" => $client->getPostal(),
  5730.             "clientCity" => $client->getCity(),
  5731.             "audioName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  5732.             "frenchDate" => $frenchDate,
  5733.             "heure" => substr($smsDate1115),
  5734.             "centerName" => $rdv->getIdCentre()->getName(),
  5735.             "audioMail" => $rdv->getIdAudio()->getMail(),
  5736.             "modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5737.         );
  5738.         $subject "Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  5739.         $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject181);
  5740.         $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.";
  5741.         // $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone());
  5742.         // audio Notif mail SMS
  5743.         /* $params = array(  
  5744.                         "lienModifer" =>"{$_ENV['BASE_logiciel']}rdv",
  5745.                         "lienAnnule"=> "{$_ENV['BASE_logiciel']}rdv",
  5746.                         "date" => substr($smsDate, 0, 10),
  5747.                         "heure" =>substr($smsDate, 11, 15),
  5748.                         'motif' => $rdv->getIdMotif()->getTitre(),
  5749.                         'clientPhone'=> $client->getPhone(),
  5750.                         'clientNom' =>$client->getLastname(),
  5751.                         'clientPrenom' =>$client->getName(),
  5752.                         'clientCivilite' => $client->getCivilite(),
  5753.                         'clientPostal' => $client->getPostal(),
  5754.                         'clientMail' => $client->getMail(),
  5755.                         'centerName' => $rdv->getIdCentre()->getName(),
  5756.                         'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5757.                         'centerCity' => $rdv->getIdCentre()->getCity(),
  5758.                         'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5759.                         'idPatient' => $client->getId(),
  5760.                         'proUrl' => "{$_ENV['BASE_logiciel']}",
  5761.                         'audioproName' => $rdv->getIdAudio()->getCivilite().' '.$rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(),
  5762.                         'titre' => 'Votre rendez-vous est modifié pour le :'
  5763.                     );
  5764.         $subject = "🔀 Rendez-vous My Audio modifié du ". $frenchDate . " à " . substr($smsDate, 11, 15);
  5765.         $publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(), $subject, 186 );
  5766.         $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.";
  5767.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());*/
  5768.         // google calendar post
  5769.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  5770.             ->findBy(array('audio' => $audio->getId()));
  5771.         $data['rdv'] = $rdv->getId();
  5772.         $synchronisationCosium $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $audio->getId()]);
  5773.         $cosiumCenter $this->getDoctrine()->getRepository(CosiumCenter::class)->findOneBy(["synchronisationCosium" => $synchronisationCosium"center" => $rdv->getIdCentre()]);
  5774.         if ($cosiumCenter) {
  5775.             $this->clientCosiumService->createAgenda($synchronisationCosium$rdv$cosiumCenter);
  5776.         }
  5777.         foreach ($synchronisations as $synchronisation) {
  5778.             if (!$synchronisation->getIsDeleted()) {
  5779.                 try {
  5780.                     $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  5781.                     $googleCalendar->createEvent($synchronisation$data);
  5782.                 } catch (\Exception $e) {
  5783.                     error_log('Error refreshing access token or creating event: ' $e->getMessage());
  5784.                 }
  5785.             }
  5786.         }
  5787.         // create schedule notification sms
  5788.         $rdvSms->storeRdvSmsNotifications($rdv);
  5789.         if ($rdv->getClientDevice()) {
  5790.             $nextRdv $this->getDoctrine()
  5791.                 ->getRepository(Rdv::class)
  5792.                 ->find($rdv->getClientDevice()->getRdv()->getId());
  5793.             if ($nextRdv->getIdClientTemp()) {
  5794.                 $nextRdvs $this->getDoctrine()
  5795.                     ->getRepository(Rdv::class)
  5796.                     ->findBy([
  5797.                         "id_client_temp" => $nextRdv->getIdClientTemp(),
  5798.                         "id_motif" => ['106''107''108''109']
  5799.                     ]);
  5800.             } else {
  5801.                 $nextRdvs $this->getDoctrine()
  5802.                     ->getRepository(Rdv::class)
  5803.                     ->findBy([
  5804.                         "id_client" => $nextRdv->getIdClient(),
  5805.                         "id_motif" => ['106''107''108''109']
  5806.                     ]);
  5807.             }
  5808.             $mappedNextRdvs array_map(function ($rdv) {
  5809.                 return [
  5810.                     'id' => $rdv->getId(),
  5811.                     'date' => $rdv->getDate()->format('d-m-Y'),
  5812.                     'hours' => $rdv->getDate()->format('H:i'),
  5813.                     'duration' => $rdv->getDuration(),
  5814.                     "motif_id" => $rdv->getIdMotif()->getId(),
  5815.                     "motif_titre" => $rdv->getIdMotif()->getTitre(),
  5816.                     "duration" => $rdv->getDuration(),
  5817.                 ];
  5818.             }, $nextRdvs);
  5819.         }
  5820.         // After successfully creating the RDV
  5821.         $this->mercure->publishRdvUpdate($rdv'created');
  5822.         return new Response(json_encode(([
  5823.             "id" => $rdv->getId(),
  5824.             "motif_id" => $rdv->getIdMotif()->getId(),
  5825.             "audio_id" => $rdv->getIdAudio()->getId(),
  5826.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  5827.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  5828.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  5829.             "centerName" => $rdv->getIdCentre()->getName(),
  5830.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  5831.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  5832.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  5833.             "duration" => $data["duree"],
  5834.             "etat_id" => $rdv->getIdEtat()->getId(),
  5835.             "date" => $rdv->getDate(),
  5836.             "clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
  5837.             "isClient" => ($client instanceof Client) ? 0,
  5838.             "device" => $rdv->getClientDevice() ? [
  5839.                 "isDevice" => true,
  5840.                 "deviceID" => $rdv->getClientDevice()->getDevice()->getId(),
  5841.                 "clientDeviceID" => $rdv->getClientDevice()->getId(),
  5842.                 "deviceModel" => $rdv->getClientDevice()->getDevice()->getModel(),
  5843.                 "settingName" => $rdv->getClientDevice()->getSettingDevice()->getName(),
  5844.                 "settingDeviceId" => $rdv->getClientDevice()->getSettingDevice()->getSlug(),
  5845.                 "settingSlug" => $rdv->getClientDevice()->getSettingDevice()->getSlug(),
  5846.                 "nextRdvs" => $mappedNextRdvs
  5847.             ] : [
  5848.                 "isDevice" => false
  5849.             ],
  5850.             "comment" => $rdv->getComment(),
  5851.             "review" => $rdv->getReview(),
  5852.             "note" => $rdv->getNote(),
  5853.             "status" => 200,
  5854.         ])));
  5855.     }
  5856.     /**
  5857.      * @Route("/rdv/absence", name="postAbsenceCalendar", methods={"POST"})
  5858.      */
  5859.     public function postAbsenceCalendar(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendar): Response
  5860.     {
  5861.         $data json_decode($request->getContent(), true);
  5862.         if (!isset($data["token"])) {
  5863.             return new Response(json_encode([
  5864.                 "message" => "Pas de token n'a été spécifié",
  5865.                 "status" => 401,
  5866.             ]), 401);
  5867.         }
  5868.         $entityManager $this->getDoctrine()->getManager();
  5869.         /** @var Token */
  5870.         $token $this->getDoctrine()
  5871.             ->getRepository(Token::class)
  5872.             ->findOneBy(['token' => $data["token"]]);
  5873.         if (!$token) {
  5874.             return new Response(json_encode([
  5875.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5876.                 "status" => 404,
  5877.             ]), 404);
  5878.         }
  5879.         // get token age
  5880.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5881.         // if the token if older than 7 days
  5882.         if ($dateDiff->7) {
  5883.             $entityManager->remove($token);
  5884.             $entityManager->flush();
  5885.             return $this->json([
  5886.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5887.                 'path' => 'src/Controller/ClientController.php',
  5888.                 "status" => 401,
  5889.             ], 401);
  5890.         }
  5891.         // makes the rdv
  5892.         $rdv = new Rdv();
  5893.         $audio $token->getIdAudio();
  5894.         $rdv->setIdAudio($audio);
  5895.         /** @var Centre */
  5896.         if (isset($data["centre_id"])) {
  5897.             $centre $this->getDoctrine()
  5898.                 ->getRepository(Centre::class)
  5899.                 ->findOneBy(['id' => $data["centre_id"]]);
  5900.             if ($centre == null) {
  5901.                 return new Response(json_encode(([
  5902.                     'message' => 'Error, no centre found at this id',
  5903.                     'path' => 'src/Controller/RdvController.php',
  5904.                     "status" => 400,
  5905.                 ])), 400);
  5906.             }
  5907.             /** @var AudioCentre */
  5908.             $liaison $this->getDoctrine()
  5909.                 ->getRepository(AudioCentre::class)
  5910.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  5911.             if ($liaison == null) {
  5912.                 return new Response(json_encode(([
  5913.                     'message' => 'Error, audio isnt part of the centre',
  5914.                     'path' => 'src/Controller/RdvController.php',
  5915.                     "status" => 400,
  5916.                 ])), 400);
  5917.             }
  5918.             $rdv->setIdCentre($centre);
  5919.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  5920.             // tries to set the lieu if it's an audio indie
  5921.             $lieu $this->getDoctrine()
  5922.                 ->getRepository(Lieu::class)
  5923.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  5924.             if ($lieu == null) {
  5925.                 return new Response(json_encode(([
  5926.                     'message' => 'Error, no lieu found at this id',
  5927.                     'path' => 'src/Controller/RdvController.php',
  5928.                     "status" => 400,
  5929.                 ])), 400);
  5930.             }
  5931.             $rdv->setIdLieu($lieu);
  5932.         } else {
  5933.             return new Response(json_encode(([
  5934.                 'message' => 'Error, no lieu/centre id',
  5935.                 'path' => 'src/Controller/RdvController.php',
  5936.                 "status" => 400,
  5937.             ])), 400);
  5938.         }
  5939.         // remove the taken schedule by rdv to make sure there is no overlap
  5940.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  5941.         $rdv->setDate($date);
  5942.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  5943.         /** @var EtatRdv */
  5944.         $etat $this->getDoctrine()
  5945.             ->getRepository(EtatRdv::class)
  5946.             ->findOneBy(['id' => $data["etat_id"]]);
  5947.         if ($etat == null) {
  5948.             return new Response(json_encode(([
  5949.                 'message' => 'Error, no etat found at this id',
  5950.                 'path' => 'src/Controller/RdvController.php',
  5951.                 "status" => 400,
  5952.             ])), 400);
  5953.         }
  5954.         $rdv->setIdEtat($etat);
  5955.         $rdv->setDuration($data["duree"]);
  5956.         $rdv->setIsAbsence($data["is_absence"]);
  5957.         $rdv->setMotifAbsence($data["motif"]);
  5958.         $rdv->setColor($data["color"]);
  5959.         $rdv->setNote($data["note"]);
  5960.         $rdv->setCacher(0);
  5961.         $entityManager $this->getDoctrine()->getManager();
  5962.         $entityManager->persist($rdv);
  5963.         $entityManager->flush();
  5964.         // create google calendar absence event
  5965.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  5966.             ->findBy(array('audio' => $audio->getId()));
  5967.         $data['rdv'] = $rdv->getId();
  5968.         $data['motif_absence'] = $rdv->getMotifAbsence() !== '' $rdv->getMotifAbsence() : "Absence";
  5969.         //        dd($data);
  5970.         foreach ($synchronisations as $synchronisation) {
  5971.             if (!$synchronisation->getIsDeleted()) {
  5972.                 try {
  5973.                     $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  5974.                     $googleCalendar->createAbsenceEvent($synchronisation$data);
  5975.                 } catch (\Google\Service\Exception $e) {
  5976.                     if ($e->getCode() === 403 && str_contains($e->getMessage(), 'insufficientPermissions')) {
  5977.                         error_log("Skipped synchronisation ID {$synchronisation->getId()} due to insufficient permissions.");
  5978.                         continue;
  5979.                     }
  5980.                     throw $e;
  5981.                 }
  5982.             }
  5983.         }
  5984.         return new Response(json_encode(([
  5985.             "id" => $rdv->getId(),
  5986.             "audio_id" => $rdv->getIdAudio()->getId(),
  5987.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  5988.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  5989.             "duration" => $data["duree"],
  5990.             "etat_id" => $rdv->getIdEtat()->getId(),
  5991.             "date" => $rdv->getDate(),
  5992.             "status" => 200,
  5993.         ])));
  5994.     }
  5995.     /**
  5996.      * @Route("/rdv/{id}/absence", name="puttAbsenceCalendar", methods={"PUT"})
  5997.      */
  5998.     public function putAbsenceCalendar(Request $requestRdv $rdvPublicFunction $publicFunctionGoogleCalendarService $googleCalendar): Response
  5999.     {
  6000.         $data json_decode($request->getContent(), true);
  6001.         if (!isset($data["token"])) {
  6002.             return new Response(json_encode([
  6003.                 "message" => "Pas de token n'a été spécifié",
  6004.                 "status" => 401,
  6005.             ]), 401);
  6006.         }
  6007.         $entityManager $this->getDoctrine()->getManager();
  6008.         /** @var Token */
  6009.         $token $this->getDoctrine()
  6010.             ->getRepository(Token::class)
  6011.             ->findOneBy(['token' => $data["token"]]);
  6012.         if (!$token) {
  6013.             return new Response(json_encode([
  6014.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6015.                 "status" => 404,
  6016.             ]), 404);
  6017.         }
  6018.         // get token age
  6019.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6020.         // if the token if older than 7 days
  6021.         if ($dateDiff->7) {
  6022.             $entityManager->remove($token);
  6023.             $entityManager->flush();
  6024.             return $this->json([
  6025.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6026.                 'path' => 'src/Controller/ClientController.php',
  6027.                 "status" => 401,
  6028.             ], 401);
  6029.         }
  6030.         // remove the taken schedule by rdv to make sure there is no overlap
  6031.         if (isset($data["date"])) {
  6032.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  6033.             $rdv->setDate($date);
  6034.         }
  6035.         if (isset($data["duree"])) {
  6036.             $rdv->setDuration($data["duree"]);
  6037.         }
  6038.         if (isset($data["motif"])) {
  6039.             $rdv->setMotifAbsence($data["motif"]);
  6040.         }
  6041.         if (isset($data["color"])) {
  6042.             $rdv->setColor($data["color"]);
  6043.         }
  6044.         if (isset($data["note"])) {
  6045.             $rdv->setNote($data["note"]);
  6046.         }
  6047.         $entityManager $this->getDoctrine()->getManager();
  6048.         $entityManager->flush();
  6049.         $data['rdv'] = $rdv->getId();
  6050.         $data['motif_absence'] = $rdv->getMotifAbsence() !== '' $rdv->getMotifAbsence() : "Absence";
  6051.         $data['note'] = $rdv->getNote();
  6052.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  6053.             ->findBy(array('rdv' => $rdv));
  6054.         foreach ($rdvEvents as $rdvEvent) {
  6055.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  6056.             $googleCalendar->updateAbsenceEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  6057.         }
  6058.         return new Response(json_encode(([
  6059.             "id" => $rdv->getId(),
  6060.             "audio_id" => $rdv->getIdAudio()->getId(),
  6061.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  6062.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  6063.             "duration" => $rdv->getDuration(),
  6064.             "etat_id" => $rdv->getIdEtat()->getId(),
  6065.             "date" => $rdv->getDate(),
  6066.             "status" => 200,
  6067.         ])));
  6068.     }
  6069.     /**
  6070.      * @Route("/rdv/{id}/calendar", name="editRdvCalendarByID", methods={"PUT"})
  6071.      */
  6072.     public function editRdvCalendarByID(SmsHandler $smsHandlerRdv $rdvRequest $requestGoogleCalendarService $googleCalendarPublicFunction $publicFunctionRdvSmsService $rdvSms): Response
  6073.     {
  6074.         $pastDate $rdv->getDate();
  6075.         $data json_decode($request->getContent(), true);
  6076.         $entityManager $this->getDoctrine()->getManager();
  6077.         if (!isset($data["token"])) {
  6078.             return new Response(json_encode([
  6079.                 "message" => "Pas de token n'a été spécifié",
  6080.                 "status" => 401,
  6081.             ]), 401);
  6082.         }
  6083.         /** @var Token */
  6084.         $token $this->getDoctrine()
  6085.             ->getRepository(Token::class)
  6086.             ->findOneBy(['token' => $data["token"]]);
  6087.         if (!$token) {
  6088.             return new Response(json_encode([
  6089.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6090.                 "status" => 404,
  6091.             ]), 404);
  6092.         }
  6093.         // get token age
  6094.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6095.         // if the token if older than 7 days
  6096.         if ($dateDiff->7) {
  6097.             $entityManager->remove($token);
  6098.             $entityManager->flush();
  6099.             return $this->json([
  6100.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6101.                 'path' => 'src/Controller/ClientController.php',
  6102.                 "status" => 401,
  6103.             ], 401);
  6104.         }
  6105.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  6106.             return new Response(json_encode([
  6107.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  6108.                 "status" => 404,
  6109.             ]), 404);
  6110.         }
  6111.         if (isset($data["etat_id"])) {
  6112.             $etat $this->getDoctrine()
  6113.                 ->getRepository(EtatRdv::class)
  6114.                 ->findOneBy(['id' => $data["etat_id"]]);
  6115.             if ($etat == null) {
  6116.                 return new Response(json_encode(([
  6117.                     'message' => 'Error, no etat found at this id',
  6118.                     'path' => 'src/Controller/TrustedUserController.php',
  6119.                     "status" => 400,
  6120.                 ])), 400);
  6121.             }
  6122.             $rdv->setIdEtat($etat);
  6123.         }
  6124.         if (isset($data["audio_id"])) {
  6125.             $audio $this->getDoctrine()
  6126.                 ->getRepository(Audio::class)
  6127.                 ->findOneBy(['id' => $data["audio_id"]]);
  6128.             if ($audio == null) {
  6129.                 return new Response(json_encode(([
  6130.                     'message' => 'Error, no audio found at this id',
  6131.                     'path' => 'src/Controller/TrustedUserController.php',
  6132.                     "status" => 400,
  6133.                 ])), 400);
  6134.             }
  6135.             $rdv->setIdAudio($audio);
  6136.         }
  6137.         if (isset($data["motif_id"])) {
  6138.             $motif $this->getDoctrine()
  6139.                 ->getRepository(Motif::class)
  6140.                 ->find($data["motif_id"]);
  6141.             if ($motif == null) {
  6142.                 return new Response(json_encode(([
  6143.                     'message' => 'Error, no motif found at this id',
  6144.                     'path' => 'src/Controller/TrustedUserController.php',
  6145.                     "status" => 400,
  6146.                 ])), 400);
  6147.             }
  6148.             $rdv->setIdMotif($motif);
  6149.         }
  6150.         if (isset($data["client_id"])) {
  6151.             $client $this->getDoctrine()
  6152.                 ->getRepository(Client::class)
  6153.                 ->findOneBy(['id' => $data["client_id"]]);
  6154.             if ($client == null) {
  6155.                 return new Response(json_encode(([
  6156.                     'message' => 'Error, no client found at this id',
  6157.                     'path' => 'src/Controller/TrustedUserController.php',
  6158.                     "status" => 400,
  6159.                 ])), 400);
  6160.             }
  6161.             $rdv->setIdClient($client);
  6162.         }
  6163.         if (isset($data["date"])) {
  6164.             // remove the taken schedule by rdv to make sure there is no overlap
  6165.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  6166.             $audioMotif $this->getDoctrine()
  6167.                 ->getRepository(AudioMotif::class)
  6168.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  6169.             if ($audioMotif == null) {
  6170.                 return new Response(json_encode(([
  6171.                     'message' => 'Error, no motif of this id found at this audio',
  6172.                     'path' => 'src/Controller/RdvController.php',
  6173.                     "status" => 400,
  6174.                 ])), 400);
  6175.             }
  6176.             if ($rdv->getIdAudio()->getIsIndie()) {
  6177.                 if ($rdv->getIdCentre()) {
  6178.                     // regular centre audio indie
  6179.                     /** @var AudioCentre */
  6180.                     $liaison $this->getDoctrine()
  6181.                         ->getRepository(AudioCentre::class)
  6182.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  6183.                     if ($liaison == null) {
  6184.                         return new Response(json_encode(([
  6185.                             'message' => 'Error, audio isnt part of the centre',
  6186.                             'path' => 'src/Controller/RdvController.php',
  6187.                             "status" => 400,
  6188.                         ])), 400);
  6189.                     }
  6190.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  6191.                         return new Response(json_encode(([
  6192.                             'message' => 'Error, no horaire found for this audio',
  6193.                             'path' => 'src/Controller/RdvController.php',
  6194.                             "status" => 400,
  6195.                         ])), 400);
  6196.                     }
  6197.                 } else {
  6198.                     // lieu audio indie
  6199.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  6200.                         return new Response(json_encode(([
  6201.                             'message' => 'Error, no horaire found for this audio',
  6202.                             'path' => 'src/Controller/RdvController.php',
  6203.                             "status" => 400,
  6204.                         ])), 400);
  6205.                     }
  6206.                 }
  6207.             } else {
  6208.                 // regular centre
  6209.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  6210.                     return new Response(json_encode(([
  6211.                         'message' => 'Error, no horaire found for this audio',
  6212.                         'path' => 'src/Controller/RdvController.php',
  6213.                         "status" => 400,
  6214.                     ])), 400);
  6215.                 }
  6216.             }
  6217.             $rdv->setDate($date);
  6218.         }
  6219.         if (isset($data["comment"]) && $token->getIdClient()) {
  6220.             $rdv->setComment($data["comment"]);
  6221.         }
  6222.         if (isset($data["review"]) && $token->getIdClient()) {
  6223.             $rdv->setReview($data["review"]);
  6224.         }
  6225.         if (isset($data["note"])) {
  6226.             $rdv->setNote($data["note"]);
  6227.         }
  6228.         $entityManager->flush();
  6229.         $date $rdv->getDate();
  6230.         $smsDate $date->format('d-m-Y H:i');
  6231.         $oldDate $pastDate->format('d-m-Y H:i');
  6232.         $locale 'fr_FR';
  6233.         $formatter = new IntlDateFormatter(
  6234.             $locale,
  6235.             IntlDateFormatter::FULL,
  6236.             IntlDateFormatter::SHORT,
  6237.             null,
  6238.             IntlDateFormatter::GREGORIAN,
  6239.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  6240.         );
  6241.         $smsDateLongFormat $formatter->format($date);
  6242.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  6243.         $frenchDate ucfirst($frenchDate);
  6244.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  6245.         // notif client
  6246.         if ($rdv->getIdEtat()->getId() != 2) {
  6247.             $params = array(
  6248.                 "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  6249.                 "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  6250.                 "date" => $smsDateLongFormat,
  6251.                 "heure" => substr($smsDate1115),
  6252.                 "motif" => $rdv->getIdMotif()->getTitre(),
  6253.                 "centerName" => $rdv->getIdCentre()->getName(),
  6254.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  6255.                 "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  6256.                 "audioMail" => $rdv->getIdAudio()->getMail(),
  6257.                 "centerPhone" => $rdv->getIdCentre()->getPhone(),
  6258.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  6259.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  6260.                 'titre' => 'Votre rendez-vous est modifié pour le',
  6261.                 'frenchDate' => $frenchDate,
  6262.             );
  6263.             $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  6264.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  6265.             if ($data["sms"]) {
  6266.                 $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.";
  6267.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  6268.             }
  6269.         }
  6270.         //     //// == suppression
  6271.         else if ($rdv->getIdEtat()->getId() == 2) {
  6272.             $params = array(
  6273.                 "date" => substr($smsDate010),
  6274.                 "lien" => "{$_ENV['BASE_client']}search",
  6275.                 "heure" => substr($smsDate1115),
  6276.                 "patientName" => $client->getLastName(),
  6277.                 'titre' => 'Votre rendez-vous est annulé :',
  6278.                 'centerName' => $rdv->getIdCentre()->getName(),
  6279.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  6280.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  6281.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  6282.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  6283.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6284.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  6285.                 'motif' => $rdv->getIdMotif()->getTitre(),
  6286.             );
  6287.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  6288.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  6289.             if ($data["sms"]) {
  6290.                 $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  6291.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  6292.             }
  6293.         }
  6294.         //notif Audio
  6295.         if ($rdv->getIdEtat()->getId() != 2) {
  6296.             if ($data["sms"]) {
  6297.                 $params = array(
  6298.                     "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  6299.                     "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  6300.                     "date" => substr($smsDate010),
  6301.                     "frenchDate" => $frenchDate,
  6302.                     "heure" => substr($smsDate1115),
  6303.                     'motif' => $rdv->getIdMotif()->getTitre(),
  6304.                     'clientPhone' => $client->getPhone(),
  6305.                     'clientNom' => $client->getLastname(),
  6306.                     'clientPrenom' => $client->getName(),
  6307.                     'clientCivilite' => $client->getCivilite(),
  6308.                     'clientPostal' => $client->getPostal(),
  6309.                     'clientMail' => $client->getMail(),
  6310.                     'centerName' => $rdv->getIdCentre()->getName(),
  6311.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  6312.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  6313.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  6314.                     'idPatient' => $client->getId(),
  6315.                     'proUrl' => "{$_ENV['BASE_logiciel']}",
  6316.                     'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6317.                     'titre' => 'Votre rendez-vous est modifié pour le :'
  6318.                 );
  6319.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  6320.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  6321.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  6322.                     $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  6323.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  6324.                 }
  6325.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  6326.                     $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.";
  6327.                     // $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  6328.                 }
  6329.             }
  6330.         } else if ($rdv->getIdEtat()->getId() == 2) {
  6331.             if ($data["sms"]) {
  6332.                 $params = array(
  6333.                     "date" => substr($smsDate010),
  6334.                     "lien" => "{$_ENV['BASE_client']}search",
  6335.                     "heure" => substr($smsDate1115),
  6336.                     "patientName" => $client->getLastName(),
  6337.                     'titre' => 'Votre rendez-vous est annulé :',
  6338.                     'centerName' => $rdv->getIdCentre()->getName(),
  6339.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  6340.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  6341.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  6342.                     'centerPhone' => $rdv->getIdCentre()->getPhone(),
  6343.                     'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6344.                     'audioMail' => $rdv->getIdAudio()->getMail(),
  6345.                     'motif' => $rdv->getIdMotif()->getTitre(),
  6346.                 );
  6347.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  6348.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  6349.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  6350.                     $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  6351.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject188);
  6352.                 }
  6353.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  6354.                     $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.";
  6355.                     //$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  6356.                 }
  6357.             }
  6358.         }
  6359.         /* generate sms notif on update */
  6360.         // update sms notification     
  6361.         $rdvSms->updateRdvSms($rdv);
  6362.         // google calendar update
  6363.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  6364.             ->findBy(array('audio' => $rdv->getIdAudio()));
  6365.         $data['rdv'] = $rdv->getId();
  6366.         $data['motif_id'] = $rdv->getIdMotif();
  6367.         $data['note'] = $rdv->getNote();
  6368.         if ($rdv->getIdClient() !== null) {
  6369.             $data["client_id"] = $rdv->getIdClient()->getId();
  6370.         }
  6371.         if ($rdv->getIdClientTemp() !== null) {
  6372.             $data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
  6373.         }
  6374.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  6375.             ->findBy(array('rdv' => $rdv));
  6376.         foreach ($rdvEvents as $rdvEvent) {
  6377.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  6378.             $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  6379.         }
  6380.         return new Response(json_encode(([
  6381.             "id" => $rdv->getId(),
  6382.             "motif_id" => $rdv->getIdMotif()->getId(),
  6383.             "audio_id" => $rdv->getIdAudio()->getId(),
  6384.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  6385.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  6386.             "fullName" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  6387.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  6388.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  6389.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  6390.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  6391.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  6392.             "centre_id" => $rdv->getIdCentre()->getId(),
  6393.             "centerName" => $rdv->getIdCentre()->getName(),
  6394.             "etat_id" => $rdv->getIdEtat()->getId(),
  6395.             "date" => $rdv->getDate(),
  6396.             "comment" => $rdv->getComment(),
  6397.             "note" => $rdv->getNote(),
  6398.             "review" => $rdv->getReview(),
  6399.             "status" => 200,
  6400.         ])));
  6401.     }
  6402.     /**
  6403.      * @Route("/rdv/{id}/absence", name="deletetAbsenceCalendar", methods={"DELETE"})
  6404.      */
  6405.     public function deletetAbsenceCalendar(Request $requestRdv $rdvGoogleCalendarService $googleCalendar): Response
  6406.     {
  6407.         $data json_decode($request->getContent(), true);
  6408.         if (!isset($data["token"])) {
  6409.             return new Response(json_encode([
  6410.                 "message" => "Pas de token n'a été spécifié",
  6411.                 "status" => 401,
  6412.             ]), 401);
  6413.         }
  6414.         $entityManager $this->getDoctrine()->getManager();
  6415.         /** @var Token */
  6416.         $token $this->getDoctrine()
  6417.             ->getRepository(Token::class)
  6418.             ->findOneBy(['token' => $data["token"]]);
  6419.         if (!$token) {
  6420.             return new Response(json_encode([
  6421.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6422.                 "status" => 404,
  6423.             ]), 404);
  6424.         }
  6425.         // get token age
  6426.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6427.         // if the token if older than 7 days
  6428.         if ($dateDiff->7) {
  6429.             $entityManager->remove($token);
  6430.             $entityManager->flush();
  6431.             return $this->json([
  6432.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6433.                 'path' => 'src/Controller/ClientController.php',
  6434.                 "status" => 401,
  6435.             ], 401);
  6436.         }
  6437.         // delete google agenda event
  6438.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  6439.             ->findBy(array('rdv' => $rdv));
  6440.         //dd($rdvEvents);
  6441.         foreach ($rdvEvents as $rdvEvent) {
  6442.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  6443.             $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  6444.             $entityManager->remove($rdvEvent);
  6445.             $entityManager->flush();
  6446.         }
  6447.         $entityManager->remove($rdv);
  6448.         $entityManager->flush();
  6449.         return new Response(json_encode(([
  6450.             "message" => "Absence Supprime",
  6451.             "status" => 200,
  6452.         ])));
  6453.     }
  6454.     /**
  6455.      * @Route("/rdvs/facturation/rdv", name="getMyRDV", methods={"GET"})
  6456.      */
  6457.     public function getMyRDV(Request $request): Response
  6458.     {
  6459.         /* $date = new DateTime();
  6460.         $minutes_to_add = 10;
  6461.         $date->add(new DateInterval('PT' . $minutes_to_add . 'M'));
  6462.         $date->setTimezone(new DateTimeZone('Europe/Paris'));
  6463.         $currentDate = $date->format('Y-m-d H:i:00');
  6464.         $toSend = $this->getDoctrine()->getRepository(Rdv::class)
  6465.             ->findRdvsIn10Mins($currentDate); 
  6466.         */
  6467.     }
  6468.     /**
  6469.      * @Route("/rdvs/facturation/lead", name="getMyLead", methods={"GET"})
  6470.      */
  6471.     public function getMyLead(Request $request): Response {}
  6472.     /**
  6473.      * @Route("/rdvs/total-count", name="getRdvCount", methods={"GET"})
  6474.      */
  6475.     public function getRdvCount(Request $request): Response
  6476.     {
  6477.         $rdvs $this->getDoctrine()->getRepository(Rdv::class)->findAll();
  6478.         return new Response(count($rdvs));
  6479.     }
  6480.     /**
  6481.      * @Route("/admin/update-relance/{id}", name="admin_update_relance", methods={"POST"})
  6482.      */
  6483.     public function updateRelance(Request $requestLeadRdv $leadEntityManagerInterface $em): JsonResponse
  6484.     {
  6485.         $data json_decode($request->getContent(), true);
  6486.         $relanceCount $data['relanceCount'] ?? null;
  6487.         if ($relanceCount !== null) {
  6488.             $lead->setRelanceCallCount((int)$relanceCount);
  6489.             $em->flush();
  6490.             return new JsonResponse(['success' => true]);
  6491.         }
  6492.         return new JsonResponse(['success' => false], 400);
  6493.     }
  6494.     /**
  6495.      * @Route("/rdv/lead", name="postLeadRdv", methods={"POST"})
  6496.      */
  6497.     public function postLeadRdv(Request $requestEntityManagerInterface $entityManagerPublicFunction $publicFunctionGoogleCalendarService $googleCalendar): Response
  6498.     {
  6499.         $data json_decode($request->getContent(), true);
  6500.         $today = new DateTime();
  6501.         try {
  6502.             $client null;
  6503.             // Gestion du client via token ou création
  6504.             if (!empty($data['clientToken'])) {
  6505.                 $token $entityManager->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
  6506.                 $client $token $token->getIdClient() : null;
  6507.             } elseif (!empty($data['client'])) {
  6508.                 $clientData $this->createOrGetClient($data['client']);
  6509.                 $client $entityManager->getRepository(Client::class)->find($clientData['id']);
  6510.             }
  6511.             if (!$client) {
  6512.                 return $this->json(["status" => 400"message" => "Client non trouvé ou invalide"], 400);
  6513.             }
  6514.             // Création du rendez-vous LeadRdv
  6515.             $rdvLead = new LeadRdv();
  6516.             $rdvLead->setClient($client);
  6517.             if (isset($data['titleLead'])) {
  6518.                 $rdvLead->setTitleLead($data['titleLead']);
  6519.             }
  6520.             if (isset($data['rangeAge'])) {
  6521.                 $rdvLead->setRangeAge($data['rangeAge']);
  6522.             }
  6523.             if (isset($data['situations'])) {
  6524.                 $rdvLead->setSituationsGene($data['situations']);
  6525.             }
  6526.             if (isset($data['equipe'])) {
  6527.                 $rdvLead->setEquipeAppareil($data['equipe']);
  6528.             }
  6529.             if (isset($data['durationEquipe'])) {
  6530.                 $rdvLead->setDurationEquipeAppareil($data['durationEquipe']);
  6531.             }
  6532.             if (isset($data['bilanAuditif'])) {
  6533.                 $rdvLead->setBilanAuditif($data['bilanAuditif']);
  6534.             }
  6535.             if (isset($data['ordonance'])) {
  6536.                 $rdvLead->setOrdonance($data['ordonance']);
  6537.             }
  6538.             if (isset($data['dateOrdonance'])) {
  6539.                 $rdvLead->setDateOrdonance($data['dateOrdonance']);
  6540.             }
  6541.             if (isset($data['canMove'])) {
  6542.                 $rdvLead->setCanMove($data['canMove']);
  6543.             }
  6544.             if (isset($data['traffic_source'])) {
  6545.                 $rdvLead->setTrafficSource($data['traffic_source']);
  6546.             }
  6547.             if (isset($data['article_name'])) {
  6548.                 $rdvLead->setTrafficLpVersion($data['article_name']);
  6549.             }
  6550.             if (isset($data['lp_version'])) {
  6551.                 $rdvLead->setTrafficArticleName($data['lp_version']);
  6552.             }
  6553.             if (isset($data['isNewLp'])) {
  6554.                 $rdvLead->setIsNewLp($data['isNewLp']);
  6555.                 $leadStatus $entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'demande_contact']);
  6556.                 if ($leadStatus) {
  6557.                     $rdvLead->setLeadStatus($leadStatus);
  6558.                 }
  6559.             }
  6560.             $rdvLead->setDate($today);
  6561.             if (!empty($data['audio'])) {
  6562.                 $audio $entityManager->getRepository(Audio::class)->find($data['audio']);
  6563.                 if ($audio) {
  6564.                     $rdvLead->setAudio($audio);
  6565.                 }
  6566.             }
  6567.             if ($client->getPostal()) {
  6568.                 $centerCount $this->getMatchingCentresCount($client->getPostal());
  6569.                 $rdvLead->setCentersCount($centerCount);
  6570.                 if ($centerCount == 0) {
  6571.                     $leadStatus $entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'hors_zone']);
  6572.                     if ($leadStatus) {
  6573.                         $rdvLead->setLeadStatus($leadStatus);
  6574.                     }
  6575.                 }
  6576.             }
  6577.             // Création du Token
  6578.             $tokenString $publicFunction->generateRandomString(30);
  6579.             $token = (new Token())
  6580.                 ->setCreationDate(new DateTime())
  6581.                 ->setToken($tokenString)
  6582.                 ->setIdClient($client);
  6583.             $entityManager->persist($rdvLead);
  6584.             $entityManager->persist($token);
  6585.             $entityManager->flush();
  6586.             return $this->json([
  6587.                 "id" => $client->getId(),
  6588.                 "idRdvLead" => $rdvLead->getId(),
  6589.                 "name" => $client->getName(),
  6590.                 "lastname" => $client->getLastname(),
  6591.                 "token" => $tokenString,
  6592.                 "code" => $clientData['password'],
  6593.                 "postalCode" => $client->getPostal() ?? null,
  6594.                 "status" => 200,
  6595.             ]);
  6596.         } catch (\Exception $e) {
  6597.             return $this->json(["status" => 500"message" => $e->getMessage()], 500);
  6598.         }
  6599.     }
  6600.     /**
  6601.      * @Route("/testGenerateVoice", name="testGenerateVoice", methods={"GET"})
  6602.      */
  6603.     public function testGenerateVoice(AppointmentCallService $service): Response
  6604.     {
  6605.         // TEST LOCAL$rdv = $this->entityManager->getRepository(Rdv::class)->find(6653);
  6606.         $rdv $this->entityManager->getRepository(Rdv::class)->find(2306);
  6607.         $lead $this->entityManager->getRepository(LeadRdv::class)->find(496);
  6608.         // $service->handleCallCenterAfterRdv(
  6609.         //     $rdv
  6610.         // );
  6611.         // $service->handleReminderCallToPatient(
  6612.         //     $rdv
  6613.         // );
  6614.         $service->handleEquipmentStatusCall($rdv);
  6615.         // $service->handleReminderCallToPatientOneHourBefore(
  6616.         //     $rdv
  6617.         // );
  6618.         // $service->handleCallToPatientAfterRdv(
  6619.         //     $rdv
  6620.         // );
  6621.         // $service->handleFollowupCall15Days($rdv);
  6622.         // $service->handleNewLeadCall($lead, "+33743393532");
  6623.         // $service->handleFollowupCall31Days($rdv);
  6624.         return new Response(json_encode([
  6625.             "status" => 200,
  6626.         ]), 200, ['Content-Type' => 'application/json']);
  6627.     }
  6628.     /**
  6629.      * @Route("/testSynthflow", name="testSynthflow", methods={"POST"})
  6630.      */
  6631.     public function testSynthflow(SynthflowService $service): Response
  6632.     {
  6633.         // TEST LOCAL
  6634.         $lead $this->entityManager->getRepository(LeadRdv::class)->find(496);
  6635.         $service->initiateCall($lead);
  6636.         return new Response(json_encode([
  6637.             "status" => 200,
  6638.         ]), 200, ['Content-Type' => 'application/json']);
  6639.     }
  6640.     /**
  6641.      * Private method to create a new client or get existing one by phone
  6642.      */
  6643.     private function createOrGetClient(array $data): array
  6644.     {
  6645.         $clientRepository $this->entityManager->getRepository(Client::class);
  6646.         // check sur le mail et phone
  6647.         $existingClient $clientRepository->findOneBy(['mail' => $data['email']]);
  6648.         if ($existingClient) {
  6649.             if ($existingClient->getPostal() !== $data['postalCode']) {
  6650.                 $existingClient->setPostal($data['postalCode']);
  6651.                 $this->entityManager->persist($existingClient);
  6652.                 $this->entityManager->flush();
  6653.             }
  6654.             return ['id' => $existingClient->getId(), 'password' => 'Votre mot de passe'];
  6655.         }
  6656.         $randomPassword $this->generateRandomPassword(12);
  6657.         $client = new Client();
  6658.         $client->setLastname($data['lastname']);
  6659.         $client->setBirthdate(null);
  6660.         $client->setName($data['firstname']);
  6661.         $client->setPhone($data['phone']);
  6662.         $client->setMail($data['email']);
  6663.         $client->setSignupDate(new \DateTime());
  6664.         $client->setPassword(password_hash($randomPasswordPASSWORD_DEFAULT));
  6665.         $client->setPostal($data['postalCode']);
  6666.         $client->setAddress($data['address'] ?? null);
  6667.         $client->setCity($data['city'] ?? null);
  6668.         $client->setDesactivate(false);
  6669.         if (isset($data['civilite'])) {
  6670.             $civilite = ($data['civilite'] === 'Homme') ? 'Monsieur' 'Madame';
  6671.             $client->setCivilite($civilite);
  6672.         }
  6673.         $this->entityManager->persist($client);
  6674.         $this->entityManager->flush();
  6675.         return ['id' => $client->getId(), 'password' => $randomPassword];
  6676.     }
  6677.     private function generateRandomPassword($length 10): string
  6678.     {
  6679.         return bin2hex(random_bytes($length 2));
  6680.     }
  6681.     private function getMatchingCentresCount($clientPostal): int
  6682.     {
  6683.         // Récupérer les coordonnées GPS du code postal du client
  6684.         $clientCoordinates $this->entityManager
  6685.             ->getRepository(RegionDepartment::class)
  6686.             ->findOneBy(['codePostal' => $clientPostal]);
  6687.         $clientLat $clientCoordinates $clientCoordinates->getLatitude() : null;
  6688.         $clientLon $clientCoordinates $clientCoordinates->getLongitude() : null;
  6689.         $centres $this->entityManager->getRepository(Centre::class)->findAll();
  6690.         $count 0;
  6691.         foreach ($centres as $centre) {
  6692.             if ($centre->getZoneKm()) {
  6693.                 $latitude $centre->getLatitude();
  6694.                 $longitude $centre->getLongitude();
  6695.                 $radius $centre->getZoneKm();
  6696.                 $postals $this->entityManager->getRepository(RegionDepartment::class)->findPostalsWithinRadius($latitude$longitude$radius);
  6697.                 $postalCodes array_values(array_unique(array_column($postals'code_postal')));
  6698.                 if (in_array($clientPostal$postalCodes)) {
  6699.                     $count++;
  6700.                 }
  6701.             }
  6702.         }
  6703.         return $count;
  6704.     }
  6705.     /**
  6706.      * @Route("/rdv/send-map", name="getRdvMap", methods={"POST"})
  6707.      */
  6708.     public function sendEmailWithMap(Request $requestPublicFunction $publicFunction): Response
  6709.     {
  6710.         $data json_decode($request->getContent(), true);
  6711.         $mail "";
  6712.         $name "";
  6713.         $centre "";
  6714.         if (isset($data['clientToken'])) {
  6715.             $token $this->getDoctrine()->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
  6716.             $client $token->getIdClient();
  6717.             $mail $client->getMail();
  6718.             $name $client->getLastname() . " " $client->getName();
  6719.             $centre $this->getDoctrine()->getRepository(Centre::class)->findOneBy(['id' => $data['centre']['id']]);
  6720.         } else {
  6721.             $mail $data['email'];
  6722.             $name $data['name'];
  6723.         }
  6724.         $locale 'fr_FR';
  6725.         $dateTime DateTime::createFromFormat('d/m/Y H:i'$data['date']);
  6726.         if ($dateTime) {
  6727.             $fmt = new IntlDateFormatter($localeIntlDateFormatter::FULLIntlDateFormatter::NONE);
  6728.             $fmt->setPattern("EEEE dd MMMM");
  6729.             $formattedDate ucfirst($fmt->format($dateTime));
  6730.         } else {
  6731.             $formattedDate "Date invalide";
  6732.         }
  6733.         $params = [
  6734.             'date' => $data['date'],
  6735.             'time' => $data['time'],
  6736.             'frenchDate' => $formattedDate,
  6737.             'clientAddress' => $data['address'],
  6738.             'centerName' => $centre->getName(),
  6739.             'centerAddress' => $centre->getAddress(),
  6740.             'centerPostal' => $centre->getPostale(),
  6741.             'centerCity' => $centre->getCity(),
  6742.             'start' => $data['start'],
  6743.             'end' => $data['end'],
  6744.             'urlApi' => "{$_ENV['BASE_client']}",
  6745.         ];
  6746.         $publicFunction->sendEmail($params$mail$name"Votre Rendez-vous My Audio"198);
  6747.         return new Response(json_encode([
  6748.             "status" => 200,
  6749.             "params" => $params,
  6750.         ]), 200, ['Content-Type' => 'application/json']);
  6751.     }
  6752.     /**
  6753.      * @Route("/rdv/cantmove", name="notifCantMove", methods={"POST"})
  6754.      */
  6755.     public function notifCantMove(Request $requestPublicFunction $publicFunction): Response
  6756.     {
  6757.         $data json_decode($request->getContent(), true);
  6758.         $email "lead.myaudio@gmail.com";
  6759.         $centre "";
  6760.         $type "My Audio";
  6761.         $details "";
  6762.         $picto "❌";
  6763.         $ordo "sans ordo";
  6764.         $subject "";
  6765.         if (isset($data['ordonance'])) {
  6766.             if ($data["ordonance"] == "oui") {
  6767.                 $ordo "avec ordo";
  6768.             }
  6769.         } else {
  6770.             $ordo "";
  6771.         }
  6772.         if (isset($data['centre'])) {
  6773.             $centre $data['centre'];
  6774.             $subject $picto " Lead - demande de contact ne pouvant pas se déplacer " $data['postal'] . " " $ordo;
  6775.         } else {
  6776.             $centre "";
  6777.             $type "Hors Zone";
  6778.             $details "Pas de centre dans la zone";
  6779.             $subject $picto " Lead Hors Zone " $data['postal'] . " " $ordo " ne pouvant pas se déplacer";
  6780.         }
  6781.         $responses = [
  6782.             'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
  6783.             'situations' => isset($data['situations']) ? $data['situations'] : null,
  6784.             'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
  6785.             'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
  6786.             'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
  6787.             'ordonance' => isset($data['ordonance']) ? $data['ordonance'] : null,
  6788.             'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
  6789.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  6790.         ];
  6791.         $department $this->getDepartmentFromPostalCode($data['address']);
  6792.         $data['departmentCode'] = $department['departmentCode'];
  6793.         $data['departmentName'] = $department['departmentName'];
  6794.         $data['regionName'] = $department['regionName'];
  6795.         $data['city'] = $department['city'];
  6796.         $params = [
  6797.             'date' => $data['date'],
  6798.             'time' => $data['time'],
  6799.             'address' => $data['address'],
  6800.             'centre' => $centre,
  6801.             'type' => $type,
  6802.             'details' => $details,
  6803.             'responses' => $responses,
  6804.             'name' => $data['name'],
  6805.             'civilite' => $data['civilite'],
  6806.             'nom' => $data['firstname'],
  6807.             'prenom' => $data['lastname'],
  6808.             'codePostal' => $data['address'],
  6809.             'telephone' => $data['phone'],
  6810.             'email' => $data['email'],
  6811.             'departement' => $data['departmentName'],
  6812.             'ville' => $data['city'],
  6813.             'region' => $data['regionName'],
  6814.             'trangeAge' => isset($data['rangAge']) ? $data['rangAge'] : null,
  6815.             'situationVecu' => isset($data['situations']) ? implode(', '$data['situations']) : null,
  6816.             'dejaEquipe' => isset($data['equipeAppareil']) ? $data['equipeAppareil'] : null,
  6817.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  6818.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  6819.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  6820.         ];
  6821.         $publicFunction->sendEmail($params$email$data['name'], $subject208);
  6822.         return new Response(json_encode([
  6823.             "status" => 200,
  6824.         ]), 200, ['Content-Type' => 'application/json']);
  6825.     }
  6826.     /**
  6827.      * @Route("/rdv/cantmove/v2", name="notifCantMoveV2", methods={"POST"})
  6828.      */
  6829.     public function notifCantMoveV2(Request $requestPublicFunction $publicFunction): Response
  6830.     {
  6831.         $data json_decode($request->getContent(), true);
  6832.         $email "lead.myaudio@gmail.com";
  6833.         $centre "";
  6834.         $type "My Audio";
  6835.         $details "";
  6836.         $picto "❌";
  6837.         $subject "";
  6838.         $audio "";
  6839.         $subject $picto " Lead ne pouvant pas se déplacer";
  6840.         $department $this->getDepartmentFromPostalCode($data['address']);
  6841.         $data['departmentCode'] = $department['departmentCode'];
  6842.         $data['departmentName'] = $department['departmentName'];
  6843.         $data['regionName'] = $department['regionName'];
  6844.         $data['city'] = $department['city'];
  6845.         $password "";
  6846.         $params = [
  6847.             'name' => $data['name'],
  6848.             'civilite' => $data['civilite'],
  6849.             'nom' => $data['firstname'],
  6850.             'prenom' => $data['lastname'],
  6851.             'codePostal' => $data['address'],
  6852.             'telephone' => $data['phone'],
  6853.             'email' => $data['email'],
  6854.             'password' => $data['clientSecretCookie'],
  6855.             'trancheAge' => isset($data['rangAge']) ? $data['rangAge'] : null,
  6856.             'situationVecu' => isset($data['situations']) ? implode(', '$data['situations']) : null,
  6857.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  6858.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  6859.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  6860.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  6861.             'urlLogin' => "{$_ENV['BASE_client']}login"
  6862.         ];
  6863.         // Send email to MyAudio
  6864.         $publicFunction->sendEmail($params$email$data['name'], $subject220);
  6865.         $publicFunction->sendEmail($params'contact@myaudio.fr'$data['name'], $subject220);
  6866.         // Send email to patient
  6867.         $params = [
  6868.             'clientEmail' => $data['email'],
  6869.             'clientPassword' => $data['clientSecretCookie'],
  6870.             'rdv' => "https://www.myaudio.fr/search",
  6871.             'urlLogin' => "{$_ENV['BASE_client']}login"
  6872.         ];
  6873.         $publicFunction->sendEmail($params$data['email'], $data['name'], 'Rendez-vous My Audio - En cours de traitement'219);
  6874.         $rdvLead $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
  6875.         if ($rdvLead) {
  6876.             $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'cant_move']);
  6877.             if ($leadStatus) {
  6878.                 $rdvLead->setLeadStatus($leadStatus);
  6879.                 $this->entityManager->flush();
  6880.             }
  6881.         }
  6882.         return new Response(json_encode([
  6883.             "status" => 200,
  6884.         ]), 200, ['Content-Type' => 'application/json']);
  6885.     }
  6886.     /**
  6887.      * @Route("/rdv/notiflead", name="notifLead", methods={"POST"})
  6888.      */
  6889.     public function notifLeadRdv(Request $requestPublicFunction $publicFunction): Response
  6890.     {
  6891.         $data json_decode($request->getContent(), true);
  6892.         $email "lead.myaudio@gmail.com";
  6893.         $centre "";
  6894.         $type "My Audio";
  6895.         $details "";
  6896.         $picto "❌";
  6897.         $ordo "sans ordo";
  6898.         $subject "";
  6899.         $name "";
  6900.         $postal "";
  6901.         $emailPatient "";
  6902.         if (isset($data['clientToken']) && !empty($data['clientToken'])) {
  6903.             $token $this->getDoctrine()->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
  6904.             $client $token->getIdClient();
  6905.             $name $client->getLastname() . " " $client->getName();
  6906.             $postal $client->getPostal();
  6907.             $emailPatient $client->getMail();
  6908.         } else {
  6909.             if (isset($data['postal'])) {
  6910.                 $postal $data['postal'];
  6911.             }
  6912.             if (isset($data['name'])) {
  6913.                 $name $data['name'];
  6914.             }
  6915.             if (isset($data['email'])) {
  6916.                 $email $data['email'];
  6917.             }
  6918.             if (isset($data['email'])) {
  6919.                 $emailPatient $data['email'];
  6920.             }
  6921.         }
  6922.         if (isset($data["ordonance"])) {
  6923.             if ($data["ordonance"] == "oui") {
  6924.                 $ordo "avec ordo";
  6925.             }
  6926.         }
  6927.         if (isset($data['centre'])) {
  6928.             $centre $data['centre'];
  6929.             $picto "✅";
  6930.             $subject $picto " Lead booké " $postal " " $ordo;
  6931.         } else {
  6932.             $centre "";
  6933.             $type "Hors Zone";
  6934.             $details "Pas de centre dans la zone";
  6935.             $subject $picto " Lead Hors Zone " $postal " " $ordo;
  6936.         }
  6937.         $responses = [
  6938.             'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
  6939.             'situations' => isset($data['situations']) ? $data['situations'] : null,
  6940.             'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
  6941.             'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
  6942.             'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
  6943.             'ordonance' => isset($data['ordonance']) ? $data['ordonance'] : null,
  6944.             'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
  6945.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  6946.         ];
  6947.         $params = [
  6948.             'date' => $data['date'],
  6949.             'time' => $data['time'],
  6950.             'address' => $data['address'],
  6951.             'centre' => $centre,
  6952.             'type' => $type,
  6953.             'details' => $details,
  6954.             'responses' => $responses,
  6955.             'name' => $name,
  6956.             'email' => $emailPatient,
  6957.         ];
  6958.         $publicFunction->sendEmail($params$email$name$subject180);
  6959.         return new Response(json_encode([
  6960.             "status" => 200,
  6961.             "params" => $params,
  6962.             "responses" => $responses
  6963.         ]), 200, ['Content-Type' => 'application/json']);
  6964.     }
  6965.     /**
  6966.      *  Met à jour l'état d'un rendez-vous.
  6967.      *
  6968.      * Cette fonction permet de modifier l'état d'un rendez-vous en fonction des données envoyées
  6969.      * via une requête PUT. Elle effectue plusieurs vérifications, notamment :
  6970.      * - La présence et la validité du token d'authentification.
  6971.      * - L'existence du rendez-vous et du nouvel état.
  6972.      * - L'expiration du token (plus de 7 jours).
  6973.      * 
  6974.      * Si le rendez-vous est marqué comme "Absence injustifiée" (état ID 3), un email et un SMS sont envoyés
  6975.      * au client et à l'équipe MyAudio pour les informer.
  6976.      * 
  6977.      * @Route("api/save-etat-rdv", name="saveEtatRdv", methods={"PUT"})
  6978.      */
  6979.     public function saveEtatRdv(Request $requestPublicFunction $publicFunction): Response
  6980.     {
  6981.         $entityManager $this->getDoctrine()->getManager();
  6982.         $data json_decode($request->getContent(), true);
  6983.         if (!$data['token']) {
  6984.             return new Response(json_encode([
  6985.                 "message" => "Pas de token n'a été spécifié",
  6986.                 "status" => 401,
  6987.             ]), 401);
  6988.         }
  6989.         /** @var Token */
  6990.         $token $this->getDoctrine()
  6991.             ->getRepository(Token::class)
  6992.             ->findOneBy(['token' => $data['token'], 'id_audio' => $data['audio']]);
  6993.         if (!$token) {
  6994.             return new Response(json_encode([
  6995.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6996.                 "status" => 404,
  6997.             ]), 404);
  6998.         }
  6999.         // get token age
  7000.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  7001.         // if the token if older than 7 days
  7002.         if ($dateDiff->7) {
  7003.             $entityManager->remove($token);
  7004.             $entityManager->flush();
  7005.             return $this->json([
  7006.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  7007.                 'path' => 'src/Controller/ClientController.php',
  7008.                 "status" => 401,
  7009.             ], 401);
  7010.         }
  7011.         $rdv $this->getDoctrine()->getRepository(Rdv::class)->find($data['rdv']);
  7012.         if (!$rdv) {
  7013.             return new Response(json_encode([
  7014.                 "message" => "Rdv not found.",
  7015.                 "status" => 404,
  7016.             ]), 404);
  7017.         }
  7018.         $rdvEtat $this->getDoctrine()
  7019.             ->getRepository(EtatRdv::class)
  7020.             ->find($data['etat']);
  7021.         if (!$rdvEtat) {
  7022.             return new Response(json_encode([
  7023.                 "message" => "Rdv etat not found.",
  7024.                 "status" => 404,
  7025.             ]), 404);
  7026.         }
  7027.         $rdv->setIdEtat($rdvEtat);
  7028.         $entityManager->flush();
  7029.         $encodedNomDuCentre rawurlencode($rdv->getIdCentre()->getName());
  7030.         $urlApi "audioprothesiste/{$rdv->getIdCentre()->getCity()}/{$rdv->getIdCentre()->getPostale()}/{$encodedNomDuCentre}/prise-de-rdvaudioprothesiste-rapide/{$rdv->getIdCentre()->getId()}";
  7031.         if ($rdvEtat->getId() == 3) {
  7032.             // Send email to client
  7033.             $date $rdv->getDate();
  7034.             $smsDate $date->format('d-m-Y H:i');
  7035.             $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  7036.             $params = array(
  7037.                 "date" => substr($smsDate010),
  7038.                 "lien" => "{$_ENV['BASE_client']}$urlApi,
  7039.                 "heure" => substr($smsDate1115),
  7040.                 'centerName' => $rdv->getIdCentre()->getName() ?? '',
  7041.                 'centerPostal' => $rdv->getIdCentre()->getPostale() ?? '',
  7042.                 'centerCity' => $rdv->getIdCentre()->getCity() ?? '',
  7043.                 'centerAddress' => $rdv->getIdCentre()->getAddress() ?? '',
  7044.                 'centerPhone' => $rdv->getIdCentre()->getPhone() ?? '',
  7045.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName() ?? '',
  7046.                 'audioMail' => $rdv->getIdAudio()->getMail() ?? '',
  7047.             );
  7048.             $subject "Vous avez manqué votre rendez-vous MyAudio avec " $rdv->getIdCentre()->getName();
  7049.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject214);
  7050.             // Send sms to client
  7051.             $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();
  7052.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  7053.             // Send email to MyAudio
  7054.             $date $rdv->getDate();
  7055.             $smsDate $date->format('d-m-Y H:i');
  7056.             $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  7057.             $params = array(
  7058.                 "date" => substr($smsDate010),
  7059.                 "lien" => "{$_ENV['BASE_client']}search",
  7060.                 "heure" => substr($smsDate1115),
  7061.                 'centerName' => $rdv->getIdCentre()->getName() ?? '',
  7062.                 'centerPostal' => $rdv->getIdCentre()->getPostale() ?? '',
  7063.                 'centerCity' => $rdv->getIdCentre()->getCity() ?? '',
  7064.                 'centerAddress' => $rdv->getIdCentre()->getAddress() ?? '',
  7065.                 'centerPhone' => $rdv->getIdCentre()->getPhone() ?? '',
  7066.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName() ?? '',
  7067.                 'audioMail' => $rdv->getIdAudio()->getMail() ?? '',
  7068.                 'clientName' => $client->getName() . ' ' $client->getLastName() ?? '',
  7069.                 'clientMail' => $client->getMail() ?? '',
  7070.                 'clientPhone' => $client->getPhone() ?? '',
  7071.             );
  7072.             $subject "Le patient " $client->getName() . ' ' $client->getLastName() . " a manqué son rendez-vous MyAudio avec le centre " $rdv->getIdCentre()->getName();
  7073.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$client->getName() . ' ' $client->getLastName(), $subject215);
  7074.         }
  7075.         return new Response(json_encode([
  7076.             "message" => "rdvEtat has been successfully updated",
  7077.             "status" => 200,
  7078.         ]));
  7079.     }
  7080.     /**
  7081.      * 
  7082.      * @Route("api/send-email/clientnotcompletebook", name="askToContact", methods={"POST"})
  7083.      */
  7084.     public function askToContact(Request $requestPublicFunction $publicFunction): Response
  7085.     {
  7086.         $data json_decode($request->getContent(), true);
  7087.         $staticToken "3f3a8b74f3e5b2d0c4917f5f9a7c07efb1a0f1e5e8c907ec9c4e9df129e3125e9";
  7088.         $token $data['token'] ?? null;
  7089.         if ($token !== $staticToken) {
  7090.             return new JsonResponse(
  7091.                 [
  7092.                     'status' => 'error',
  7093.                     'code' => 'unauthorized',
  7094.                     'message' => 'Unauthorized access.'
  7095.                 ],
  7096.                 JsonResponse::HTTP_UNAUTHORIZED
  7097.             );
  7098.         }
  7099.         $params = [
  7100.             'clientCivilite' => isset($data['civilite']) ? $data['civilite'] : 'Pas indiqué',
  7101.             'clientNom' => isset($data['firstname']) ? $data['firstname'] : null,
  7102.             'clientPrenom' => isset($data['lastname']) ? $data['lastname'] : null,
  7103.             'clientPostal' => isset($data['postalCode']) ? $data['postalCode'] : null,
  7104.             'clientPhone' => isset($data['phone']) ? $data['phone'] : null,
  7105.             'clientMail' => isset($data['email']) ? $data['email'] : null,
  7106.             'password' => isset($data['clientSecretCookie']) ? $data['clientSecretCookie'] : null,
  7107.             'rangeAge' => isset($data['trancheAge']) ? $data['trancheAge'] : null,
  7108.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  7109.             'situations' => isset($data['situations']) ? implode(', '$data['situations']) : null,
  7110.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  7111.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  7112.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  7113.         ];
  7114.         $templateEmailMyAudio 223;
  7115.         if (!empty($data['centre'])) {
  7116.             $centre $data['centre'];
  7117.             $audio $centre['audio'][0];
  7118.             $params['centerName'] = $centre['name'] ?? null;
  7119.             $params['centerPostal'] = $centre['postale'] ?? null;
  7120.             $params['centerCity'] = $centre['city'] ?? null;
  7121.             $params['centerAddress'] = $centre['address'] ?? null;
  7122.             $params['centerPhone'] = $centre['phone'] ?? null;
  7123.             $params['audioproName'] = $audio['civilite'] . ' ' $audio['lastname'] . ' ' $audio['name'] ?? null;
  7124.             $templateEmailMyAudio 222;
  7125.         }
  7126.         // Email to My Audio
  7127.         $email "lead.myaudio@gmail.com";
  7128.         $subject "Demande de contact -  Nouveau Lead À Contacter Hors Zone";
  7129.         $publicFunction->sendEmail($params$email$data['name'], $subject$templateEmailMyAudio);
  7130.         $publicFunction->sendEmail($params'contact@myaudio.fr'$data['name'], $subject$templateEmailMyAudio);
  7131.         $coordinates $this->getCoordinatesFromPostalCode($data['postalCode']);
  7132.         $latitude $coordinates['latitude'];
  7133.         $longitude $coordinates['longitude'];
  7134.         $params = [
  7135.             'email' => isset($data['email']) ? $data['email'] : null,
  7136.             'password' => isset($data['clientSecretCookie']) ? $data['clientSecretCookie'] : null,
  7137.             "lienRdv" => "{$_ENV['BASE_client']}search?latitude={$latitude}&longitude={$longitude}&ville={$data['postalCode']}",
  7138.         ];
  7139.         // Email to Client
  7140.         $subject "My Audio - Confirmation de demande de contact";
  7141.         $publicFunction->sendEmail($params$data['email'], $data['name'], $subject221);
  7142.         $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";
  7143.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$data['phone']);
  7144.         if (isset($data['clientRdvLp'])) {
  7145.             $rdvLead $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
  7146.             if ($rdvLead) {
  7147.                 $rdvLead->setSendAskToContact(1);
  7148.                 $rdvLead->setCountAskToContact(($rdvLead->getCountAskToContact() ?? 0) + 1);
  7149.                 $this->entityManager->flush();
  7150.                 $this->sendWhatsApp($data$rdvLead);
  7151.             }
  7152.         }
  7153.         return new Response(json_encode([
  7154.             "message" => "Email ask for contact send with success",
  7155.             "status" => 200,
  7156.         ]));
  7157.     }
  7158.     private function sendWhatsApp($data$lead): void
  7159.     {
  7160.         $adminUrl $this->adminUrlGenerator
  7161.             ->setDashboard(DashboardController::class)
  7162.             ->setController(LeadRdvCrudController::class)
  7163.             ->setAction('detail')
  7164.             ->setEntityId($lead->getId())
  7165.             ->generateUrl();
  7166.         $relativeUrl parse_url($adminUrlPHP_URL_PATH) . '?' parse_url($adminUrlPHP_URL_QUERY);
  7167.         // Supprimer le slash en trop s’il y en a un au début
  7168.         $relativeUrl ltrim($relativeUrl'/');
  7169.         // 🧑‍🤝‍🧑 Tableau des destinataires
  7170.         $destinataires = [
  7171.             '33611879183'// Numéro 1
  7172.             '33667597626'// Numéro 2
  7173.             '447884128220'// Numéro 3
  7174.         ];
  7175.         foreach ($destinataires as $numero) {
  7176.             $this->whatsapp->sendTemplateMessage(
  7177.                 $numero,  // Numéro de téléphone du destinataire
  7178.                 'lead_notif_myaudio',  // Nom du template WhatsApp
  7179.                 [
  7180.                     'body' => [
  7181.                         ['parameter_name' => 'nom_client''text' => $data['firstname'] . ' ' $data['lastname']],  // {{nom_client}}
  7182.                         ['parameter_name' => 'email_client''text' => $data['email'] ?? ' '],  // {{email_client}}
  7183.                         ['parameter_name' => 'telephone_client''text' => $data['phone'] ?? ' '],  // {{telephone_client}}
  7184.                         ['parameter_name' => 'date_lead''text' => $lead->getDate()->format('d/m/Y H:i')],  // {{date_lead}}
  7185.                         ['parameter_name' => 'code_postal''text' => $data['postalCode'] ?? ' '],  // {{code_postal}}
  7186.                         ['parameter_name' => 'nombre_centres''text' => $lead->getCentersCount() ?? '0'],  // {{nombre_centres}}
  7187.                     ],
  7188.                     'button' => $relativeUrl,  // <--- seulement le chemin dynamique
  7189.                 ]
  7190.             );
  7191.         }
  7192.     }
  7193.     /**
  7194.      * Get coordinates from the postal code using the database.
  7195.      */
  7196.     private function getCoordinatesFromPostalCode(string $postalCode): array
  7197.     {
  7198.         $region $this->entityManager
  7199.             ->getRepository(RegionDepartment::class)
  7200.             ->findOneBy(['codePostal' => $postalCode]);
  7201.         if ($region) {
  7202.             return [
  7203.                 'latitude' => $region->getLatitude(),
  7204.                 'longitude' => $region->getLongitude(),
  7205.             ];
  7206.         }
  7207.         return [
  7208.             'latitude' => null,
  7209.             'longitude' => null,
  7210.         ];
  7211.     }
  7212.     /**
  7213.      * Get the department code from the code postal
  7214.      */
  7215.     private function getDepartmentFromPostalCode(string $postalCode): ?array
  7216.     {
  7217.         $region $this->entityManager
  7218.             ->getRepository(RegionDepartment::class)
  7219.             ->findOneBy(['codePostal' => $postalCode]);
  7220.         if ($region) {
  7221.             return [
  7222.                 'departmentCode' => $region->getCodeDepartement(),
  7223.                 'departmentName' => $region->getNomDepartement(),
  7224.                 'regionCode' => $region->getCodeRegion(),
  7225.                 'regionName' => $region->getNomRegion(),
  7226.                 'city' => $region->getNomCommunePostal(),
  7227.             ];
  7228.         }
  7229.         return null;
  7230.     }
  7231.     /**
  7232.      * 
  7233.      * @Route("/giuili-admin/lead/{leadId}/centre/{centreId}", name="showLeadCentre", methods={"GET"})
  7234.      */
  7235.     public function showLeadCentre(int $leadIdCentre $centreId): Response
  7236.     {
  7237.         // dd("tets");
  7238.         $center $centres $this->getDoctrine()
  7239.             ->getRepository(AudioCentre::class)
  7240.             ->findOneBy(['id_centre' => $centreId->getId()]);
  7241.         $audio $center->getIdAudio();
  7242.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  7243.             ->findBy(['id_audio' => $audio'isDeleted' => 0]);
  7244.         return $this->render('easyadmin/leadRdv/centre_show.html.twig', [
  7245.             'audio' => $audio,
  7246.             'leadId' => $leadId,
  7247.             'centreId' => $centreId,
  7248.             'motifs' => $motifs,
  7249.         ]);
  7250.     }
  7251.     /**
  7252.      * @Route("/rdv-easyadmin", name="postRdvEasyAdmin", methods={"POST"})
  7253.      */
  7254.     public function postRdvEasyAdmin(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSmsAppointmentCallService $Callservice): Response
  7255.     {
  7256.         $data json_decode($request->getContent(), true);
  7257.         $entityManager $this->getDoctrine()->getManager();
  7258.         $audio $this->getDoctrine()
  7259.             ->getRepository(Audio::class)
  7260.             ->findOneBy(['id' => $data["audio_id"]]);
  7261.         $leadRdv =   $this->getDoctrine()->getRepository(LeadRdv::class)
  7262.             ->find($data["lead_id"]);
  7263.         $client $this->getDoctrine()->getRepository(Client::class)
  7264.             ->find($leadRdv->getClient());
  7265.         $responses = [
  7266.             'rangeAge' => $leadRdv->getRangeAge(),
  7267.             'situations' =>  implode(", "$leadRdv->getSituationsGene()),
  7268.             'equipeAppareil' => $leadRdv->getEquipeAppareil(),
  7269.             'durationEquipe' => $leadRdv->getDurationEquipeAppareil(),
  7270.             'bilanAuditif' => $leadRdv->getBilanAuditif(),
  7271.             'ordonance' => $leadRdv->getOrdonance(),
  7272.             'dateOrdonance' => $leadRdv->getDateOrdonance(),
  7273.             'canMove' => $leadRdv->getCanMove(),
  7274.         ];
  7275.         // makes the rdv
  7276.         $rdv = new Rdv();
  7277.         $rdv->setIdAudio($audio);
  7278.         if (isset($proche)) {
  7279.             $rdv->setIdProche($proche);
  7280.         }
  7281.         if (isset($data["client_id_temp"])) {
  7282.             $rdv->setIdClientTemp($client);
  7283.         } else {
  7284.             $rdv->setIdClient($client);
  7285.         }
  7286.         $rdv->setIsMyaudio(true);
  7287.         if (isset($data["isRdvLead"])) {
  7288.             $rdv->setIsRdvLp(true);
  7289.         }
  7290.         if (isset($data["isRdvRapide"])) {
  7291.             $rdv->setIsRdvRapide(true);
  7292.         }
  7293.         if (isset($data["duree"])) {
  7294.             $rdv->setDuration($data["duree"]);
  7295.         }
  7296.         if (isset($data["color"])) {
  7297.             $rdv->setColor($data["color"]);
  7298.         }
  7299.         /** @var Centre */
  7300.         if (isset($data["centre_id"])) {
  7301.             $centre $this->getDoctrine()
  7302.                 ->getRepository(Centre::class)
  7303.                 ->findOneBy(['id' => $data["centre_id"]]);
  7304.             if ($centre == null) {
  7305.                 return new Response(json_encode(([
  7306.                     'message' => 'Error, no centre found at this id',
  7307.                     'path' => 'src/Controller/RdvController.php',
  7308.                     "status" => 400,
  7309.                 ])), 400);
  7310.             }
  7311.             /** @var AudioCentre */
  7312.             $liaison $this->getDoctrine()
  7313.                 ->getRepository(AudioCentre::class)
  7314.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  7315.             if ($liaison == null) {
  7316.                 return new Response(json_encode(([
  7317.                     'message' => 'Error, audio isnt part of the centre',
  7318.                     'path' => 'src/Controller/RdvController.php',
  7319.                     "status" => 400,
  7320.                 ])), 400);
  7321.             }
  7322.             $rdv->setIdCentre($centre);
  7323.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  7324.             // tries to set the lieu if it's an audio indie
  7325.             $lieu $this->getDoctrine()
  7326.                 ->getRepository(Lieu::class)
  7327.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  7328.             if ($lieu == null) {
  7329.                 return new Response(json_encode(([
  7330.                     'message' => 'Error, no lieu found at this id',
  7331.                     'path' => 'src/Controller/RdvController.php',
  7332.                     "status" => 400,
  7333.                 ])), 400);
  7334.             }
  7335.             $rdv->setIdLieu($lieu);
  7336.         } else {
  7337.             return new Response(json_encode(([
  7338.                 'message' => 'Error, no lieu/centre id',
  7339.                 'path' => 'src/Controller/RdvController.php',
  7340.                 "status" => 400,
  7341.             ])), 400);
  7342.         }
  7343.         /** @var Motif */
  7344.         $motif $this->getDoctrine()
  7345.             ->getRepository(Motif::class)
  7346.             ->find($data["motif_id"]);
  7347.         if ($motif == null) {
  7348.             return new Response(json_encode(([
  7349.                 'message' => 'Error, no motif found at this id',
  7350.                 'path' => 'src/Controller/RdvController.php',
  7351.                 "status" => 400,
  7352.             ])), 400);
  7353.         }
  7354.         /** @var AudioMotif */
  7355.         $audioMotif $this->getDoctrine()
  7356.             ->getRepository(AudioMotif::class)
  7357.             ->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
  7358.         if ($audioMotif == null) {
  7359.             return new Response(json_encode(([
  7360.                 'message' => 'Error, no motif of this id found at this audio',
  7361.                 'path' => 'src/Controller/RdvController.php',
  7362.                 "status" => 400,
  7363.             ])), 400);
  7364.         }
  7365.         // remove the taken schedule by rdv to make sure there is no overlap
  7366.         $data["date"] = str_replace("h"":"$data["date"]);
  7367.         $date \DateTime::createFromFormat("Y-m-d\TH:i"$data["date"]);
  7368.         if (isset($data["note"])) {
  7369.             $rdv->setNote($data["note"]);
  7370.         }
  7371.         $date \DateTime::createFromFormat("Y-m-d\TH:i"$data["date"]);
  7372.         $rdv->setDate($date);
  7373.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  7374.         /** @var EtatRdv */
  7375.         $etat $this->getDoctrine()
  7376.             ->getRepository(EtatRdv::class)
  7377.             ->findOneBy(['id' => $data["etat_id"]]);
  7378.         if ($etat == null) {
  7379.             return new Response(json_encode(([
  7380.                 'message' => 'Error, no etat found at this id',
  7381.                 'path' => 'src/Controller/RdvController.php',
  7382.                 "status" => 400,
  7383.             ])), 400);
  7384.         }
  7385.         $rdv->setIdEtat($etat);
  7386.         $rdv->setIdMotif($motif);
  7387.         $rdv->setIsAbsence(0);
  7388.         $rdv->setCacher(0);
  7389.         $entityManager $this->getDoctrine()->getManager();
  7390.         $entityManager->persist($rdv);
  7391.         $leadRdv->setRdv($rdv);
  7392.         $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
  7393.         $leadRdv->setLeadStatus($leadStatus);
  7394.         $entityManager->flush();
  7395.         /// SMSEMAIL A décommenter pour autoriser l'envoi de sms / email à la création de rdv par l'audio / le client SMSEMAIL ///
  7396.         $date $rdv->getDate();
  7397.         $smsDate $date->format('d-m-Y H:i');
  7398.         $locale 'fr_FR';
  7399.         $formatter = new IntlDateFormatter(
  7400.             $locale,
  7401.             IntlDateFormatter::FULL,
  7402.             IntlDateFormatter::SHORT,
  7403.             null,
  7404.             IntlDateFormatter::GREGORIAN,
  7405.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  7406.         );
  7407.         $smsDateLongFormat $formatter->format($date);
  7408.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  7409.         $client->setIdCentre($rdv->getIdCentre());
  7410.         $client->setIdAudio($rdv->getIdAudio());
  7411.         $entityManager->persist($client);
  7412.         $entityManager->flush();
  7413.         // client notif mail Sms
  7414.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  7415.         $frenchDate ucfirst($frenchDate);
  7416.         $params = array(
  7417.             "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  7418.             "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  7419.             "date" => $smsDateLongFormat,
  7420.             "RdvDate" => $smsDateLongFormat,
  7421.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  7422.             "centerName" => $rdv->getIdCentre()->getName(),
  7423.             "prenom" => $client->getName(),
  7424.             "centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  7425.             "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  7426.             'motif' => $rdv->getIdMotif()->getTitre(),
  7427.             "centerCity" => $rdv->getIdCentre()->getCity(),
  7428.             "audioName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  7429.             'titre' => "Votre rendez-vous est validé le " substr($smsDate010) . " à "  substr($smsDate1115),
  7430.             "position" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  7431.             "address" => $rdv->getIdCentre()->getAddress(),
  7432.             "postal" => $rdv->getIdCentre()->getPostale(),
  7433.             "city" => $rdv->getIdCentre()->getCity(),
  7434.             "clientEmail" => $client->getMail(),
  7435.             "clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
  7436.             "clientAddress" => $client->getAddress(),
  7437.             "clientPostal" => $client->getPostal(),
  7438.             "clientCity" => $client->getCity(),
  7439.             "audioName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  7440.             "frenchDate" => $frenchDate,
  7441.             "heure" => substr($smsDate1115),
  7442.             "centerName" => $rdv->getIdCentre()->getName(),
  7443.             "audioMail" => $rdv->getIdAudio()->getMail(),
  7444.             "modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
  7445.         );
  7446.         $paramsPatient $params;
  7447.         $isNew false;
  7448.         if (isset($data["isLead"]) && isset($data["passwordGenerated"]) != null) {
  7449.             $subject "✅Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  7450.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject189);
  7451.             $isNew true;
  7452.         } else {
  7453.             $subject "Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  7454.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject181);
  7455.         }
  7456.         $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.";
  7457.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  7458.         // audio Notif mail SMS
  7459.         $birthday $rdv->getIdClient()->getBirthdate();
  7460.         $params = array(
  7461.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  7462.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  7463.             "date" => substr($smsDate010),
  7464.             "heure" => substr($smsDate1115),
  7465.             "mail" => $client->getMail(),
  7466.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  7467.             'telClient' => $client->getPhone(),
  7468.             'phone' => $client->getPhone(),
  7469.             'clientCivilite' => $client->getCivilite(),
  7470.             'clientNom' => $client->getLastname(),
  7471.             'clientPrenom' => $client->getName(),
  7472.             'clientPostal' => $client->getPostal(),
  7473.             'clientMail' => $client->getMail(),
  7474.             'clientPhone' => $client->getPhone(),
  7475.             'motif' => $rdv->getIdMotif()->getTitre(),
  7476.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  7477.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  7478.             'centerName' => $rdv->getIdCentre()->getName(),
  7479.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  7480.             'centerCity' => $rdv->getIdCentre()->getCity(),
  7481.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  7482.             'idPatient' => $client->getId(),
  7483.             'proUrl' => "{$_ENV['BASE_logiciel']}",
  7484.             'frenchDate' => $frenchDate,
  7485.             'responses' => $responses,
  7486.         );
  7487.         $templateEmail 182;
  7488.         if (!empty($data['canMove'])) {
  7489.             $templateEmail 197;
  7490.         }
  7491.         $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  7492.         $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  7493.         if ($rdv->getIdAudio()->getConfirmRdvMail()) {
  7494.             $subject "✅ Nouveau Rendez-vous My Audio le " $frenchDate " à " substr($smsDate1115);
  7495.             $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject$templateEmail);
  7496.         }
  7497.         if ($rdv->getIdAudio()->getConfirmRdvSms()) {
  7498.             $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.";
  7499.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  7500.         }
  7501.         $age null;
  7502.         if ($client->getBirthdate()) {
  7503.             $age $client->getBirthdate()->diff(new \DateTime())->y;
  7504.         }
  7505.         // Génère le PDF à partir d’un template
  7506.         $pdfContent $this->generatePdf(
  7507.             'pdf/rdv_recap.html.twig',
  7508.             [
  7509.                 'id' => $client->getId() ?? '',
  7510.                 'nom' => $client->getName() ?? '',
  7511.                 'prenom' => $client->getLastname() ?? '',
  7512.                 'birthday' =>  $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  7513.                 'age' => $age,
  7514.                 'adresse' => $client->getAddress() ?? '',
  7515.                 'postal' => $client->getPostal() ?? '',
  7516.                 'city' => $client->getCity() ?? '',
  7517.                 'phone' => $client->getPhone() ?? '',
  7518.                 'mail' => $client->getMail() ?? '',
  7519.                 'centerName' => $rdv->getIdCentre()->getName() ?? '',
  7520.                 "date" => substr($smsDate010) ?? '',
  7521.                 "heure" => substr($smsDate1115) ?? '',
  7522.                 'duration' => $rdv->getDuration(),
  7523.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  7524.                 'motif' => $rdv->getIdMotif() ? $rdv->getIdMotif()->getTitre() : '',
  7525.                 'situations' => $this->formatImploded($leadRdv->getSituationsGene()),
  7526.                 'IntensiteGen' => $leadRdv->getIntensiteGene() ?? '',
  7527.                 'devicePref' => $this->formatImploded($leadRdv->getPreferenceDevice()),
  7528.                 'deviceModelPref' =>  implode(", "$leadRdv->getDeviceModelPreference()),
  7529.                 'criterePrincipal' => $this->formatImploded($leadRdv->getCriterePrincipal()),
  7530.                 'accoupheneCote' =>  $leadRdv->getAcoupheneCote() ?? '',
  7531.                 'originePerte' => $this->formatImploded($leadRdv->getOriginePerte()),
  7532.                 'diabete' =>  $leadRdv->getDiabete() ?? '',
  7533.                 'hypertension' =>  $leadRdv->getHypertension() ?? '',
  7534.                 'mutuelle' =>  $leadRdv->getMutuelle() ?? '',
  7535.                 'nameMutuelle' =>  $leadRdv->getNameMutuelle() ?? '',
  7536.                 'priseEnCharge' => $leadRdv->getPriseEnCharge() ?? '',
  7537.                 'budget' => $leadRdv->getBudget() ?? '',
  7538.                 'equipeAppareil' => $leadRdv->getEquipeAppareil() ?? '',
  7539.                 'durationEquipe' => $leadRdv->getDurationEquipeAppareil() ?? '',
  7540.                 'bilanAuditif' => $leadRdv->getBilanAuditif() ?? '',
  7541.                 'ordonance' => $leadRdv->getOrdonance() ?? '',
  7542.                 'dateOrdonance' => $leadRdv->getDateOrdonance() ?? '',
  7543.                 'canMove' => $leadRdv->getCanMove() ?? '',
  7544.                 'comment' => $leadRdv->getComment() ?? '',
  7545.             ],
  7546.             $this->getParameter('kernel.project_dir') . '/public/assets/pdf/recap-rdv-myaudio.pdf'
  7547.         );
  7548.         $this->sendEmailWithPdfAttachmentThenDelete(
  7549.             $params,
  7550.             $mailAudio,
  7551.             $client->getName(),
  7552.             $subject,
  7553.             $templateEmail// ID du template Sendinblue
  7554.             $pdfContent
  7555.         );
  7556.         // send notif to admin
  7557.         $paramsSourceLead = [
  7558.             'trafficSource' => "EasyAdmin",
  7559.         ];
  7560.         $paramsAdmin = array(
  7561.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  7562.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  7563.             "RdvDate" => substr($smsDate010),
  7564.             "heure" => substr($smsDate1115),
  7565.             "clientMail" => $client->getMail(),
  7566.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  7567.             'telClient' => $client->getPhone(),
  7568.             'clientNom' => $client->getLastname(),
  7569.             'clientPrenom' => $client->getName(),
  7570.             'clientCivilite' => $client->getCivilite(),
  7571.             'clientPostal' => $client->getPostal(),
  7572.             'clientPhone' => $client->getPhone(),
  7573.             'motif' => $rdv->getIdMotif()->getTitre(),
  7574.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  7575.             'centerName' => $rdv->getIdCentre()->getName(),
  7576.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  7577.             'centerCity' => $rdv->getIdCentre()->getCity(),
  7578.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  7579.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  7580.             'date' => substr($smsDate010),
  7581.             'urlApi' => "{$_ENV['BASE_API']}",
  7582.             'clientId' => $client->getId(),
  7583.             'centerId' => $rdv->getIdCentre()->getId(),
  7584.             'frenchDate' => $frenchDate,
  7585.             'responses' => $responses,
  7586.             'paramsSourceLead' => $paramsSourceLead
  7587.         );
  7588.         $subject "Nouveau RDV MA | RR - " $rdv->getIdCentre()->getName();
  7589.         $templateEmail 183;
  7590.         if (!empty($data['canMove'])) {
  7591.             $templateEmail 190;
  7592.         }
  7593.         $publicFunction->sendEmail($paramsAdmin"contact@myaudio.fr""my audio"$subject$templateEmail);
  7594.         $publicFunction->sendEmail($paramsAdmin"lead.myaudio@gmail.com""my audio"$subject$templateEmail);
  7595.         $specificSubscription $this->getDoctrine()
  7596.              ->getRepository(SpecificSubscription::class)
  7597.              ->findOneBy(['audio' => $audio]);
  7598.       if ($specificSubscription && $specificSubscription->getContractCategory()) {
  7599.         $contractCategory $specificSubscription->getContractCategory();
  7600.       if ($contractCategory->getName() === "OPTICAL CENTER SUCCURSALE") {
  7601.         $publicFunction->sendEmail($paramsAdmin"christel.montagne@optical-center.com""my audio"$subject246);
  7602.          }
  7603.        }
  7604.         try {
  7605.             $Callservice->handleCallCenterAfterRdv(
  7606.                 $rdv
  7607.             );
  7608.             $rdv->setIsNotificationRdvCallSent(1);
  7609.             $this->entityManager->flush();
  7610.         } catch (\Exception $e) {
  7611.             $this->logger->error("Erreur lors de l'appel de notification pour le RDV #{$rdv->getId()}: " $e->getMessage());
  7612.         }
  7613.         // google calendar post
  7614.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  7615.             ->findBy(array('audio' => $audio->getId()));
  7616.         $data['rdv'] = $rdv->getId();
  7617.         foreach ($synchronisations as $synchronisation) {
  7618.             if (!$synchronisation->getIsDeleted()) {
  7619.                 $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  7620.                 $googleCalendar->createEvent($synchronisation$data);
  7621.             }
  7622.         }
  7623.         return new Response(json_encode(([
  7624.             "id" => $rdv->getId(),
  7625.             "motif_id" => $rdv->getIdMotif()->getId(),
  7626.             "audio_id" => $rdv->getIdAudio()->getId(),
  7627.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  7628.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  7629.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  7630.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  7631.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  7632.             "testclient" => $rdv->getTestClient() ? [
  7633.                 "result" => $rdv->getTestClient()->getResultTonal(),
  7634.                 "date" => $rdv->getTestClient()->getDate(),
  7635.                 "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  7636.             ] : null,
  7637.             "duration" => $audioMotif->getDuration(),
  7638.             "consigne" => $audioMotif->getConsigne(),
  7639.             "etat_id" => $rdv->getIdEtat()->getId(),
  7640.             "date" => $rdv->getDate(),
  7641.             "comment" => $rdv->getComment(),
  7642.             "centerName" => $rdv->getIdCentre()->getName(),
  7643.             "review" => $rdv->getReview(),
  7644.             "note" => $rdv->getNote(),
  7645.             "status" => 200,
  7646.             "paramsPatient" => $paramsPatient,
  7647.             "isNew" => $isNew,
  7648.         ])));
  7649.     }
  7650.     private function generatePdf(string $template, array $data = [], string $outputPath): string
  7651.     {
  7652.         // Render le contenu HTML avec Twig
  7653.         $html $this->twig->render($template$data);
  7654.         // Configurer Dompdf
  7655.         $options = new Options();
  7656.         $options->set('defaultFont''Arial');
  7657.         $dompdf = new Dompdf($options);
  7658.         $dompdf->loadHtml($html);
  7659.         $dompdf->setPaper('A4''portrait');
  7660.         $dompdf->render();
  7661.         // Sauvegarder le PDF
  7662.         file_put_contents($outputPath$dompdf->output());
  7663.         return $outputPath// Renvoie le chemin du fichier PDF généré
  7664.     }
  7665.     private function sendEmailWithPdfAttachmentThenDelete(
  7666.         array $params,
  7667.         string $mail,
  7668.         string $name,
  7669.         string $subject,
  7670.         int $templateId,
  7671.         string $pdfFilePath
  7672.     ): void {
  7673.         // Lire et encoder le contenu du PDF
  7674.         $attachment = [
  7675.             "name" => basename($pdfFilePath),
  7676.             "content" => base64_encode(file_get_contents($pdfFilePath)),
  7677.         ];
  7678.         // Construire les données pour l’API Sendinblue
  7679.         $data = [
  7680.             "sender" => [
  7681.                 "email" => 'noreply@myaudio.fr',
  7682.                 "name" => 'My Audio',
  7683.             ],
  7684.             "to" => [
  7685.                 [
  7686.                     "email" => $mail,
  7687.                     "name" => $name,
  7688.                 ],
  7689.             ],
  7690.             "subject" => $subject,
  7691.             "templateId" => $templateId,
  7692.             "params" => $params,
  7693.             "attachment" => [$attachment],
  7694.         ];
  7695.         // Envoi via cURL
  7696.         $ch curl_init();
  7697.         curl_setopt($chCURLOPT_URL'https://api.sendinblue.com/v3/smtp/email');
  7698.         curl_setopt($chCURLOPT_RETURNTRANSFER1);
  7699.         curl_setopt($chCURLOPT_POST1);
  7700.         curl_setopt($chCURLOPT_POSTFIELDSjson_encode($data));
  7701.         $headers = [
  7702.             'Accept: application/json',
  7703.             'Api-Key: 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',
  7704.             'Content-Type: application/json',
  7705.         ];
  7706.         curl_setopt($chCURLOPT_HTTPHEADER$headers);
  7707.         $result curl_exec($ch);
  7708.         if (curl_errno($ch)) {
  7709.             echo 'Erreur email : ' curl_error($ch);
  7710.         }
  7711.         curl_close($ch);
  7712.         // Supprimer le PDF après envoi
  7713.         if (file_exists($pdfFilePath)) {
  7714.             unlink($pdfFilePath);
  7715.         }
  7716.     }
  7717.     private function formatImploded(array $data): string
  7718.     {
  7719.         return implode(', 'array_map(function ($item) {
  7720.             return str_replace('_'' '$item);
  7721.         }, $data));
  7722.     }
  7723.     /**
  7724.      * 
  7725.      * @Route("/admin/rdv/export-pdf-form", name="admin_rdv_export_pdf_form", methods={"GET", "POST"})
  7726.      */
  7727.     public function exportPdfForm(Request $request): Response
  7728.     {
  7729.         $form $this->createFormBuilder()
  7730.             ->add('startDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  7731.                 'label' => 'Date de début',
  7732.                 'widget' => 'single_text',
  7733.                 'html5' => true,
  7734.                 'required' => true,
  7735.             ])
  7736.             ->add('endDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  7737.                 'label' => 'Date de fin',
  7738.                 'widget' => 'single_text',
  7739.                 'html5' => true,
  7740.                 'required' => true,
  7741.             ])
  7742.             ->add('format'\Symfony\Component\Form\Extension\Core\Type\ChoiceType::class, [
  7743.                 'label' => 'Format d\'export',
  7744.                 'choices' => [
  7745.                     'PDF' => 'pdf',
  7746.                     'Excel' => 'excel',
  7747.                 ],
  7748.                 'expanded' => false,
  7749.                 'multiple' => false,
  7750.                 'required' => true,
  7751.             ])
  7752.             ->getForm();
  7753.         //dd($request);
  7754.         $form->handleRequest($request);
  7755.         if ($form->isSubmitted() && $form->isValid()) {
  7756.             $data $form->getData();
  7757.             $start $data['startDate']->format('Y-m-d');
  7758.             $end $data['endDate']->format('Y-m-d');
  7759.             if ($data['format'] === 'pdf') {
  7760.                 return $this->redirectToRoute('admin_rdv_export_pdf', [
  7761.                     'startDate' => $start,
  7762.                     'endDate' => $end,
  7763.                 ]);
  7764.             } else {
  7765.                 return $this->redirectToRoute('admin_rdv_export_excel', [
  7766.                     'startDate' => $start,
  7767.                     'endDate' => $end,
  7768.                 ]);
  7769.             }
  7770.         }
  7771.         return $this->render('easyadmin/rdv/export_pdf_form.html.twig', [
  7772.             'form' => $form->createView(),
  7773.         ]);
  7774.     }
  7775.     /**
  7776.      * 
  7777.      * @Route("/optical/rdv/export-pdf-form", name="optical_rdv_export_pdf_form", methods={"GET", "POST"})
  7778.      */
  7779.     public function exportOpticalPdfForm(Request $request): Response
  7780.     {
  7781.         $form $this->createFormBuilder()
  7782.             ->add('startDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  7783.                 'label' => 'Date de début',
  7784.                 'widget' => 'single_text',
  7785.                 'html5' => true,
  7786.                 'required' => true,
  7787.             ])
  7788.             ->add('endDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  7789.                 'label' => 'Date de fin',
  7790.                 'widget' => 'single_text',
  7791.                 'html5' => true,
  7792.                 'required' => true,
  7793.             ])
  7794.             ->add('format'\Symfony\Component\Form\Extension\Core\Type\ChoiceType::class, [
  7795.                 'label' => 'Format d\'export',
  7796.                 'choices' => [
  7797.                     'PDF' => 'pdf',
  7798.                     'Excel' => 'excel',
  7799.                 ],
  7800.                 'expanded' => false,
  7801.                 'multiple' => false,
  7802.                 'required' => true,
  7803.             ])
  7804.             ->getForm();
  7805.         //dd($request);
  7806.         $form->handleRequest($request);
  7807.         if ($form->isSubmitted() && $form->isValid()) {
  7808.             $data $form->getData();
  7809.             $start $data['startDate']->format('Y-m-d');
  7810.             $end $data['endDate']->format('Y-m-d');
  7811.             if ($data['format'] === 'pdf') {
  7812.                 return $this->redirectToRoute('optical_rdv_export_pdf', [
  7813.                     'startDate' => $start,
  7814.                     'endDate' => $end,
  7815.                 ]);
  7816.             } else {
  7817.                 return $this->redirectToRoute('optical_rdv_export_excel', [
  7818.                     'startDate' => $start,
  7819.                     'endDate' => $end,
  7820.                 ]);
  7821.             }
  7822.         }
  7823.         return $this->render('easyadmin/rdv/export_pdf_form.html.twig', [
  7824.             'form' => $form->createView(),
  7825.         ]);
  7826.     }
  7827.     /**
  7828.      * @Route("/admin/lead-rdv/update-status", name="admin_lead_rdv_update_status", methods={"POST"})
  7829.      */
  7830.     public function updateStatus(Request $request): JsonResponse
  7831.     {
  7832.         // Récupérer les données envoyées en AJAX
  7833.         $data json_decode($request->getContent(), true);
  7834.         $leadId $data['leadId'] ?? null;
  7835.         $statusId $data['statusId'] ?? null;
  7836.         if (!$leadId || !$statusId) {
  7837.             return new JsonResponse(['success' => false'message' => 'Données manquantes'], 400);
  7838.         }
  7839.         // Récupérer le lead et le statut
  7840.         $lead $this->entityManager->getRepository(LeadRdv::class)->find($leadId);
  7841.         $status $this->entityManager->getRepository(LeadStatus::class)->find($statusId);
  7842.         if (!$lead || !$status) {
  7843.             return new JsonResponse(['success' => false'message' => 'Lead ou statut introuvable'], 404);
  7844.         }
  7845.         // Mettre à jour le statut du lead
  7846.         $lead->setLeadStatus($status);
  7847.         $this->entityManager->flush();
  7848.         return new JsonResponse(['success' => true]);
  7849.     }
  7850.     /**
  7851.      * @Route("/admin/rdv/update-client-status", name="admin_rdv_update_client_status", methods={"POST"})
  7852.      */
  7853.     public function updateClientStatus(Request $request): JsonResponse
  7854.     {
  7855.         $data json_decode($request->getContent(), true);
  7856.         $rdvId $data['rdvId'] ?? null;
  7857.         $statusId $data['statusId'] ?? null;
  7858.         if (!$rdvId || !$statusId) {
  7859.             return new JsonResponse(['success' => false'message' => 'Données manquantes'], 400);
  7860.         }
  7861.         // Récupérer le RDV
  7862.         $rdv $this->entityManager->getRepository(Rdv::class)->find($rdvId);
  7863.         if (!$rdv) {
  7864.             return new JsonResponse(['success' => false'message' => 'RDV non trouvé'], 404);
  7865.         }
  7866.         // Récupérer le statut
  7867.         $clientStatus $this->entityManager->getRepository(ClientStatus::class)->find($statusId);
  7868.         if (!$clientStatus) {
  7869.             return new JsonResponse(['success' => false'message' => 'Statut non trouvé'], 404);
  7870.         }
  7871.         // Mettre à jour le client
  7872.         $client $rdv->getIdClient();
  7873.         if ($client) {
  7874.             $client->setClientStatus($clientStatus);
  7875.             $this->entityManager->flush();
  7876.             // Si le statut est "Facturé", lancer la facturation
  7877.             if ((int)$statusId === 2) {
  7878.                 // Réutiliser la méthode de facturation existante
  7879.                 $crudController $this->container->get(RdvMyAudioCrudController::class);
  7880.                 $crudController->billing($rdv);
  7881.             }
  7882.             return new JsonResponse(['success' => true]);
  7883.         }
  7884.         return new JsonResponse(['success' => false'message' => 'Client non trouvé'], 404);
  7885.     }
  7886.     /**
  7887.      * @Route("/admin/rdv/update-rdv-status", name="admin_rdv_update_status", methods={"POST"})
  7888.      */
  7889.     public function updateRdvStatus(Request $requestEntityManagerInterface $entityManager): JsonResponse
  7890.     {
  7891.         $data json_decode($request->getContent(), true);
  7892.         $rdvId $data['rdvId'] ?? null;
  7893.         $statusId $data['statusId'] ?? null;
  7894.         if (!$rdvId || !$statusId) {
  7895.             return new JsonResponse(['success' => false'message' => 'Données manquantes'], 400);
  7896.         }
  7897.         // Récupérer le RDV
  7898.         $rdv $entityManager->getRepository(Rdv::class)->find($rdvId);
  7899.         if (!$rdv) {
  7900.             return new JsonResponse(['success' => false'message' => 'RDV non trouvé'], 404);
  7901.         }
  7902.         // Récupérer le statut
  7903.         $etatRdv $entityManager->getRepository(EtatRdv::class)->find($statusId);
  7904.         if (!$etatRdv) {
  7905.             return new JsonResponse(['success' => false'message' => 'Statut non trouvé'], 404);
  7906.         }
  7907.         // Mettre à jour le statut du RDV
  7908.         $rdv->setIdEtat($etatRdv);
  7909.         $entityManager->flush();
  7910.         return new JsonResponse(['success' => true]);
  7911.     }
  7912.     /**
  7913.      * @Route("/admin/rdv/export-pdf/{startDate}/{endDate}", name="admin_rdv_export_pdf", methods={"GET"})
  7914.      */
  7915.     public function exportPdfFromDate(string $startDatestring $endDateKernelInterface $kernel): Response
  7916.     {
  7917.         $start = new \DateTimeImmutable($startDate);
  7918.         $end = new \DateTimeImmutable($endDate);
  7919.         $today = new \DateTimeImmutable();
  7920.         $rdvs $this->rdvRepository->findBySinceDateAndMyAudio($start$end);
  7921.         $html "
  7922.     <html>
  7923.     <head>
  7924.         <style>
  7925.             body { font-family: Arial, sans-serif; font-size: 13px; }
  7926.             table { width: 100%; border-collapse: collapse; font-size: 11px; }
  7927.             th, td { border: 1px solid #000; padding: 5px; text-align: left; }
  7928.             th { font-weight: bold; }
  7929.             h1 { font-size: 14px; }
  7930.         </style>
  7931.     </head>
  7932.     <body>
  7933.         <h1>Rendez-vous My Audio du " $start->format('d/m/Y') . " au " $end->format('d/m/Y') . "</h1>
  7934.         <table cellspacing='0' cellpadding='5'>
  7935.             <thead>
  7936.                 <tr>
  7937.                     <th>ID du RDV</th>
  7938.                     <th>Date du RDV</th>
  7939.                     <th>Jours écoulés</th>
  7940.                     <th>Statut RDV</th>
  7941.                     <th>Nom patient</th>
  7942.                     <th>Téléphone patient</th>
  7943.                     <th>Statut patient</th>
  7944.                     <th>Centre</th>
  7945.                     <th>Téléphone Centre</th>
  7946.                     <th>Adresse</th>
  7947.                     <th>Nom Audio</th>
  7948.                 </tr>
  7949.             </thead>
  7950.             <tbody>";
  7951.         foreach ($rdvs as $rdv) {
  7952.             $dateRdv $rdv->getDate();
  7953.             $joursEcoules $dateRdv->diff($today)->days;
  7954.             $client $rdv->getIdClient();
  7955.             $centre $rdv->getIdCentre();
  7956.             $etat $rdv->getIdEtat();
  7957.             $audio $rdv->getIdAudio();
  7958.             $html .= "<tr>
  7959.             <td>" $rdv->getId() . "</td>
  7960.             <td>" $dateRdv->format('d/m/Y H:i') . "</td>
  7961.             <td>" $joursEcoules " jours</td>
  7962.             <td>" . ($etat htmlspecialchars($etat->getLibelle()) : 'Non défini') . "</td>
  7963.             <td>" . ($client htmlspecialchars($client->getName() . ' ' $client->getLastname()) : '') . "</td>
  7964.             <td>" . ($client htmlspecialchars($client->getPhone()) : '') . "</td>
  7965.             <td>" . ($client && $client->getClientStatus() ? htmlspecialchars($client->getClientStatus()->getLibelle()) : 'Non défini') . "</td>
  7966.             <td>" . ($centre htmlspecialchars($centre->getName()) : '') . "</td>
  7967.             <td>" . ($centre htmlspecialchars($centre->getPhone()) : '') . "</td>
  7968.             <td>" . ($centre htmlspecialchars($centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity()) : '') . "</td>
  7969.             <td>" . ($audio htmlspecialchars($audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastname()) : '') . "</td>
  7970.         </tr>";
  7971.         }
  7972.         $html .= "</tbody></table></body></html>";
  7973.         // Configuration et rendu du PDF
  7974.         $options = new Options();
  7975.         $options->set('defaultFont''Arial');
  7976.         $dompdf = new Dompdf($options);
  7977.         $dompdf->loadHtml($html);
  7978.         $dompdf->setPaper('A4''landscape');
  7979.         $dompdf->render();
  7980.         // Création du dossier s'il n'existe pas
  7981.         $projectDir $kernel->getProjectDir();
  7982.         $outputDir $projectDir '/public/assets/pdf/rdv';
  7983.         $filesystem = new Filesystem();
  7984.         if (!$filesystem->exists($outputDir)) {
  7985.             $filesystem->mkdir($outputDir0775);
  7986.         }
  7987.         $filenameDate $start->format('Y-m-d') . '_to_' $end->format('Y-m-d');
  7988.         $outputPath "$outputDir/rdvs-$filenameDate.pdf";
  7989.         file_put_contents($outputPath$dompdf->output());
  7990.         return new Response($dompdf->output(), 200, [
  7991.             'Content-Type' => 'application/pdf',
  7992.             'Content-Disposition' => 'attachment; filename="rdvs-' $filenameDate '.pdf"',
  7993.         ]);
  7994.     }
  7995.     /**
  7996.      * @Route("/optical/rdv/export-pdf/{startDate}/{endDate}", name="optical_rdv_export_pdf", methods={"GET"})
  7997.      */
  7998.     public function exportOpticalPdfFromDate(string $startDatestring $endDateKernelInterface $kernel): Response
  7999.     {
  8000.         $start = new \DateTimeImmutable($startDate);
  8001.         $end = new \DateTimeImmutable($endDate);
  8002.         $today = new \DateTimeImmutable();
  8003.         $rdvs $this->rdvRepository->findOpticalBySinceDateAndMyAudio($start$end);
  8004.         $html "
  8005.     <html>
  8006.     <head>
  8007.         <style>
  8008.             body { font-family: Arial, sans-serif; font-size: 13px; }
  8009.             table { width: 100%; border-collapse: collapse; font-size: 11px; }
  8010.             th, td { border: 1px solid #000; padding: 5px; text-align: left; }
  8011.             th { font-weight: bold; }
  8012.             h1 { font-size: 14px; }
  8013.         </style>
  8014.     </head>
  8015.     <body>
  8016.         <h1>Rendez-vous My Audio du " $start->format('d/m/Y') . " au " $end->format('d/m/Y') . "</h1>
  8017.         <table cellspacing='0' cellpadding='5'>
  8018.             <thead>
  8019.                 <tr>
  8020.                     <th>ID du RDV</th>
  8021.                     <th>Date du RDV</th>
  8022.                     <th>Jours écoulés</th>
  8023.                     <th>Statut RDV</th>
  8024.                     <th>Nom patient</th>
  8025.                     <th>Téléphone patient</th>
  8026.                     <th>Statut patient</th>
  8027.                     <th>Centre</th>
  8028.                     <th>Téléphone Centre</th>
  8029.                     <th>Adresse</th>
  8030.                     <th>Nom Audio</th>
  8031.                 </tr>
  8032.             </thead>
  8033.             <tbody>";
  8034.         foreach ($rdvs as $rdv) {
  8035.             $dateRdv $rdv->getDate();
  8036.             $joursEcoules $dateRdv->diff($today)->days;
  8037.             $client $rdv->getIdClient();
  8038.             $centre $rdv->getIdCentre();
  8039.             $etat $rdv->getIdEtat();
  8040.             $audio $rdv->getIdAudio();
  8041.             $html .= "<tr>
  8042.             <td>" $rdv->getId() . "</td>
  8043.             <td>" $dateRdv->format('d/m/Y H:i') . "</td>
  8044.             <td>" $joursEcoules " jours</td>
  8045.             <td>" . ($etat htmlspecialchars($etat->getLibelle()) : 'Non défini') . "</td>
  8046.             <td>" . ($client htmlspecialchars($client->getName() . ' ' $client->getLastname()) : '') . "</td>
  8047.             <td>" . ($client htmlspecialchars($client->getPhone()) : '') . "</td>
  8048.             <td>" . ($client && $client->getClientStatus() ? htmlspecialchars($client->getClientStatus()->getLibelle()) : 'Non défini') . "</td>
  8049.             <td>" . ($centre htmlspecialchars($centre->getName()) : '') . "</td>
  8050.             <td>" . ($centre htmlspecialchars($centre->getPhone()) : '') . "</td>
  8051.             <td>" . ($centre htmlspecialchars($centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity()) : '') . "</td>
  8052.             <td>" . ($audio htmlspecialchars($audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastname()) : '') . "</td>
  8053.         </tr>";
  8054.         }
  8055.         $html .= "</tbody></table></body></html>";
  8056.         // Configuration et rendu du PDF
  8057.         $options = new Options();
  8058.         $options->set('defaultFont''Arial');
  8059.         $dompdf = new Dompdf($options);
  8060.         $dompdf->loadHtml($html);
  8061.         $dompdf->setPaper('A4''landscape');
  8062.         $dompdf->render();
  8063.         // Création du dossier s'il n'existe pas
  8064.         $projectDir $kernel->getProjectDir();
  8065.         $outputDir $projectDir '/public/assets/pdf/rdv';
  8066.         $filesystem = new Filesystem();
  8067.         if (!$filesystem->exists($outputDir)) {
  8068.             $filesystem->mkdir($outputDir0775);
  8069.         }
  8070.         $filenameDate $start->format('Y-m-d') . '_to_' $end->format('Y-m-d');
  8071.         $outputPath "$outputDir/rdvs-$filenameDate.pdf";
  8072.         file_put_contents($outputPath$dompdf->output());
  8073.         return new Response($dompdf->output(), 200, [
  8074.             'Content-Type' => 'application/pdf',
  8075.             'Content-Disposition' => 'attachment; filename="rdvs-' $filenameDate '.pdf"',
  8076.         ]);
  8077.     }
  8078.     /**
  8079.      * 
  8080.      * @Route("/admin/rdv/export/excel/{startDate}/{endDate}", name="admin_rdv_export_excel", methods={"GET"})
  8081.      */
  8082.     public function exportExcelFromDate(string $startDatestring $endDate): Response
  8083.     {
  8084.         $start = new \DateTimeImmutable($startDate);
  8085.         $end = new \DateTimeImmutable($endDate);
  8086.         $rdvs $this->rdvRepository->findBySinceDateAndMyAudio($start$end);
  8087.         $spreadsheet = new Spreadsheet();
  8088.         $sheet $spreadsheet->getActiveSheet();
  8089.         // Headers
  8090.         $sheet->fromArray([
  8091.             'ID du RDV',
  8092.             'Date du RDV',
  8093.             'Jours écoulés',
  8094.             'Statut RDV',
  8095.             'Nom patient',
  8096.             'Téléphone patient',
  8097.             'Statut patient',
  8098.             'Centre',
  8099.             'Téléphone Centre',
  8100.             'Adresse',
  8101.             'Nom Audio'
  8102.         ], null'A1');
  8103.         $today = new \DateTimeImmutable();
  8104.         $row 2;
  8105.         foreach ($rdvs as $rdv) {
  8106.             $dateRdv $rdv->getDate();
  8107.             $joursEcoules $dateRdv->diff($today)->days;
  8108.             $client $rdv->getIdClient();
  8109.             $centre $rdv->getIdCentre();
  8110.             $etat $rdv->getIdEtat();
  8111.             $sheet->fromArray([
  8112.                 $rdv->getId(),
  8113.                 $dateRdv->format('d/m/Y H:i'),
  8114.                 $joursEcoules ' jours',
  8115.                 $etat $etat->getLibelle() : 'Non défini',
  8116.                 $client $client->getName() . ' ' $client->getLastname() : '',
  8117.                 $client $client->getPhone() : '',
  8118.                 $client && $client->getClientStatus() ? $client->getClientStatus()->getLibelle() : 'Non défini',
  8119.                 $centre $centre->getName() : '',
  8120.                 $centre $centre->getPhone() : '',
  8121.                 $centre $centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity() : '',
  8122.                 $rdv->getIdAudio() ? $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastname() : '',
  8123.             ], null'A' $row);
  8124.             $row++;
  8125.         }
  8126.         $writer = new Xlsx($spreadsheet);
  8127.         $filename "rdvs-$startDate-to-$endDate.xlsx";
  8128.         // Stream the file to browser
  8129.         $response = new \Symfony\Component\HttpFoundation\StreamedResponse(function () use ($writer) {
  8130.             $writer->save('php://output');
  8131.         });
  8132.         $dispositionHeader $response->headers->makeDisposition(
  8133.             \Symfony\Component\HttpFoundation\ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  8134.             $filename
  8135.         );
  8136.         $response->headers->set('Content-Type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  8137.         $response->headers->set('Content-Disposition'$dispositionHeader);
  8138.         return $response;
  8139.     }
  8140.     /**
  8141.      * 
  8142.      * @Route("/optical/rdv/export/excel/{startDate}/{endDate}", name="optical_rdv_export_excel", methods={"GET"})
  8143.      */
  8144.     public function exportOpticalExcelFromDate(string $startDatestring $endDate): Response
  8145.     {
  8146.         $start = new \DateTimeImmutable($startDate);
  8147.         $end = new \DateTimeImmutable($endDate);
  8148.         $rdvs $this->rdvRepository->findOpticalBySinceDateAndMyAudio($start$end);
  8149.         $spreadsheet = new Spreadsheet();
  8150.         $sheet $spreadsheet->getActiveSheet();
  8151.         // Headers
  8152.         $sheet->fromArray([
  8153.             'ID du RDV',
  8154.             'Date du RDV',
  8155.             'Jours écoulés',
  8156.             'Statut RDV',
  8157.             'Nom patient',
  8158.             'Téléphone patient',
  8159.             'Statut patient',
  8160.             'Centre',
  8161.             'Téléphone Centre',
  8162.             'Adresse',
  8163.             'Nom Audio'
  8164.         ], null'A1');
  8165.         $today = new \DateTimeImmutable();
  8166.         $row 2;
  8167.         foreach ($rdvs as $rdv) {
  8168.             $dateRdv $rdv->getDate();
  8169.             $joursEcoules $dateRdv->diff($today)->days;
  8170.             $client $rdv->getIdClient();
  8171.             $centre $rdv->getIdCentre();
  8172.             $etat $rdv->getIdEtat();
  8173.             $sheet->fromArray([
  8174.                 $rdv->getId(),
  8175.                 $dateRdv->format('d/m/Y H:i'),
  8176.                 $joursEcoules ' jours',
  8177.                 $etat $etat->getLibelle() : 'Non défini',
  8178.                 $client $client->getName() . ' ' $client->getLastname() : '',
  8179.                 $client $client->getPhone() : '',
  8180.                 $client && $client->getClientStatus() ? $client->getClientStatus()->getLibelle() : 'Non défini',
  8181.                 $centre $centre->getName() : '',
  8182.                 $centre $centre->getPhone() : '',
  8183.                 $centre $centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity() : '',
  8184.                 $rdv->getIdAudio() ? $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastname() : '',
  8185.             ], null'A' $row);
  8186.             $row++;
  8187.         }
  8188.         $writer = new Xlsx($spreadsheet);
  8189.         $filename "rdvs-$startDate-to-$endDate.xlsx";
  8190.         // Stream the file to browser
  8191.         $response = new \Symfony\Component\HttpFoundation\StreamedResponse(function () use ($writer) {
  8192.             $writer->save('php://output');
  8193.         });
  8194.         $dispositionHeader $response->headers->makeDisposition(
  8195.             \Symfony\Component\HttpFoundation\ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  8196.             $filename
  8197.         );
  8198.         $response->headers->set('Content-Type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  8199.         $response->headers->set('Content-Disposition'$dispositionHeader);
  8200.         return $response;
  8201.     }
  8202.     /**
  8203.      * 
  8204.      * @Route("/admin/update-note", name="update_note", methods={"POST"})
  8205.      */
  8206.     public function updateNote(Request $requestEntityManagerInterface $em): JsonResponse
  8207.     {
  8208.         $data json_decode($request->getContent(), true);
  8209.         $id $data['id'] ?? null;
  8210.         $note $data['note'] ?? null;
  8211.         if (!$id || $note === null) {
  8212.             return new JsonResponse(['status' => 'error''message' => 'Invalid data'], 400);
  8213.         }
  8214.         $entity $em->getRepository(Rdv::class)->find($id);
  8215.         if (!$entity) {
  8216.             return new JsonResponse(['status' => 'error''message' => 'Entity not found'], 404);
  8217.         }
  8218.         $entity->setNote($note);
  8219.         $em->flush();
  8220.         return new JsonResponse(['status' => 'success']);
  8221.     }
  8222.     /**
  8223.      * 
  8224.      * @Route("/giuili-admin/edit-rdv/{rdvId}/centre/{centreId}", name="update_admin_rdv", methods={"GET"})
  8225.      */
  8226.     public function showRdvCentre(int $rdvIdCentre $centreId): Response
  8227.     {
  8228.         // dd("tets");
  8229.         $center $centres $this->getDoctrine()
  8230.             ->getRepository(AudioCentre::class)
  8231.             ->findOneBy(['id_centre' => $centreId->getId()]);
  8232.         $audio $center->getIdAudio();
  8233.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  8234.             ->findBy(['id_audio' => $audio'isDeleted' => 0]);
  8235.         return $this->render('easyadmin/rdv/centre_show.html.twig', [
  8236.             'audio' => $audio,
  8237.             'rdvId' => $rdvId,
  8238.             'centreId' => $centreId,
  8239.             'motifs' => $motifs,
  8240.         ]);
  8241.     }
  8242.     
  8243.     /**
  8244.      * 
  8245.      * @Route("/optical-center/edit-rdv/{rdvId}/centre/{centreId}", name="update_optical_rdv", methods={"GET"})
  8246.      */
  8247.     public function showRdvCentreOptical(int $rdvIdCentre $centreId): Response
  8248.     {
  8249.         // dd("tets");
  8250.         $center $centres $this->getDoctrine()
  8251.             ->getRepository(AudioCentre::class)
  8252.             ->findOneBy(['id_centre' => $centreId->getId()]);
  8253.         $audio $center->getIdAudio();
  8254.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  8255.             ->findBy(['id_audio' => $audio'isDeleted' => 0]);
  8256.         return $this->render('easyadmin/rdv/centre_show.html.twig', [
  8257.             'audio' => $audio,
  8258.             'rdvId' => $rdvId,
  8259.             'centreId' => $centreId,
  8260.             'motifs' => $motifs,
  8261.         ]);
  8262.     }
  8263.     /**
  8264.      * @Route("/update-rdv-easyadmin", name="update_rdv_easyadmin", methods={"POST"})
  8265.      */
  8266.     public function updateRdvEasyadmin(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  8267.     {
  8268.         $data json_decode($request->getContent(), true);
  8269.         $rdv $this->getDoctrine()
  8270.             ->getRepository(Rdv::class)
  8271.             ->find($data["rdv_id"]);
  8272.         $pastDate $rdv->getDate();
  8273.         $entityManager $this->getDoctrine()->getManager();
  8274.         if (isset($data["etat_id"])) {
  8275.             $etat $this->getDoctrine()
  8276.                 ->getRepository(EtatRdv::class)
  8277.                 ->findOneBy(['id' => $data["etat_id"]]);
  8278.             if ($etat == null) {
  8279.                 return new Response(json_encode(([
  8280.                     'message' => 'Error, no etat found at this id',
  8281.                     'path' => 'src/Controller/TrustedUserController.php',
  8282.                     "status" => 400,
  8283.                 ])), 400);
  8284.             }
  8285.             $rdv->setIdEtat($etat);
  8286.         }
  8287.         if (isset($data["audio_id"])) {
  8288.             $audio $this->getDoctrine()
  8289.                 ->getRepository(Audio::class)
  8290.                 ->findOneBy(['id' => $data["audio_id"]]);
  8291.             if ($audio == null) {
  8292.                 return new Response(json_encode(([
  8293.                     'message' => 'Error, no audio found at this id',
  8294.                     'path' => 'src/Controller/TrustedUserController.php',
  8295.                     "status" => 400,
  8296.                 ])), 400);
  8297.             }
  8298.             $rdv->setIdAudio($audio);
  8299.         }
  8300.         if (isset($data["motif_id"])) {
  8301.             $motif $this->getDoctrine()
  8302.                 ->getRepository(Motif::class)
  8303.                 ->find($data["motif_id"]);
  8304.             if ($motif == null) {
  8305.                 return new Response(json_encode(([
  8306.                     'message' => 'Error, no motif found at this id',
  8307.                     'path' => 'src/Controller/TrustedUserController.php',
  8308.                     "status" => 400,
  8309.                 ])), 400);
  8310.             }
  8311.             $rdv->setIdMotif($motif);
  8312.         }
  8313.         if (isset($data["client_id"])) {
  8314.             $client $this->getDoctrine()
  8315.                 ->getRepository(Client::class)
  8316.                 ->findOneBy(['id' => $data["client_id"]]);
  8317.             if ($client == null) {
  8318.                 return new Response(json_encode(([
  8319.                     'message' => 'Error, no client found at this id',
  8320.                     'path' => 'src/Controller/TrustedUserController.php',
  8321.                     "status" => 400,
  8322.                 ])), 400);
  8323.             }
  8324.             $rdv->setIdClient($client);
  8325.         }
  8326.         if (isset($data["date"])) {
  8327.             $data["date"] = str_replace("h"":"$data["date"]);
  8328.             $date \DateTime::createFromFormat("Y-m-d\TH:i"$data["date"]);
  8329.             $audioMotif $this->getDoctrine()
  8330.                 ->getRepository(AudioMotif::class)
  8331.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  8332.             if ($audioMotif == null) {
  8333.                 return new Response(json_encode(([
  8334.                     'message' => 'Error, no motif of this id found at this audio',
  8335.                     'path' => 'src/Controller/RdvController.php',
  8336.                     "status" => 400,
  8337.                 ])), 400);
  8338.             }
  8339.             if ($rdv->getIdAudio()->getIsIndie()) {
  8340.                 if ($rdv->getIdCentre()) {
  8341.                     // regular centre audio indie
  8342.                     /** @var AudioCentre */
  8343.                     $liaison $this->getDoctrine()
  8344.                         ->getRepository(AudioCentre::class)
  8345.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  8346.                     if ($liaison == null) {
  8347.                         return new Response(json_encode(([
  8348.                             'message' => 'Error, audio isnt part of the centre',
  8349.                             'path' => 'src/Controller/RdvController.php',
  8350.                             "status" => 400,
  8351.                         ])), 400);
  8352.                     }
  8353.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  8354.                         return new Response(json_encode(([
  8355.                             'message' => 'Error, no horaire found for this audio',
  8356.                             'path' => 'src/Controller/RdvController.php',
  8357.                             "status" => 400,
  8358.                         ])), 400);
  8359.                     }
  8360.                 } else {
  8361.                     // lieu audio indie
  8362.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  8363.                         return new Response(json_encode(([
  8364.                             'message' => 'Error, no horaire found for this audio',
  8365.                             'path' => 'src/Controller/RdvController.php',
  8366.                             "status" => 400,
  8367.                         ])), 400);
  8368.                     }
  8369.                 }
  8370.             } else {
  8371.                 // regular centre
  8372.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  8373.                     return new Response(json_encode(([
  8374.                         'message' => 'Error, no horaire found for this audio',
  8375.                         'path' => 'src/Controller/RdvController.php',
  8376.                         "status" => 400,
  8377.                     ])), 400);
  8378.                 }
  8379.             }
  8380.             $rdv->setDate($date);
  8381.         }
  8382.         if (isset($data["comment"]) && $token->getIdClient()) {
  8383.             $rdv->setComment($data["comment"]);
  8384.         }
  8385.         if (isset($data["review"]) && $token->getIdClient()) {
  8386.             $rdv->setReview($data["review"]);
  8387.         }
  8388.         if (isset($data["note"])) {
  8389.             $rdv->setNote($data["note"]);
  8390.         }
  8391.         $entityManager->flush();
  8392.         $date $rdv->getDate();
  8393.         $smsDate $date->format('d-m-Y H:i');
  8394.         $oldDate $pastDate->format('d-m-Y H:i');
  8395.         $locale 'fr_FR';
  8396.         $formatter = new IntlDateFormatter(
  8397.             $locale,
  8398.             IntlDateFormatter::FULL,
  8399.             IntlDateFormatter::SHORT,
  8400.             null,
  8401.             IntlDateFormatter::GREGORIAN,
  8402.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  8403.         );
  8404.         $smsDateLongFormat $formatter->format($date);
  8405.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  8406.         $frenchDate ucfirst($frenchDate);
  8407.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  8408.         // notif client
  8409.         if ($rdv->getIdEtat()->getId() != 2) {
  8410.             $params = array(
  8411.                 "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  8412.                 "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  8413.                 "date" => $smsDateLongFormat,
  8414.                 "heure" => substr($smsDate1115),
  8415.                 "motif" => $rdv->getIdMotif()->getTitre(),
  8416.                 "centerName" => $rdv->getIdCentre()->getName(),
  8417.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  8418.                 "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  8419.                 "audioMail" => $rdv->getIdAudio()->getMail(),
  8420.                 "centerPhone" => $rdv->getIdCentre()->getPhone(),
  8421.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  8422.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  8423.                 'titre' => 'Votre rendez-vous est modifié pour le',
  8424.                 'frenchDate' => $frenchDate,
  8425.             );
  8426.             $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  8427.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  8428.             $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.";
  8429.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  8430.         }
  8431.         //     //// == suppression
  8432.         else if ($rdv->getIdEtat()->getId() == 2) {
  8433.             $params = array(
  8434.                 "date" => substr($smsDate010),
  8435.                 "lien" => "{$_ENV['BASE_client']}search",
  8436.                 "heure" => substr($smsDate1115),
  8437.                 "patientName" => $client->getLastName(),
  8438.                 'titre' => 'Votre rendez-vous est annulé :',
  8439.                 'centerName' => $rdv->getIdCentre()->getName(),
  8440.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  8441.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  8442.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  8443.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  8444.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  8445.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  8446.                 'motif' => $rdv->getIdMotif()->getTitre(),
  8447.             );
  8448.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  8449.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  8450.             if ($data["sms"]) {
  8451.                 $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  8452.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  8453.             }
  8454.         }
  8455.         //notif Audio
  8456.         if ($rdv->getIdEtat()->getId() != 2) {
  8457.             $params = array(
  8458.                 "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  8459.                 "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  8460.                 "date" => substr($smsDate010),
  8461.                 "frenchDate" => $frenchDate,
  8462.                 "heure" => substr($smsDate1115),
  8463.                 'motif' => $rdv->getIdMotif()->getTitre(),
  8464.                 'clientPhone' => $client->getPhone(),
  8465.                 'clientNom' => $client->getLastname(),
  8466.                 'clientPrenom' => $client->getName(),
  8467.                 'clientCivilite' => $client->getCivilite(),
  8468.                 'clientPostal' => $client->getPostal(),
  8469.                 'clientMail' => $client->getMail(),
  8470.                 'centerName' => $rdv->getIdCentre()->getName(),
  8471.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  8472.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  8473.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  8474.                 'idPatient' => $client->getId(),
  8475.                 'proUrl' => "{$_ENV['BASE_logiciel']}",
  8476.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  8477.                 'titre' => 'Votre rendez-vous est modifié pour le :'
  8478.             );
  8479.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  8480.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  8481.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  8482.                 $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  8483.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  8484.             }
  8485.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  8486.                 $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.";
  8487.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  8488.             }
  8489.         } else if ($rdv->getIdEtat()->getId() == 2) {
  8490.             $params = array(
  8491.                 "date" => substr($smsDate010),
  8492.                 "lien" => "{$_ENV['BASE_client']}search",
  8493.                 "heure" => substr($smsDate1115),
  8494.                 "patientName" => $client->getLastName(),
  8495.                 'titre' => 'Votre rendez-vous est annulé :',
  8496.                 'centerName' => $rdv->getIdCentre()->getName(),
  8497.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  8498.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  8499.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  8500.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  8501.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  8502.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  8503.                 'motif' => $rdv->getIdMotif()->getTitre(),
  8504.             );
  8505.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  8506.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  8507.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  8508.                 $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  8509.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject188);
  8510.             }
  8511.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  8512.                 $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.";
  8513.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  8514.             }
  8515.         }
  8516.         /* generate sms notif on update */
  8517.         // update sms notification     
  8518.         $rdvSms->updateRdvSms($rdv);
  8519.         // google calendar update
  8520.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  8521.             ->findBy(array('audio' => $rdv->getIdAudio()));
  8522.         $data['rdv'] = $rdv->getId();
  8523.         $data['motif_id'] = $rdv->getIdMotif();
  8524.         $data['note'] = $rdv->getNote();
  8525.         if ($rdv->getIdClient() !== null) {
  8526.             $data["client_id"] = $rdv->getIdClient()->getId();
  8527.         }
  8528.         if ($rdv->getIdClientTemp() !== null) {
  8529.             $data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
  8530.         }
  8531.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  8532.             ->findBy(array('rdv' => $rdv));
  8533.         foreach ($rdvEvents as $rdvEvent) {
  8534.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  8535.             $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  8536.         }
  8537.         return new Response(json_encode(([
  8538.             "id" => $rdv->getId(),
  8539.             "motif_id" => $rdv->getIdMotif()->getId(),
  8540.             "audio_id" => $rdv->getIdAudio()->getId(),
  8541.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  8542.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  8543.             "fullName" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  8544.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  8545.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  8546.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  8547.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  8548.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  8549.             "centre_id" => $rdv->getIdCentre()->getId(),
  8550.             "centerName" => $rdv->getIdCentre()->getName(),
  8551.             "etat_id" => $rdv->getIdEtat()->getId(),
  8552.             "date" => $rdv->getDate(),
  8553.             "comment" => $rdv->getComment(),
  8554.             "note" => $rdv->getNote(),
  8555.             "review" => $rdv->getReview(),
  8556.             "status" => 200,
  8557.         ])));
  8558.     }
  8559.     private function checkRdvReminder($rdv): ?array
  8560.     {
  8561.         $dateRdv $rdv->getDate();
  8562.         $today = new \DateTime();
  8563.         $today->setTime(000);
  8564.         $dateRdv->setTime(000);
  8565.         $intervalDays $today->diff($dateRdv)->days;
  8566.         if ($intervalDays === 1) {
  8567.             $interval "24";
  8568.         } elseif ($intervalDays === 2) {
  8569.             $interval "48";
  8570.         } elseif ($intervalDays === 3) {
  8571.             $interval "72";
  8572.         } elseif ($intervalDays === 4) {
  8573.             $interval "96";
  8574.         } else { // >= 4 jours
  8575.             $interval "92";
  8576.         }
  8577.         $client $rdv->getIdClientTemp() ?: $rdv->getIdClient();
  8578.         $clientId $client $client->getId() : null;
  8579.         $clientName null;
  8580.         if ($client) {
  8581.             $clientName $client->getName() . ' ' $client->getLastName();
  8582.         }
  8583.         $motif $rdv->getIdMotif();
  8584.         $motifTitle $motif $motif->getTitre() : null;
  8585.         $centre $rdv->getIdCentre();
  8586.         $centreName null;
  8587.         if ($centre) {
  8588.             $centreName $centre->getName();
  8589.         }
  8590.         return [
  8591.             'rdvId' => $rdv->getId(),
  8592.             'clientId' => $clientId,
  8593.             'clientName' => $clientName ?? 'N/A',
  8594.             'interval' => $interval,
  8595.             'date' => $rdv->getDate() ? $rdv->getDate()->format('d-m-Y H:i') : null,
  8596.             'motif' => $motifTitle ?? 'N/A',
  8597.             'centreName' => $centreName ?? 'N/A',
  8598.         ];
  8599.     }
  8600. }