src/Controller/RdvController.php line 7140

Open in your IDE?
  1. <?php
  2. namespace App\Controller;
  3. use DateTime;
  4. use DateInterval;
  5. use DateTimeZone;
  6. use Dompdf\Dompdf;
  7. use App\Entity\Rdv;
  8. use Dompdf\Options;
  9. use App\Entity\Lieu;
  10. use App\Entity\Audio;
  11. use App\Entity\Motif;
  12. use App\Entity\Referral;
  13. use App\Entity\Token;
  14. use Twig\Environment;
  15. use App\Entity\Centre;
  16. use App\Entity\Client;
  17. use \IntlDateFormatter;
  18. use App\Entity\CallLog;
  19. use App\Entity\EtatRdv;
  20. use App\Entity\LeadRdv;
  21. use App\Entity\Proches;
  22. use App\Entity\LieuTier;
  23. use App\Entity\RdvEvent;
  24. use App\Entity\AudioMotif;
  25. use App\Entity\CentreTier;
  26. use App\Entity\ClientTemp;
  27. use App\Entity\LeadStatus;
  28. use App\Entity\Remplacant;
  29. use App\Entity\TestClient;
  30. use App\Entity\AudioCentre;
  31. use App\Service\SmsHandler;
  32. use App\Entity\AccessCentre;
  33. use App\Entity\ClientStatus;
  34. use Psr\Log\LoggerInterface;
  35. use App\Entity\ClientBlocked;
  36. use App\Entity\CentreMutuelle;
  37. use App\Entity\LieuPrestation;
  38. use App\Entity\AudioSpecialite;
  39. use App\Entity\CallInteraction;
  40. use App\Service\PublicFunction;
  41. use App\Entity\CentrePrestation;
  42. use App\Entity\RegionDepartment;
  43. use App\Repository\RdvRepository;
  44. use Symfony\Component\Mime\Email;
  45. use App\Entity\Device\ClientDevice;
  46. use App\Entity\Notification\RdvSms;
  47. use App\Service\Lead\TwilioService;
  48. use App\Service\Lead\WhatsappService;
  49. use App\Entity\SynchronisationSetting;
  50. use App\Service\Lead\SynthflowService;
  51. use App\Service\Lead\ElevenLabsService;
  52. use Doctrine\ORM\EntityManagerInterface;
  53. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  54. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  55. use Symfony\Contracts\Cache\ItemInterface;
  56. use App\Service\Cosium\ClientCosiumService;
  57. use App\Service\Notification\RdvSmsService;
  58. use App\Entity\SpecificSubscription;
  59. use Symfony\Contracts\Cache\CacheInterface;
  60. use App\Entity\Synchronisation\CosiumCenter;
  61. use App\Service\Lead\AppointmentCallService;
  62. use Symfony\Component\Filesystem\Filesystem;
  63. use Symfony\Component\HttpFoundation\Request;
  64. use Symfony\Component\Mailer\MailerInterface;
  65. use Symfony\Component\HttpFoundation\Response;
  66. use Symfony\Component\Routing\Annotation\Route;
  67. use Doctrine\Common\Collections\ArrayCollection;
  68. use App\EasyAdmin\Controller\DashboardController;
  69. use Symfony\Component\HttpKernel\KernelInterface;
  70. use Symfony\Component\HttpFoundation\JsonResponse;
  71. use App\EasyAdmin\Controller\LeadRdvCrudController;
  72. use App\Service\AdsCompany\RepresentativeCdaService;
  73. use App\Entity\Synchronisation\SynchronisationCosium;
  74. use App\Service\GoogleCalendar\GoogleCalendarService;
  75. use App\EasyAdmin\Controller\RdvMyAudioCrudController;
  76. use App\Service\Notification\EmailNotificationService;
  77. use Symfony\Component\HttpFoundation\BinaryFileResponse;
  78. use EasyCorp\Bundle\EasyAdminBundle\Router\AdminUrlGenerator;
  79. use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
  80. use Symfony\Component\Mercure\PublisherInterface;
  81. use Symfony\Component\Mercure\Update;
  82. use App\Service\Mercure\MercureService;
  83. class RdvController extends AbstractController
  84. {
  85.     private $emailNotificationService;
  86.     private $clientCosiumService;
  87.     private $rdvRepository;
  88.     private $entityManager;
  89.     private $cache;
  90.     private $mercure;
  91.     private $twig;
  92.     private AdminUrlGenerator $adminUrlGenerator;
  93.     private WhatsappService $whatsapp;
  94.     private LoggerInterface $logger;  // Service de journalisation
  95.     private RdvRepository $rdvRepo;
  96.     public function __construct(CacheInterface $cacheEntityManagerInterface $entityManagerRdvRepository $rdvRepoEmailNotificationService $emailNotificationServiceClientCosiumService $clientCosiumServiceRdvRepository $rdvRepositoryEnvironment $twigAdminUrlGenerator $adminUrlGeneratorWhatsappService $whatsappLoggerInterface $logger,MercureService $mercure)
  97.     {
  98.         $this->entityManager $entityManager;
  99.         $this->emailNotificationService $emailNotificationService;
  100.         $this->clientCosiumService $clientCosiumService;
  101.         $this->rdvRepository $rdvRepository;
  102.         $this->cache $cache;
  103.         $this->twig $twig;
  104.         $this->adminUrlGenerator $adminUrlGenerator;
  105.         $this->whatsapp $whatsapp;
  106.         $this->logger $logger;
  107.         $this->rdvRepo $rdvRepo;
  108.         $this->mercure $mercure;
  109.     }
  110.     /**
  111.      * @Route("/rdv/{id}", name="deleteRdvByID", methods={"DELETE"})
  112.      */
  113.     public function deleteRdvByID(Request $requestRdv $rdvGoogleCalendarService $googleCalendar)
  114.     {
  115.         if (!$request->query->get('token')) {
  116.             return new Response(json_encode([
  117.                 "message" => "Pas de token n'a été spécifié",
  118.                 "status" => 401,
  119.             ]), 401);
  120.         }
  121.         $entityManager $this->getDoctrine()->getManager();
  122.         /** @var Token */
  123.         $token $this->getDoctrine()
  124.             ->getRepository(Token::class)
  125.             ->findOneBy(['token' => $request->query->get('token')]);
  126.         if (!$token) {
  127.             return new Response(json_encode([
  128.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  129.                 "status" => 404,
  130.             ]), 404);
  131.         }
  132.         // get token age
  133.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  134.         // if the token if older than 7 days
  135.         if ($dateDiff->7) {
  136.             $entityManager->remove($token);
  137.             $entityManager->flush();
  138.             return $this->json([
  139.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  140.                 'path' => 'src/Controller/ClientController.php',
  141.                 "status" => 401,
  142.             ], 401);
  143.         }
  144.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  145.             return new Response(json_encode([
  146.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  147.                 "status" => 404,
  148.             ]), 404);
  149.         }
  150.         $entityManager->remove($rdv);
  151.         $entityManager->flush();
  152.         return new Response(json_encode(([
  153.             'message' => "Rdv has been successfully deleted",
  154.             "status" => 200,
  155.         ])));
  156.     }
  157.     /**
  158.      * @Route("/rdv/{id}", name="getRdvByID", methods={"GET","HEAD"})
  159.      */
  160.     public function getRdvByID(Request $requestRdv $rdvPublicFunction $publicFunction)
  161.     {
  162.         if (!$request->query->get('token')) {
  163.             return new Response(json_encode([
  164.                 "message" => "Pas de token n'a été spécifié",
  165.                 "status" => 401,
  166.             ]), 401);
  167.         }
  168.         $entityManager $this->getDoctrine()->getManager();
  169.         /** @var Token */
  170.         $token $this->getDoctrine()
  171.             ->getRepository(Token::class)
  172.             ->findOneBy(['token' => $request->query->get('token')]);
  173.         if (!$token) {
  174.             return new Response(json_encode([
  175.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  176.                 "status" => 404,
  177.             ]), 404);
  178.         }
  179.         // get token age
  180.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  181.         // if the token if older than 7 days
  182.         if ($dateDiff->7) {
  183.             $entityManager->remove($token);
  184.             $entityManager->flush();
  185.             return $this->json([
  186.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  187.                 'path' => 'src/Controller/ClientController.php',
  188.                 "status" => 401,
  189.             ], 401);
  190.         }
  191.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  192.             return new Response(json_encode([
  193.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  194.                 "status" => 404,
  195.             ]), 404);
  196.         }
  197.         /** @var AudioCentre */
  198.         $liaison $this->getDoctrine()->getRepository(AudioCentre::class)
  199.             ->findOneBy(array('id_audio' => $rdv->getIdAudio(), 'id_centre' => $rdv->getIdCentre(), 'isConfirmed' => true));
  200.         // Motif filter
  201.         /** @var AudioMotif[] */
  202.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  203.             ->findBy(array('id_audio' => $rdv->getIdAudio(), 'id_motif' => $rdv->getIdMotif()));
  204.         $resultMotif = new ArrayCollection();
  205.         foreach ($motifs as $motif) {
  206.             $resultMotif->add([
  207.                 "id" => $motif->getIdMotif()->getId(),
  208.                 "titre" => $motif->getIdMotif()->getTitre(),
  209.                 "consigne" => $motif->getConsigne(),
  210.                 "duration" => $motif->getDuration(),
  211.             ]);
  212.         }
  213.         // Specialities
  214.         /** @var AudioSpecialite[] */
  215.         $specialities $this->getDoctrine()->getRepository(AudioSpecialite::class)
  216.             ->findBy(array('id_audio' => $rdv->getIdAudio()));
  217.         $resultSpeciality = new ArrayCollection();
  218.         foreach ($specialities as $speciality) {
  219.             $resultSpeciality->add([
  220.                 "id" => $speciality->getIdSpecialite()->getId(),
  221.                 "titre" => $speciality->getIdSpecialite()->getLibelle(),
  222.             ]);
  223.         }
  224.         if ($rdv->getIdCentre())
  225.         /** @var AccessCentre*/
  226.         {
  227.             $accessCentre $this->getDoctrine()->getRepository(AccessCentre::class)
  228.                 ->findOneBy(array('id_centre' => $rdv->getIdCentre()));
  229.         } else
  230.         /** @var AccessCentre*/
  231.         {
  232.             $accessCentre $this->getDoctrine()->getRepository(AccessCentre::class)
  233.                 ->findOneBy(array('id_lieu' => $rdv->getIdLieu()));
  234.         }
  235.         if ($rdv->getIdCentre())
  236.         /** @var CentrePrestation[]*/
  237.         {
  238.             $prestations $this->getDoctrine()->getRepository(CentrePrestation::class)
  239.                 ->findBy(array('id_centre' => $liaison->getIdCentre()->getId()));
  240.         } else
  241.         /** @var LieuPrestation[]*/
  242.         {
  243.             $prestations $this->getDoctrine()->getRepository(LieuPrestation::class)
  244.                 ->findBy(array('id_lieu' => $rdv->getIdLieu()));
  245.         }
  246.         $resultPrestation = new ArrayCollection();
  247.         foreach ($prestations as $prestation) {
  248.             $resultPrestation->add([
  249.                 "id" => $prestation->getIdPrestation()->getId(),
  250.                 "titre" => $prestation->getIdPrestation()->getLibelle(),
  251.             ]);
  252.         }
  253.         $mutuelles $this->getDoctrine()->getRepository(CentreMutuelle::class)
  254.             ->findBy(array('id_centre' => $rdv->getIdCentre()));
  255.         $resultMutuelle = new ArrayCollection();
  256.         foreach ($mutuelles as $mutuelle) {
  257.             $resultMutuelle->add([
  258.                 "id" => $mutuelle->getIdMutuelle()->getId(),
  259.                 "titre" => $mutuelle->getIdMutuelle()->getLibelle(),
  260.             ]);
  261.         }
  262.         if ($rdv->getIdCentre())
  263.         /** @var CentreTier[]*/
  264.         {
  265.             $tiers $this->getDoctrine()->getRepository(CentreTier::class)
  266.                 ->findBy(array('id_centre' => $liaison->getIdCentre()->getId()));
  267.         } else
  268.         /** @var LieuTier[]*/
  269.         {
  270.             $tiers $this->getDoctrine()->getRepository(LieuTier::class)
  271.                 ->findBy(array('id_lieu' => $rdv->getIdLieu()));
  272.         }
  273.         $resultTier = new ArrayCollection();
  274.         foreach ($tiers as $tier) {
  275.             $resultTier->add([
  276.                 "id" => $tier->getIdTier()->getId(),
  277.                 "titre" => $tier->getIdTier()->getLibelle(),
  278.             ]);
  279.         }
  280.         $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  281.         /** @var Rdv[] */
  282.         $audioRdvs $this->getDoctrine()->getRepository(Rdv::class)
  283.             ->findAllReviewsAudio($rdv->getIdAudio()->getId());
  284.         /** @var Rdv[] */
  285.         $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  286.             ->findAllReviewsCentre($rdvCentre->getId());
  287.         // Comment
  288.         /** @var Rdv[] */
  289.         $rdvs $this->getDoctrine()->getRepository(Rdv::class)
  290.             ->findBy(array('id_audio' => $rdv->getIdAudio()));
  291.         $comments = [];
  292.         foreach ($rdvs as $rdv)
  293.             if ($rdv->getComment() && $rdv->getReview() && $rdv->getIdClient())
  294.                 array_push($comments, [
  295.                     "id" => $rdv->getIdClient()->getId(),
  296.                     "name" => $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname()[0] . ".",
  297.                     "comment" => $rdv->getComment(),
  298.                     "isMale" => $rdv->getIdClient()->getCivilite() == "Monsieur",
  299.                     "review" => $rdv->getReview(),
  300.                 ]);
  301.         return new Response(json_encode(([
  302.             "id" => $rdv->getId(),
  303.             "motif_id" => $rdv->getIdMotif()->getId(),
  304.             "motif_titre" => $rdv->getIdMotif()->getTitre(),
  305.             "audio_id" => $rdv->getIdAudio()->getId(),
  306.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  307.             "client_id" => $rdv->getIdClient()->getId(),
  308.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  309.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  310.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  311.             "etat_id" => $rdv->getIdEtat()->getId(),
  312.             "date" => $rdv->getDate(),
  313.             "comment" => $rdv->getComment(),
  314.             "review" => $rdv->getReview(),
  315.             "note" => $rdv->getNote(),
  316.             "testclient" => $rdv->getTestClient() ? [
  317.                 "result" => $rdv->getTestClient()->getResultTonal(),
  318.                 "date" => $rdv->getTestClient()->getDate(),
  319.                 "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  320.             ] : null,
  321.             "comments" => $comments,
  322.             "audio" => [
  323.                 "id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : $rdv->getIdAudio()->getId(),
  324.                 "civilite" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getCivilite() : $rdv->getIdAudio()->getCivilite(),
  325.                 "name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() : $rdv->getIdAudio()->getName(),
  326.                 "lastname" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getLastname(),
  327.                 "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  328.                 "mail" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getMail() : $rdv->getIdAudio()->getMail(),
  329.                 "phone" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getPhone() : $rdv->getIdAudio()->getPhone(),
  330.                 "adeli" => $rdv->getIdAudio()->getAdeli(),
  331.                 "pin" => $rdv->getIdAudio()->getPin(),
  332.                 "description" => $rdv->getIdAudio()->getDescription(),
  333.                 "averageRating" => $publicFunction->calculateRating($audioRdvs),
  334.                 "nbrReview" => count($audioRdvs),
  335.                 "motifs" => $resultMotif->toArray(),
  336.                 "specialities" => $resultSpeciality->toArray(),
  337.             ],
  338.             "centre" => [
  339.                 "id" => $rdvCentre->getId(),
  340.                 "audio_id" => $rdvCentre->getIdGerant()->getId(),
  341.                 "name" => $rdvCentre->getName(),
  342.                 "imgUrl" => $rdvCentre->getImgUrl(),
  343.                 "isRdvDomicile" => $rdv->getIdCentre() ? $rdvCentre->getIsRdvDomicile() : $rdv->getIdAudio()->getIsRdvDomicileIndie(),
  344.                 "address" => $rdvCentre->getAddress(),
  345.                 "postale" => $rdvCentre->getPostale(),
  346.                 "city" => $rdvCentre->getCity(),
  347.                 "finess" => $rdvCentre->getFiness(),
  348.                 "siret" => $rdvCentre->getSiret(),
  349.                 "website" => $rdvCentre->getWebsite(),
  350.                 "phone" => $rdvCentre->getPhone(),
  351.                 "isHandicap" => $rdvCentre->getIsHandicap(),
  352.                 "longitude" => $rdvCentre->getLongitude(),
  353.                 "latitude" => $rdvCentre->getLatitude(),
  354.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  355.                 "nbrReview" => count($centreRdvs),
  356.                 "tram" => $accessCentre->getTram(),
  357.                 "rer" => $accessCentre->getRer(),
  358.                 "metro" => $accessCentre->getMetro(),
  359.                 "bus" => $accessCentre->getBus(),
  360.                 "parking" => $accessCentre->getParkingPublic(),
  361.                 "description" => $rdv->getIdCentre()->getDescription(),
  362.                 "parkingPrivate" => $accessCentre->getParkingPrivate(),
  363.                 "other" => $accessCentre->getOther(),
  364.                 "prestations" => $resultPrestation->toArray(),
  365.                 "mutuelles" => $resultMutuelle->toArray(),
  366.                 "tiers" => $resultTier->toArray(),
  367.                 "isLieu" => false,
  368.                 "schedule" => $rdv->getIdAudio()->getIsIndie() == false $rdv->getIdCentre()->getHoraire() : ($rdv->getIdLieu() ? $rdv->getIdLieu()->getHoraire() : $liaison->getHoraire()),
  369.             ],
  370.             "status" => 200,
  371.         ])));
  372.     }
  373.     /**
  374.      * @Route("/rdvs/client/{id}", name="getRdvsByClientID", methods={"GET","HEAD"})
  375.      */
  376.     public function getRdvsByClientID(Request $requestClient $clientPublicFunction $publicFunction)
  377.     {
  378.         if (!$request->query->get('token')) {
  379.             return new Response(json_encode([
  380.                 "message" => "Pas de token n'a été spécifié",
  381.                 "status" => 401,
  382.             ]), 401);
  383.         }
  384.         $entityManager $this->getDoctrine()->getManager();
  385.         /** @var Token */
  386.         $token $this->getDoctrine()
  387.             ->getRepository(Token::class)
  388.             ->findOneBy(['token' => $request->query->get('token')]);
  389.         if (!$token) {
  390.             return new Response(json_encode([
  391.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  392.                 "status" => 404,
  393.             ]), 404);
  394.         }
  395.         // get token age
  396.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  397.         // if the token if older than 7 days
  398.         if ($dateDiff->7) {
  399.             $entityManager->remove($token);
  400.             $entityManager->flush();
  401.             return $this->json([
  402.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  403.                 'path' => 'src/Controller/ClientController.php',
  404.                 "status" => 401,
  405.             ], 401);
  406.         }
  407.         if ($token->getIdClient()) {
  408.             if ($client != $token->getIdClient()) {
  409.                 return new Response(json_encode([
  410.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  411.                     "status" => 404,
  412.                 ]), 404);
  413.             }
  414.         } else if ($token->getIdAudio()) {
  415.             /** @var Token */
  416.             $token $this->getDoctrine()
  417.                 ->getRepository(Rdv::class)
  418.                 ->findOneBy(['id_client' => $client'id_audio' => $token->getIdAudio()]);
  419.             if ($client != $token->getIdClient()) {
  420.                 return new Response(json_encode([
  421.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  422.                     "status" => 404,
  423.                 ]), 404);
  424.             }
  425.         } else {
  426.             return new Response(json_encode([
  427.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  428.                 "status" => 404,
  429.             ]), 404);
  430.         }
  431.         if ($request->query->get('audio')) {
  432.             /** @var Rdv[] */
  433.             $rdvs $this->getDoctrine()
  434.                 ->getRepository(Rdv::class)
  435.                 ->findBy(['id_client' => $client->getId(), 'id_audio' => $token->getIdAudio()]);
  436.             $rdvResult = new ArrayCollection();
  437.         } else {
  438.             /** @var Rdv[] */
  439.             $rdvs $this->getDoctrine()
  440.                 ->getRepository(Rdv::class)
  441.                 ->findBy(['id_client' => $client->getId()]);
  442.             $rdvResult = new ArrayCollection();
  443.         }
  444.         if ($request->query->get('old')) {
  445.             $oldRdvResult = new ArrayCollection();
  446.         }
  447.         foreach ($rdvs as $rdv) {
  448.             if ($rdv->getIdEtat()->getId() != 1) {
  449.                 continue;
  450.             }
  451.             /** @var AudioMotif */
  452.             $audioMotif $this->getDoctrine()
  453.                 ->getRepository(AudioMotif::class)
  454.                 ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  455.             if (!$audioMotif) {
  456.                 continue;
  457.             }
  458.             $duration '';
  459.             if (is_null($rdv->getDuration())) {
  460.                 $duration $audioMotif->getDuration();
  461.             } else {
  462.                 $duration $rdv->getDuration();
  463.             }
  464.             $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  465.             /** @var Rdv[] */
  466.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  467.                 ->findAllReviewsCentre($rdvCentre->getId());
  468.             $rdvItem = [
  469.                 "id" => $rdv->getId(),
  470.                 "motif_id" => $rdv->getIdMotif()->getId(),
  471.                 "duration" => $duration,
  472.                 "color" => $audioMotif->getColor(),
  473.                 "audio_id" => $rdv->getIdAudio()->getId(),
  474.                 "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  475.                 "audio_name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() . " " $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  476.                 "client_id" => $rdv->getIdClient()->getId(),
  477.                 "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  478.                 "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  479.                 "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  480.                 "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  481.                 "testclient" => $rdv->getTestClient() ? [
  482.                     "result" => $rdv->getTestClient()->getResultTonal(),
  483.                     "date" => $rdv->getTestClient()->getDate(),
  484.                     "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  485.                 ] : null,
  486.                 "name" => $rdvCentre->getName(),
  487.                 "phone" => $rdvCentre->getPhone(),
  488.                 "imgUrl" => $rdvCentre->getImgUrl(),
  489.                 "address" => $rdvCentre->getAddress(),
  490.                 "postale" => $rdvCentre->getPostale(),
  491.                 "city" => $rdvCentre->getCity(),
  492.                 "etat_id" => $rdvCentre->getId(),
  493.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  494.                 "nbrReview" => count($centreRdvs),
  495.                 "acceptedCurrency" => "CB Chèque",
  496.                 "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  497.                 "note" => $rdv->getNote(),
  498.                 "comment" => $rdv->getComment(),
  499.                 "review" => $rdv->getReview(),
  500.             ];
  501.             if ($rdv->getDate() >= new DateTime()) {
  502.                 $rdvResult->add($rdvItem);
  503.             } else if ($request->query->get('old')) {
  504.                 $oldRdvResult->add($rdvItem);
  505.             }
  506.         }
  507.         if ($request->query->get('old')) {
  508.             if ($request->query->get('onlyOld')) {
  509.                 if (count($rdvResult) > || count($oldRdvResult) > 0) {
  510.                     return new Response(json_encode(([
  511.                         "oldRdv" => $oldRdvResult->toArray(),
  512.                         "status" => 200,
  513.                     ])));
  514.                 } else {
  515.                     return new Response(json_encode(([
  516.                         "message" => "Aucun rendez-vous n'a été trouvé!",
  517.                         "test" => "count:" count($rdvs),
  518.                         'path' => 'src/Controller/RdvController.php',
  519.                         "rdv" => array(),
  520.                         "oldRdv" => array(),
  521.                         "status" => 404,
  522.                     ])));
  523.                 }
  524.             } else {
  525.                 if (count($rdvResult) > || count($oldRdvResult) > 0) {
  526.                     return new Response(json_encode(([
  527.                         "rdv" => $rdvResult->toArray(),
  528.                         "oldRdv" => $oldRdvResult->toArray(),
  529.                         "status" => 200,
  530.                     ])));
  531.                 } else {
  532.                     return new Response(json_encode(([
  533.                         "message" => "Aucun rendez-vous n'a été trouvé!",
  534.                         "test" => "count:" count($rdvs),
  535.                         'path' => 'src/Controller/RdvController.php',
  536.                         "rdv" => array(),
  537.                         "oldRdv" => array(),
  538.                         "status" => 404,
  539.                     ])));
  540.                 }
  541.             }
  542.         } else {
  543.             if (count($rdvResult) > 0) {
  544.                 return new Response(json_encode(([
  545.                     "content" => $rdvResult->toArray(),
  546.                     "status" => 200,
  547.                 ])));
  548.             } else {
  549.                 return new Response(json_encode(([
  550.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  551.                     "test" => "count2:" count($rdvs),
  552.                     'path' => 'src/Controller/RdvController.php',
  553.                     "status" => 404,
  554.                 ])));
  555.             }
  556.         }
  557.     }
  558.     /**
  559.      * @Route("/rdvs/client/{id}/centre", name="getRdvsByClientIDForCentre", methods={"GET","HEAD"})
  560.      */
  561.     public function getRdvsByClientIDForCentre(Request $requestClient $clientPublicFunction $publicFunction)
  562.     {
  563.         if (!$request->query->get('token')) {
  564.             return new Response(json_encode([
  565.                 "message" => "Pas de token n'a été spécifié",
  566.                 "status" => 401,
  567.             ]), 401);
  568.         }
  569.         $entityManager $this->getDoctrine()->getManager();
  570.         /** @var Token */
  571.         $token $this->getDoctrine()
  572.             ->getRepository(Token::class)
  573.             ->findOneBy(['token' => $request->query->get('token')]);
  574.         if (!$token) {
  575.             return new Response(json_encode([
  576.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  577.                 "status" => 404,
  578.             ]), 404);
  579.         }
  580.         $audio $this->getDoctrine()
  581.             ->getRepository(Audio::class)
  582.             ->findOneBy(['id' => $request->query->get('audio')]);
  583.         $audioCentre $this->getDoctrine()
  584.             ->getRepository(AudioCentre::class)
  585.             ->findOneBy(['id_audio' => $audio]);
  586.         // get token age
  587.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  588.         // if the token if older than 7 days
  589.         if ($dateDiff->7) {
  590.             $entityManager->remove($token);
  591.             $entityManager->flush();
  592.             return $this->json([
  593.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  594.                 'path' => 'src/Controller/ClientController.php',
  595.                 "status" => 401,
  596.             ], 401);
  597.         }
  598.         if ($token->getIdClient()) {
  599.             if ($client != $token->getIdClient()) {
  600.                 return new Response(json_encode([
  601.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  602.                     "status" => 404,
  603.                 ]), 404);
  604.             }
  605.         } else if ($token->getIdAudio()) {
  606.             /** @var Token */
  607.             if ($token->getIdAudio() != $audio) {
  608.                 return new Response(json_encode([
  609.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  610.                     "status" => 404,
  611.                 ]), 404);
  612.             }
  613.         } else {
  614.             return new Response(json_encode([
  615.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  616.                 "status" => 404,
  617.             ]), 404);
  618.         }
  619.         if ($request->query->get('centre')) {
  620.             /** @var Rdv[] */
  621.             $rdvs $this->getDoctrine()
  622.                 ->getRepository(Rdv::class)
  623.                 ->findBy(['id_client' => $client->getId(), 'id_centre' => $audioCentre->getIdCentre()]);
  624.             $rdvResult = new ArrayCollection();
  625.         } else {
  626.             /** @var Rdv[] */
  627.             $rdvs $this->getDoctrine()
  628.                 ->getRepository(Rdv::class)
  629.                 ->findBy(['id_client' => $client->getId()]);
  630.             $rdvResult = new ArrayCollection();
  631.         }
  632.         if ($request->query->get('old')) {
  633.             $oldRdvResult = new ArrayCollection();
  634.         }
  635.         foreach ($rdvs as $rdv) {
  636.             /*if ($rdv->getIdEtat()->getId() != 1) {
  637.                 continue;
  638.             }*/
  639.             /** @var AudioMotif */
  640.             $audioMotif $this->getDoctrine()
  641.                 ->getRepository(AudioMotif::class)
  642.                 ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  643.             if (!$audioMotif) {
  644.                 continue;
  645.             }
  646.             $duration '';
  647.             if (is_null($rdv->getDuration())) {
  648.                 $duration $audioMotif->getDuration();
  649.             } else {
  650.                 $duration $rdv->getDuration();
  651.             }
  652.             $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  653.             /** @var Rdv[] */
  654.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  655.                 ->findAllReviewsCentre($rdvCentre->getId());
  656.             $rdvItem = [
  657.                 "id" => $rdv->getId(),
  658.                 "motif_id" => $rdv->getIdMotif()->getId(),
  659.                 "duration" => $duration,
  660.                 "color" => $audioMotif->getColor(),
  661.                 "audio_id" => $rdv->getIdAudio()->getId(),
  662.                 "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  663.                 "audio_name" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getName() . " " $rdv->getRemplacant()->getLastname() : $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  664.                 "client_id" => $rdv->getIdClient()->getId(),
  665.                 "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  666.                 "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  667.                 "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  668.                 "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  669.                 "testclient" => $rdv->getTestClient() ? [
  670.                     "result" => $rdv->getTestClient()->getResultTonal(),
  671.                     "date" => $rdv->getTestClient()->getDate(),
  672.                     "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  673.                 ] : null,
  674.                 "name" => $rdvCentre->getName(),
  675.                 "phone" => $rdvCentre->getPhone(),
  676.                 "imgUrl" => $rdvCentre->getImgUrl(),
  677.                 "address" => $rdvCentre->getAddress(),
  678.                 "postale" => $rdvCentre->getPostale(),
  679.                 "city" => $rdvCentre->getCity(),
  680.                 "etat_id" => $rdvCentre->getId(),
  681.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  682.                 "nbrReview" => count($centreRdvs),
  683.                 "acceptedCurrency" => "CB Chèque",
  684.                 "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  685.                 "note" => $rdv->getNote(),
  686.                 "comment" => $rdv->getComment(),
  687.                 "review" => $rdv->getReview(),
  688.                 "status" => $rdv->getIdEtat()->getLibelle()
  689.             ];
  690.             // dd(new DateTime());
  691.             if ($rdv->getDate() >= new DateTime()) {
  692.                 $rdvResult->add($rdvItem);
  693.             } else if ($request->query->get('old')) {
  694.                 $oldRdvResult->add($rdvItem);
  695.             }
  696.         }
  697.         if ($request->query->get('old')) {
  698.             if (count($rdvResult) > || count($oldRdvResult) > 0) {
  699.                 return new Response(json_encode(([
  700.                     "rdv" => $rdvResult->toArray(),
  701.                     "oldRdv" => $oldRdvResult->toArray(),
  702.                     "status" => 200,
  703.                 ])));
  704.             } else {
  705.                 return new Response(json_encode(([
  706.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  707.                     "test" => "count:" count($rdvs),
  708.                     'path' => 'src/Controller/RdvController.php',
  709.                     "status" => 404,
  710.                 ])), 404);
  711.             }
  712.         } else {
  713.             if (count($rdvResult) > 0) {
  714.                 return new Response(json_encode(([
  715.                     "content" => $rdvResult->toArray(),
  716.                     "status" => 200,
  717.                 ])));
  718.             } else {
  719.                 return new Response(json_encode(([
  720.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  721.                     "test" => "count2:" count($rdvs),
  722.                     'path' => 'src/Controller/RdvController.php',
  723.                     "status" => 404,
  724.                 ])));
  725.             }
  726.         }
  727.     }
  728.     /////// CRON
  729.     /**
  730.      * @Route("/confirmRdvSms", name="confirmRdvSms", methods={"GET","HEAD"})
  731.      */
  732.     public function confirmRdvSms(PublicFunction $publicFunction): Response
  733.     {
  734.         $date = new DateTime();
  735.         $minutes_to_add 30;
  736.         $date->add(new DateInterval('PT' $minutes_to_add 'M'));
  737.         $date->setTimezone(new DateTimeZone('Europe/Paris'));
  738.         $currentDate $date->format('Y-m-d H:i:00');
  739.         $toSend $this->getDoctrine()->getRepository(Rdv::class)
  740.             ->findRdvsIn10Mins($currentDate);
  741.         $entityManager $this->getDoctrine()->getManager();
  742.         $rdvResult = new ArrayCollection();
  743.         foreach ($toSend as $rdv) {
  744.             $date $rdv->getDate();
  745.             // $smsDate = $date->format('d-m-Y H:i');
  746.             //$client = $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  747.             //$sms = "Vous avez votre RDV du " . substr($smsDate, 0, 10) . " à " . substr($smsDate, 11, 15) . ", taper 1 si vous confirmer votre arrivé au centre auditif ou 2 si vous avez un empêchement.";
  748.             // // $publicFunction->sendEmail("MyAudio <noreply@myaudio.fr>", $client->getMail(), "My Audio: Testing CRON", "<p>Testing Cron.</p>");
  749.             //$response = $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone(), 4);
  750.             //$another_response = explode(" | ", $response);
  751.             // $idSms = trim($another_response[2]);
  752.             // $rdv->setIdSms($idSms);
  753.             //$entityManager->persist($rdv);
  754.             // $entityManager->flush();
  755.         }
  756.         return new Response(json_encode([
  757.             // "test" => $idSms,
  758.             "currentDate" => $currentDate
  759.         ]));
  760.     }
  761.     /////// CRON 
  762.     /**
  763.      * @Route("/validateRdvSms", name="validateRdvSms", methods={"GET","HEAD"})
  764.      */
  765.     public function validateRdvSms(Request $requestPublicFunction $publicFunction): Response
  766.     {
  767.         $entityManager $this->getDoctrine()->getManager();
  768.         $smsId $_GET['smsID'];
  769.         $message $_GET['message'];
  770.         $callLog $this->getDoctrine()
  771.             ->getRepository(CallLog::class)
  772.             ->findOneBy(['smsId' => $smsId]);
  773.         if ($callLog) {
  774.             $callLog->setAnsweredAt(new \DateTimeImmutable());
  775.             $interaction = new CallInteraction;
  776.             $interaction->setCallLog($callLog);
  777.             try {
  778.                 if ($message == "1") {
  779.                     $interaction->setStep('equipment_status');
  780.                     $interaction->setResponse('réponse_reçue');
  781.                     $interaction->setTimestamp(new \DateTimeImmutable());
  782.                     $interaction->setAdditionalData(['digit' => '1''status' => 'en_essai']);
  783.                     $entityManager->persist($interaction);
  784.                     $sms "Merci pour votre réponse. Nous notons que vous êtes actuellement en période d'essai. Merci et bonne journée avec MyAudio";
  785.                     $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  786.                 } else if ($message == "2") {
  787.                     $interaction->setStep('equipment_status');
  788.                     $interaction->setResponse('réponse_reçue');
  789.                     $interaction->setTimestamp(new \DateTimeImmutable());
  790.                     $interaction->setAdditionalData(['digit' => '2''status' => 'finalise']);
  791.                     $entityManager->persist($interaction);
  792.                     $sms "Félicitations pour votre appareillage ! Nous sommes ravis que vous ayez finalisé cet achat important. Bonne journée avec My Audio.";
  793.                     $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  794.                 } else if ($message == "3") {
  795.                     $interaction->setStep('equipment_status');
  796.                     $interaction->setResponse('réponse_reçue');
  797.                     $interaction->setTimestamp(new \DateTimeImmutable());
  798.                     $interaction->setAdditionalData(['digit' => '3''status' => 'abandonne']);
  799.                     $entityManager->persist($interaction);
  800.                     $sms "Nous avons bien noté que vous avez rendu les appareils sans finaliser l'achat. Bonne journée avec My Audio.";
  801.                     $result $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  802.                     error_log("Résultat envoi SMSSSSSSSSSSSSSSSSSSSSSSSSS: " json_encode($result));
  803.                 } else if ($message == "4") {
  804.                     $interaction->setStep('equipment_status');
  805.                     $interaction->setResponse('réponse_reçue');
  806.                     $interaction->setTimestamp(new \DateTimeImmutable());
  807.                     $interaction->setAdditionalData(['digit' => '4''status' => 'attente_rdv_orl']);
  808.                     $entityManager->persist($interaction);
  809.                     $sms "Nous avons bien noté que vous etes en attente d'un rendez-vous avec un ORL. Bonne journée avec My Audio.";
  810.                     $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  811.                 } else if ($message == "5") {
  812.                     $interaction->setStep('equipment_status');
  813.                     $interaction->setResponse('réponse_reçue');
  814.                     $interaction->setTimestamp(new \DateTimeImmutable());
  815.                     $interaction->setAdditionalData(['digit' => '5''status' => 'autre']);
  816.                     $entityManager->persist($interaction);
  817.                     $sms "Merci pour votre réponse. Un conseiller My Audio vous contactera dans les prochains jours. Bonne journée.";
  818.                     $publicFunction->sendSmsWithResponse("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$callLog->getPhoneNumber(), 4);
  819.                 } else {
  820.                     error_log("Message non reconnu: " $message);
  821.                     return new Response(json_encode([
  822.                         "message" => "La réponse spécifiée est incorrecte",
  823.                         "status" => 401,
  824.                         "réponse" => $message,
  825.                     ]), 401);
  826.                 }
  827.                 $entityManager->flush();
  828.                 return new Response(json_encode([
  829.                     "message" => "Réponse traitée avec succès",
  830.                     "status" => 200,
  831.                 ]));
  832.             } catch (\Exception $e) {
  833.                 return new Response(json_encode([
  834.                     "message" => "Erreur lors du traitement de la réponse: " $e->getMessage(),
  835.                     "status" => 500,
  836.                 ]), 500);
  837.             }
  838.         }
  839.         return new Response(json_encode([
  840.             "smsId" => $smsId,
  841.             "message" => $currentDate
  842.         ]));
  843.     }
  844.     /**
  845.      * @Route("/rdvs/old/client/{id}", name="getOldRdvsByClientId", methods={"GET","HEAD"})
  846.      */
  847.     public function getOldRdvsByClientId(Request $requestClient $clientPublicFunction $publicFunction)
  848.     {
  849.         if (!$request->query->get('token')) {
  850.             return new Response(json_encode([
  851.                 "message" => "Pas de token n'a été spécifié",
  852.                 "status" => 401,
  853.             ]), 401);
  854.         }
  855.         $entityManager $this->getDoctrine()->getManager();
  856.         /** @var Token */
  857.         $token $this->getDoctrine()
  858.             ->getRepository(Token::class)
  859.             ->findOneBy(['token' => $request->query->get('token')]);
  860.         if (!$token) {
  861.             return new Response(json_encode([
  862.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  863.                 "status" => 404,
  864.             ]), 404);
  865.         }
  866.         // get token age
  867.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  868.         // if the token if older than 7 days
  869.         if ($dateDiff->7) {
  870.             $entityManager->remove($token);
  871.             $entityManager->flush();
  872.             return $this->json([
  873.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  874.                 'path' => 'src/Controller/ClientController.php',
  875.                 "status" => 401,
  876.             ], 401);
  877.         }
  878.         if ($token->getIdClient()) {
  879.             if ($client != $token->getIdClient()) {
  880.                 return new Response(json_encode([
  881.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  882.                     "status" => 404,
  883.                 ]), 404);
  884.             }
  885.         } else if ($token->getIdAudio()) {
  886.             /** @var Token */
  887.             $token $this->getDoctrine()
  888.                 ->getRepository(Rdv::class)
  889.                 ->findOneBy(['id_client' => $client'id_audio' => $token->getIdAudio()]);
  890.             if ($client != $token->getIdClient()) {
  891.                 return new Response(json_encode([
  892.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  893.                     "status" => 404,
  894.                 ]), 404);
  895.             }
  896.         } else {
  897.             return new Response(json_encode([
  898.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  899.                 "status" => 404,
  900.             ]), 404);
  901.         }
  902.         if ($request->query->get('audio')) {
  903.             /** @var ActivityRepository */
  904.             $activityRepo $this->getDoctrine();
  905.             if ($request->query->get('limit')) {
  906.                 /** @var Rdv[] */
  907.                 $rdvs $activityRepo
  908.                     ->getRepository(Rdv::class)
  909.                     ->findLastsOldRdvsWithLimit($request->query->get('limit'), $client->getId(), $request->query->get('audio'), new DateTime());
  910.                 $rdvResult = new ArrayCollection();
  911.             } else {
  912.                 /** @var Rdv[] */
  913.                 $rdvs $activityRepo
  914.                     ->getRepository(Rdv::class)
  915.                     ->findOldRdvs($client->getId(), $request->query->get('audio'), new DateTime());
  916.                 $rdvResult = new ArrayCollection();
  917.             }
  918.             foreach ($rdvs as $rdv) {
  919.                 /*if ($rdv->getIdEtat()->getId() != 1) {
  920.                     continue;
  921.                 }*/
  922.                 /** @var AudioMotif */
  923.                 $audioMotif $this->getDoctrine()
  924.                     ->getRepository(AudioMotif::class)
  925.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  926.                 if (!$audioMotif) {
  927.                     continue;
  928.                 }
  929.                 $duration '';
  930.                 if (is_null($rdv->getDuration())) {
  931.                     $duration $audioMotif->getDuration();
  932.                 } else {
  933.                     $duration $rdv->getDuration();
  934.                 }
  935.                 $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  936.                 /** @var Rdv[] */
  937.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  938.                     ->findAllReviewsCentre($rdvCentre->getId());
  939.                 $rdvItem = [
  940.                     "id" => $rdv->getId(),
  941.                     "motif_id" => $rdv->getIdMotif()->getId(),
  942.                     "duration" => $duration,
  943.                     "color" => $audioMotif->getColor(),
  944.                     "audio_id" => $rdv->getIdAudio()->getId(),
  945.                     "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  946.                     "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  947.                     "client_id" => $rdv->getIdClient()->getId(),
  948.                     "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  949.                     "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  950.                     "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  951.                     "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  952.                     "testclient" => $rdv->getTestClient() ? [
  953.                         "result" => $rdv->getTestClient()->getResultTonal(),
  954.                         "date" => $rdv->getTestClient()->getDate(),
  955.                         "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  956.                     ] : null,
  957.                     "name" => $rdvCentre->getName(),
  958.                     "phone" => $rdvCentre->getPhone(),
  959.                     "imgUrl" => $rdvCentre->getImgUrl(),
  960.                     "address" => $rdvCentre->getAddress(),
  961.                     "postale" => $rdvCentre->getPostale(),
  962.                     "city" => $rdvCentre->getCity(),
  963.                     "etat_id" => $rdvCentre->getId(),
  964.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  965.                     "nbrReview" => count($centreRdvs),
  966.                     "acceptedCurrency" => "CB Chèque",
  967.                     "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  968.                     "note" => $rdv->getNote(),
  969.                     "comment" => $rdv->getComment(),
  970.                     "review" => $rdv->getReview(),
  971.                 ];
  972.                 $rdvResult->add($rdvItem);
  973.             }
  974.         }
  975.         if (count($rdvResult) > 0) {
  976.             return new Response(json_encode(([
  977.                 "rdv" => $rdvResult->toArray(),
  978.                 "status" => 200,
  979.             ])));
  980.         } else {
  981.             return new Response(json_encode(([
  982.                 "message" => "Aucun rendez-vous a venir!",
  983.                 'path' => 'src/Controller/RdvController.php',
  984.                 "status" => 404,
  985.             ])));
  986.         }
  987.     }
  988.     /**
  989.      * @Route("/rdvs/old/client/{id}/centre", name="getOldRdvsByClientIdForCentre", methods={"GET","HEAD"})
  990.      */
  991.     public function getOldRdvsByClientIdForCentre(Request $requestClient $clientPublicFunction $publicFunction)
  992.     {
  993.         if (!$request->query->get('token')) {
  994.             return new Response(json_encode([
  995.                 "message" => "Pas de token n'a été spécifié",
  996.                 "status" => 401,
  997.             ]), 401);
  998.         }
  999.         $entityManager $this->getDoctrine()->getManager();
  1000.         /** @var Token */
  1001.         $token $this->getDoctrine()
  1002.             ->getRepository(Token::class)
  1003.             ->findOneBy(['token' => $request->query->get('token')]);
  1004.         if (!$token) {
  1005.             return new Response(json_encode([
  1006.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1007.                 "status" => 404,
  1008.             ]), 404);
  1009.         }
  1010.         $audio $this->getDoctrine()
  1011.             ->getRepository(Audio::class)
  1012.             ->findOneBy(['id' => $request->query->get('audio')]);
  1013.         $audioCentre $this->getDoctrine()
  1014.             ->getRepository(AudioCentre::class)
  1015.             ->findOneBy(['id_audio' => $audio]);
  1016.         // get token age
  1017.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1018.         // if the token if older than 7 days
  1019.         if ($dateDiff->7) {
  1020.             $entityManager->remove($token);
  1021.             $entityManager->flush();
  1022.             return $this->json([
  1023.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1024.                 'path' => 'src/Controller/ClientController.php',
  1025.                 "status" => 401,
  1026.             ], 401);
  1027.         }
  1028.         if ($token->getIdClient()) {
  1029.             if ($client != $token->getIdClient()) {
  1030.                 return new Response(json_encode([
  1031.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  1032.                     "status" => 404,
  1033.                 ]), 404);
  1034.             }
  1035.         } else if ($token->getIdAudio()) {
  1036.             /** @var Token */
  1037.             if ($token->getIdAudio() != $audio) {
  1038.                 return new Response(json_encode([
  1039.                     "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  1040.                     "status" => 404,
  1041.                 ]), 404);
  1042.             }
  1043.         } else {
  1044.             return new Response(json_encode([
  1045.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de ce client",
  1046.                 "status" => 404,
  1047.             ]), 404);
  1048.         }
  1049.         if ($request->query->get('audio')) {
  1050.             /** @var ActivityRepository */
  1051.             $activityRepo $this->getDoctrine();
  1052.             if ($request->query->get('limit')) {
  1053.                 /** @var Rdv[] */
  1054.                 $rdvs $activityRepo
  1055.                     ->getRepository(Rdv::class)
  1056.                     ->findLastsOldRdvCentresWithLimit($request->query->get('limit'), $client->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  1057.                 $rdvResult = new ArrayCollection();
  1058.             } else {
  1059.                 /** @var Rdv[] */
  1060.                 $rdvs $activityRepo
  1061.                     ->getRepository(Rdv::class)
  1062.                     ->findOldRdvsByCentre($client->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  1063.                 $rdvResult = new ArrayCollection();
  1064.             }
  1065.             //dd($rdvs);
  1066.             foreach ($rdvs as $rdv) {
  1067.                 // we comment this becoz it was just the validate , we implment other choice select
  1068.                 /* if ($rdv->getIdEtat()->getId() != 5) {
  1069.                     continue;
  1070.                 }*/
  1071.                 /** @var AudioMotif */
  1072.                 $audioMotif $this->getDoctrine()
  1073.                     ->getRepository(AudioMotif::class)
  1074.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  1075.                 if (!$audioMotif) {
  1076.                     continue;
  1077.                 }
  1078.                 $duration '';
  1079.                 if (is_null($rdv->getDuration())) {
  1080.                     $duration $audioMotif->getDuration();
  1081.                 } else {
  1082.                     $duration $rdv->getDuration();
  1083.                 }
  1084.                 $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  1085.                 /** @var Rdv[] */
  1086.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  1087.                     ->findAllReviewsCentre($rdvCentre->getId());
  1088.                 $rdvItem = [
  1089.                     "id" => $rdv->getId(),
  1090.                     "motif_id" => $rdv->getIdMotif()->getId(),
  1091.                     "duration" => $duration,
  1092.                     "color" => $audioMotif->getColor(),
  1093.                     "audio_id" => $rdv->getIdAudio()->getId(),
  1094.                     "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  1095.                     "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  1096.                     "client_id" => $rdv->getIdClient()->getId(),
  1097.                     "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() . " " $rdv->getIdProche()->getLastname() : $rdv->getIdClient()->getName() . " " $rdv->getIdClient()->getLastname(),
  1098.                     "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  1099.                     "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  1100.                     "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  1101.                     "testclient" => $rdv->getTestClient() ? [
  1102.                         "result" => $rdv->getTestClient()->getResultTonal(),
  1103.                         "date" => $rdv->getTestClient()->getDate(),
  1104.                         "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  1105.                     ] : null,
  1106.                     "name" => $rdvCentre->getName(),
  1107.                     "phone" => $rdvCentre->getPhone(),
  1108.                     "imgUrl" => $rdvCentre->getImgUrl(),
  1109.                     "address" => $rdvCentre->getAddress(),
  1110.                     "postale" => $rdvCentre->getPostale(),
  1111.                     "city" => $rdvCentre->getCity(),
  1112.                     "etat_id" => $rdvCentre->getId(),
  1113.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  1114.                     "nbrReview" => count($centreRdvs),
  1115.                     "acceptedCurrency" => "CB Chèque",
  1116.                     "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  1117.                     "note" => $rdv->getNote(),
  1118.                     "comment" => $rdv->getComment(),
  1119.                     "review" => $rdv->getReview(),
  1120.                     "status" => $rdv->getIdEtat()->getLibelle()
  1121.                 ];
  1122.                 $rdvResult->add($rdvItem);
  1123.             }
  1124.         }
  1125.         if (count($rdvResult) > 0) {
  1126.             return new Response(json_encode(([
  1127.                 "rdv" => $rdvResult->toArray(),
  1128.                 "status" => 200,
  1129.             ])));
  1130.         } else {
  1131.             return new Response(json_encode(([
  1132.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  1133.                 'path' => 'src/Controller/RdvController.php',
  1134.                 "status" => 404,
  1135.             ])));
  1136.         }
  1137.     }
  1138.     private function getOpeningHours($centerId)
  1139.     {
  1140.         $center $this->getDoctrine()->getRepository(Centre::class)->find($centerId);
  1141.         $audioCentre $this->getDoctrine()->getRepository(AudioCentre::class)
  1142.             ->findOneBy(['id_centre' => $center->getId(), 'id_audio' => $center->getIdGerant()->getId()]);
  1143.         $schedule $audioCentre->getHoraire();
  1144.         $availableHours = [];
  1145.         if (isset($schedule['fixed'])) {
  1146.             foreach ($schedule['fixed'] as $day => $hours) {
  1147.                 $dayInFrench strtolower($day);
  1148.                 $slots = [];
  1149.                 foreach ($hours as $period) {
  1150.                     $start strtotime($period['open']);
  1151.                     $end strtotime($period['close']);
  1152.                     while ($start $end) {
  1153.                         $slots[] = date('H:i'$start);
  1154.                         $start strtotime('+30 minutes'$start);
  1155.                     }
  1156.                 }
  1157.                 $availableHours[$dayInFrench] = $slots;
  1158.             }
  1159.         }
  1160.         if (isset($schedule['exceptionalOpened'])) {
  1161.             foreach ($schedule['exceptionalOpened'] as $exception) {
  1162.                 $dayOfWeek strtolower(date('l'strtotime($exception['open'])));
  1163.                 $start strtotime($exception['open']);
  1164.                 $end strtotime($exception['close']);
  1165.                 $exceptionSlots = [];
  1166.                 while ($start $end) {
  1167.                     $exceptionSlots[] = date('H:i'$start);
  1168.                     $start strtotime('+30 minutes'$start);
  1169.                 }
  1170.                 $availableHours[$dayOfWeek] = array_merge(
  1171.                     $availableHours[$dayOfWeek] ?? [],
  1172.                     $exceptionSlots
  1173.                 );
  1174.             }
  1175.         }
  1176.         if (isset($schedule['exceptionalClosed'])) {
  1177.             foreach ($schedule['exceptionalClosed'] as $exception) {
  1178.                 $dayOfWeek strtolower(date('l'strtotime($exception['open'])));
  1179.                 unset($availableHours[$dayOfWeek]);
  1180.             }
  1181.         }
  1182.         return $availableHours;
  1183.     }
  1184.     private function getBookedSlotsForDate($centerId$date)
  1185.     {
  1186.         $bookedSlots $this->getDoctrine()
  1187.             ->getRepository(Rdv::class)
  1188.             ->getBookedSlotsForDate($centerId$date);
  1189.         return $bookedSlots;
  1190.     }
  1191.     private function getAvailableSlotsForDate($openingHours$centerId$date)
  1192.     {
  1193.         $dayOfWeek date('l'strtotime($date));
  1194.         $dayInFrench $this->convertDayToFrench($dayOfWeek);
  1195.         if (!$dayInFrench) {
  1196.             throw new \Exception("Invalid day of the week: $dayOfWeek");
  1197.         }
  1198.         $slots $openingHours[$dayInFrench] ?? [];
  1199.         $bookedSlots $this->getBookedSlotsForDate($centerId$date);
  1200.         $bookedTimes = [];
  1201.         foreach ($bookedSlots as $bookedSlot) {
  1202.             $startTime $bookedSlot['date'];
  1203.             $duration $bookedSlot['duration'];
  1204.             $endTime = (clone $startTime)->modify("+$duration minutes");
  1205.             $bookedTimes[] = ['start' => $startTime'end' => $endTime];
  1206.         }
  1207.         $availableSlots = [];
  1208.         foreach ($slots as $slot) {
  1209.             $slotTime \DateTime::createFromFormat('H:i'$slot);
  1210.             $slotTime->setDate(date('Y'strtotime($date)), date('m'strtotime($date)), date('d'strtotime($date)));
  1211.             if (!$slotTime) {
  1212.                 continue;
  1213.             }
  1214.             $isAvailable true;
  1215.             foreach ($bookedTimes as $bookedTime) {
  1216.                 if ($slotTime >= $bookedTime['start'] && $slotTime $bookedTime['end']) {
  1217.                     $isAvailable false;
  1218.                     break;
  1219.                 }
  1220.             }
  1221.             if ($isAvailable) {
  1222.                 $availableSlots[] = $slot;
  1223.             }
  1224.         }
  1225.         return $availableSlots;
  1226.     }
  1227.     private function convertDayToFrench($englishDay)
  1228.     {
  1229.         $daysMap = [
  1230.             'monday' => 'lundi',
  1231.             'tuesday' => 'mardi',
  1232.             'wednesday' => 'mercredi',
  1233.             'thursday' => 'jeudi',
  1234.             'friday' => 'vendredi',
  1235.             'saturday' => 'samedi',
  1236.             'sunday' => 'dimanche'
  1237.         ];
  1238.         return $daysMap[strtolower($englishDay)] ?? null;
  1239.     }
  1240.     /**
  1241.      * @Route("/audio/{id}/rdvs/", name="getAudioRdvs", methods={"GET","HEAD"})
  1242.      */
  1243.     public function getAudioRdvs(Request $requestAudio $audio)
  1244.     {
  1245.         if (!$request->query->get('token')) {
  1246.             return new Response(json_encode([
  1247.                 "message" => "Pas de token n'a été spécifié",
  1248.                 "status" => 401,
  1249.             ]), 401);
  1250.         }
  1251.         $entityManager $this->getDoctrine()->getManager();
  1252.         /** @var Token */
  1253.         $token $this->getDoctrine()
  1254.             ->getRepository(Token::class)
  1255.             ->findOneBy(['token' => $request->query->get('token')]);
  1256.         if (!$token) {
  1257.             return new Response(json_encode([
  1258.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1259.                 "status" => 404,
  1260.             ]), 404);
  1261.         }
  1262.         // get token age
  1263.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1264.         // if the token if older than 7 days
  1265.         if ($dateDiff->7) {
  1266.             $entityManager->remove($token);
  1267.             $entityManager->flush();
  1268.             return $this->json([
  1269.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1270.                 'path' => 'src/Controller/ClientController.php',
  1271.                 "status" => 401,
  1272.             ], 401);
  1273.         }
  1274.         if ($audio != $token->getIdAudio()) {
  1275.             return new Response(json_encode([
  1276.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1277.                 "status" => 404,
  1278.             ]), 404);
  1279.         }
  1280.         $centre = (int)$request->query->get('centre');
  1281.         if (($request->query->get('debut')) && ($request->query->get('fin'))) {
  1282.             $rdvs $this->getDoctrine()
  1283.                 ->getRepository(Rdv::class)
  1284.                 ->findBetweenDate(
  1285.                     $audio->getId(),
  1286.                     new DateTime($request->query->get('debut')),
  1287.                     new DateTime($request->query->get('fin')),
  1288.                     $centre // Le centre est maintenant un entier
  1289.                 );
  1290.         } else {
  1291.             $rdvs $this->getDoctrine()
  1292.                 ->getRepository(Rdv::class)
  1293.                 ->findBy(['id_audio' => $audio->getId()]);
  1294.         }
  1295.         $rdvResult = new ArrayCollection();
  1296.         $centerId $request->query->get('centre');
  1297.         // $openingHours = $this->getOpeningHours($centerId); 
  1298.         $centerId $request->query->get('centre');
  1299.         $dateCache = new \DateTime();
  1300.         $openingHours $this->cache->get('centre_' $centerId '_horaires_' $dateCache->format('Y-m-d'), function (ItemInterface $item) use ($centerId$dateCache) {
  1301.             $item->expiresAfter(7200);
  1302.             return $this->getOpeningHours($centerId);
  1303.         });
  1304.         //dd($openingHours);
  1305.         foreach ($rdvs as $rdv) {
  1306.             if ($rdv->getIdEtat()->getId() != null) {
  1307.                 if ($rdv->getIsAbsence() != 1) {
  1308.                     /** @var AudioMotif */
  1309.                     $audioMotif $this->getDoctrine()
  1310.                         ->getRepository(AudioMotif::class)
  1311.                         ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $audio->getId()]);
  1312.                     if (!isset($audioMotif)) {
  1313.                         continue;
  1314.                     }
  1315.                     $motif $this->getDoctrine()
  1316.                         ->getRepository(Motif::class)
  1317.                         ->findOneBy(['id' => $rdv->getIdMotif()->getId()]);
  1318.                     $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  1319.                     if ($rdv->getIdClientTemp()) {
  1320.                         $confiance "";
  1321.                     } else {
  1322.                         $confiance $client->getIdPersonneConfiance() ? $client->getIdPersonneConfiance()->getId() : null;
  1323.                     }
  1324.                 }
  1325.                 $duration '';
  1326.                 if (is_null($rdv->getDuration())) {
  1327.                     $duration $audioMotif->getDuration();
  1328.                 } else {
  1329.                     $duration $rdv->getDuration();
  1330.                 }
  1331.                 $dateFin = new DateTime($rdv->getDate()->format('Y-m-d\TH:i:s'));
  1332.                 $dateFin $dateFin->add(new DateInterval("PT" $duration "M"));
  1333.                 if ($rdv->getIdClientTemp()) {
  1334.                     $findNextRdv $this->getDoctrine()
  1335.                         ->getRepository(Rdv::class)
  1336.                         ->findBy([
  1337.                             "id_client_temp" => $rdv->getIdClientTemp(),
  1338.                             "id_motif" => ['106''107''108''109']
  1339.                         ]);
  1340.                 } else {
  1341.                     $findNextRdv $this->getDoctrine()
  1342.                         ->getRepository(Rdv::class)
  1343.                         ->findBy([
  1344.                             "id_client_temp" => $rdv->getIdClient(),
  1345.                             "id_motif" => ['106''107''108''109']
  1346.                         ]);
  1347.                 }
  1348.                 $finalRdv null;
  1349.                 /*if ($rdv->getRdvParent()) {
  1350.     $finalRdv = $this->getDoctrine()
  1351.         ->getRepository(Rdv::class)
  1352.         ->find($rdv->getRdvParent());
  1353. }*/
  1354.                 //if($client->getClientDevices())
  1355.                 //{
  1356.                 //if ($client->getClientDevices()->first()) {
  1357.                 /*$nextRdv = $this->getDoctrine()
  1358.                  ->getRepository(Rdv::class)
  1359.                  ->find($finalRdv->getClientDevice()->getRdv()->getId());*/
  1360.                 //  }
  1361.                 //}
  1362.                 if ($rdv->getIsAbsence() != 1) {
  1363.                     if ($rdv->getIdClientTemp()) {
  1364.                         $nextRdvs $this->getDoctrine()
  1365.                             ->getRepository(Rdv::class)
  1366.                             ->findBy([
  1367.                                 "id_client_temp" => $client,
  1368.                                 "id_motif" => ['106''107''108''109']
  1369.                             ]);
  1370.                     } else {
  1371.                         $nextRdvs $this->getDoctrine()
  1372.                             ->getRepository(Rdv::class)
  1373.                             ->findBy([
  1374.                                 "id_client" => $client,
  1375.                                 "id_motif" => ['106''107''108''109']
  1376.                             ]);
  1377.                     }
  1378.                     if ($client->getClientDevices()) {
  1379.                         if ($client->getClientDevices()->first()) {
  1380.                             if (empty($nextRdvs)) {
  1381.                                 $isNextRdv false;
  1382.                                 $initialRdvDate $rdv->getDate();
  1383.                                 $availableSlots = [
  1384.                                     'Suivi de l’essai' => $this->findFirstAvailableSlot($centerId$initialRdvDate7),
  1385.                                     'Confirmation de l’essai' => $this->findFirstAvailableSlot($centerId$initialRdvDate14),
  1386.                                     'Validation de l’appareillage' => $this->findFirstAvailableSlot($centerId$initialRdvDate21),
  1387.                                     'Facturation de l’appareillage' => $this->findFirstAvailableSlot($centerId$initialRdvDate30),
  1388.                                     'duration' => "30"
  1389.                                 ];
  1390.                                 $mappedNextRdvs = [
  1391.                                     'Suivi de l’essai' => $this->findAvailableDay($centerId$initialRdvDate7),
  1392.                                     'Confirmation de l’essai' => $this->findAvailableDay($centerId$initialRdvDate14),
  1393.                                     'Validation de l’appareillage' => $this->findAvailableDay($centerId$initialRdvDate21),
  1394.                                     'Facturation de l’appareillage' => $this->findAvailableDay($centerId$initialRdvDate30),
  1395.                                     'duration' => "30"
  1396.                                 ];
  1397.                             } else {
  1398.                                 $isNextRdv true;
  1399.                                 $initialRdvDate $rdv->getDate();
  1400.                                 // Available slots for each follow-up date
  1401.                                 $availableSlots = [];
  1402.                                 if (isset($nextRdvs[0])) {
  1403.                                     $availableSlots['Suivi de l’essai'] = $this->getAvailableSlotsForDate(
  1404.                                         $openingHours,
  1405.                                         $centerId,
  1406.                                         $nextRdvs[0]->getDate()->format('Y-m-d')
  1407.                                     );
  1408.                                 }
  1409.                                 if (isset($nextRdvs[1])) {
  1410.                                     $availableSlots['Confirmation de l’essai'] = $this->getAvailableSlotsForDate(
  1411.                                         $openingHours,
  1412.                                         $centerId,
  1413.                                         $nextRdvs[1]->getDate()->format('Y-m-d')
  1414.                                     );
  1415.                                 }
  1416.                                 if (isset($nextRdvs[2])) {
  1417.                                     $availableSlots['Validation de l’appareillage'] = $this->getAvailableSlotsForDate(
  1418.                                         $openingHours,
  1419.                                         $centerId,
  1420.                                         $nextRdvs[2]->getDate()->format('Y-m-d')
  1421.                                     );
  1422.                                 }
  1423.                                 if (isset($nextRdvs[3])) {
  1424.                                     $availableSlots['Facturation de l’appareillage'] = $this->getAvailableSlotsForDate(
  1425.                                         $openingHours,
  1426.                                         $centerId,
  1427.                                         $nextRdvs[3]->getDate()->format('Y-m-d')
  1428.                                     );
  1429.                                 }
  1430.                                 $mappedNextRdvs array_map(function ($rdv) {
  1431.                                     return [
  1432.                                         'id' => $rdv->getId(),
  1433.                                         'date' => $rdv->getDate()->format('d-m-Y'),
  1434.                                         'hours' => $rdv->getDate()->format('H:i'),
  1435.                                         'duration' => $rdv->getDuration(),
  1436.                                         "motif_id" => $rdv->getIdMotif()->getId(),
  1437.                                         "motif_titre" => $rdv->getIdMotif()->getTitre(),
  1438.                                     ];
  1439.                                 }, $nextRdvs);
  1440.                             }
  1441.                         }
  1442.                     }
  1443.                     $rdvItem = [
  1444.                         "id" => $rdv->getId(),
  1445.                         "motif_id" => $rdv->getIdMotif()->getId(),
  1446.                         "motif_titre" => $motif->getTitre(),
  1447.                         "duration" => $duration,
  1448.                         "color" => $audioMotif->getColor(),
  1449.                         "audio_id" => $rdv->getIdAudio()->getId(),
  1450.                         "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  1451.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  1452.                         "client_id" => $client->getId(),
  1453.                         "isClient" => ($client instanceof Client) ? 0,
  1454.                         "client_name" => $rdv->getIdProche() ? $rdv->getIdProche()->getName() : $client->getName(),
  1455.                         "client_lastname" => $rdv->getIdProche() ? $rdv->getIdProche()->getLastname() : $client->getLastname(),
  1456.                         "client_mail" => $client->getMail(),
  1457.                         "client_tel" => $client->getPhone(),
  1458.                         "client_fixe" => $client->getPhoneFixe(),
  1459.                         "confiance" =>  $confiance,
  1460.                         "client_birthday" => $client->getBirthdate() ? $client->getBirthdate()->format("Y-m-d") : null,
  1461.                         "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  1462.                         "centre_id" => $rdv->getIdCentre()->getId(),
  1463.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  1464.                         "testclient" => $rdv->getTestClient() ? [
  1465.                             "result" => $rdv->getTestClient()->getResultTonal(),
  1466.                             "date" => $rdv->getTestClient()->getDate(),
  1467.                             "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  1468.                         ] : null,
  1469.                         "name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : $rdv->getIdLieu()->getName(),
  1470.                         "centerName" => $rdv->getIdCentre()->getName(),
  1471.                         "phone" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getPhone() : $rdv->getIdLieu()->getPhone(),
  1472.                         "etat_id" => $rdv->getIdEtat()->getId(),
  1473.                         "clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
  1474.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  1475.                         "dateFin" => $dateFin->format('Y-m-d\TH:i:s'),
  1476.                         "comment" => $rdv->getComment(),
  1477.                         "note" => $rdv->getNote(),
  1478.                         "isTemp" => $rdv->getIdClientTemp() ? 0,
  1479.                         "isAbsence" => $rdv->getIsAbsence(),
  1480.                         "device" => $client->getClientDevices()->first() ? [
  1481.                             "isDevice" => true,
  1482.                             "isNextRdv" => $isNextRdv,
  1483.                             "deviceID" => $client->getClientDevices()->first()->getDevice()->getId(),
  1484.                             "clientDeviceID" => $client->getClientDevices()->first()->getId(),
  1485.                             "deviceModel" => $client->getClientDevices()->first()->getDevice()->getModel(),
  1486.                             "settingDeviceId" => $client->getClientDevices()->first()->getSettingDevice()->getSlug(),
  1487.                             "settingName" => $client->getClientDevices()->first()->getSettingDevice()->getName(),
  1488.                             "settingSlug" => $client->getClientDevices()->first()->getSettingDevice()->getSlug(),
  1489.                             "nextRdvs" => $mappedNextRdvs,
  1490.                             "available_slots" => $availableSlots
  1491.                         ] : [
  1492.                             "isDevice" => false
  1493.                         ]
  1494.                     ];
  1495.                 } else {
  1496.                     // $clientDevice = $client->getClientDevices()->first();
  1497.                     $rdvItem = [
  1498.                         "id" => $rdv->getId(),
  1499.                         "duration" => $duration,
  1500.                         "color" => $rdv->getColor() ? $rdv->getColor() . '66' '#ffb2b266',
  1501.                         "audio_id" => $rdv->getIdAudio()->getId(),
  1502.                         "client_id" =>  "",
  1503.                         "isClient" => false,
  1504.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  1505.                         "centre_id" => $rdv->getIdCentre()->getId(),
  1506.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  1507.                         "name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : $rdv->getIdLieu()->getName(),
  1508.                         "phone" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getPhone() : $rdv->getIdLieu()->getPhone(),
  1509.                         "etat_id" => $rdv->getIdEtat()->getId(),
  1510.                         "clientEtatId" => "",
  1511.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  1512.                         "dateFin" => $dateFin->format('Y-m-d\TH:i:s'),
  1513.                         "note" => $rdv->getNote(),
  1514.                         "device" => "",
  1515.                         "centerName" => $rdv->getIdCentre()->getName(),
  1516.                         "isTemp" => $rdv->getIdClientTemp() ? 0,
  1517.                         "isAbsence" => $rdv->getIsAbsence(),
  1518.                         "motif_titre" => $rdv->getMotifAbsence() ? $rdv->getMotifAbsence() : "Absence",
  1519.                     ];
  1520.                 }
  1521.                 //  if ($rdv->getDate() >= new DateTime())
  1522.                 $rdvResult->add($rdvItem);
  1523.             }
  1524.         }
  1525.         $startDate = new \DateTime('2024-02-20');
  1526.         $rdvs $this->rdvRepo->findRdvsNeedingReminderByAudio($startDate$audio->getId());
  1527.         //dd($audio->getId());
  1528.         $reminders = [];
  1529.         //dd($rdvs);
  1530.         foreach ($rdvs as $rdv) {
  1531.             $info $this->checkRdvReminder($rdv);
  1532.             if ($info !== null) {
  1533.                 $reminders[] = $info;
  1534.             }
  1535.         }
  1536.         //dd($reminders);
  1537.         if (count($rdvResult) > 0) {
  1538.             return new Response(json_encode(([
  1539.                 "content" => $rdvResult->toArray(),
  1540.                 "status" => 200,
  1541.                 "reminders" => $reminders,
  1542.                 "datefin" => $dateFin
  1543.             ])));
  1544.         } else {
  1545.             $rdvItem = [];
  1546.             //$rdvResult->add($rdvItem);
  1547.             return new Response(json_encode(([
  1548.                 "content" => $rdvResult->toArray(),
  1549.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  1550.                 'path' => 'src/Controller/RdvController.php',
  1551.                 "reminders" => $reminders,
  1552.                 "status" => 404,
  1553.             ])));
  1554.         }
  1555.     }
  1556.     private function findAvailableDay(int $centerId\DateTime $initialRdvDateint $offset): string
  1557.     {
  1558.         $currentDate = (clone $initialRdvDate)->modify("+{$offset} days");
  1559.         while (true) {
  1560.             $formattedDate $currentDate->format('Y-m-d');
  1561.             $slots $this->getAvailableSlotsForDate(
  1562.                 $this->getOpeningHoursList($centerId$formattedDate),
  1563.                 $centerId,
  1564.                 $formattedDate
  1565.             );
  1566.             if (!empty($slots)) {
  1567.                 return $formattedDate;
  1568.             }
  1569.             $currentDate->modify('+1 day');
  1570.         }
  1571.     }
  1572.     private function findFirstAvailableSlot(int $centerId\DateTime $initialRdvDateint $offset): array
  1573.     {
  1574.         $currentDate = (clone $initialRdvDate)->modify("+{$offset} days");
  1575.         while (true) {
  1576.             $formattedDate $currentDate->format('Y-m-d');
  1577.             $slots $this->getAvailableSlotsForDate(
  1578.                 $this->getOpeningHoursList($centerId$formattedDate),
  1579.                 $centerId,
  1580.                 $formattedDate
  1581.             );
  1582.             if (!empty($slots)) {
  1583.                 return $slots;
  1584.             }
  1585.             $currentDate->modify('+1 day');
  1586.         }
  1587.     }
  1588.     private function getOpeningHoursList($centerId$date)
  1589.     {
  1590.         $center $this->getDoctrine()->getRepository(Centre::class)->find($centerId);
  1591.         $audioCentre $this->getDoctrine()->getRepository(AudioCentre::class)
  1592.             ->findOneBy(['id_centre' => $center->getId(), 'id_audio' => $center->getIdGerant()->getId()]);
  1593.         $schedule $audioCentre->getHoraire();
  1594.         $availableHours = [];
  1595.         $holidayDates = [
  1596.             'JourdelAn' => '01-01',
  1597.             'LundidePâques' => '21-04',
  1598.             'FêteduTravail' => '01-05',
  1599.             'Victoire1945' => '08-05',
  1600.             'Ascension' => '29-05',
  1601.             'LundidePentecôte' => '09-06',
  1602.             'FêteNationale' => '14-07',
  1603.             'Assomption' => '15-08',
  1604.             'Toussaint' => '01-11',
  1605.             'Armistice1918' => '11-11',
  1606.             'Noël' => '25-12',
  1607.         ];
  1608.         $holidays $center->getHorairesHoliday();
  1609.         $requestDate date('d-m'strtotime($date));
  1610.         $englishToFrenchDays = [
  1611.             'monday' => 'lundi',
  1612.             'tuesday' => 'mardi',
  1613.             'wednesday' => 'mercredi',
  1614.             'thursday' => 'jeudi',
  1615.             'friday' => 'vendredi',
  1616.             'saturday' => 'samedi',
  1617.             'sunday' => 'dimanche',
  1618.         ];
  1619.         $dayOfWeek strtolower(date('l'strtotime($date)));
  1620.         $dayInFrench $englishToFrenchDays[$dayOfWeek];
  1621.         if (isset($schedule['fixed'])) {
  1622.             foreach ($schedule['fixed'] as $day => $hours) {
  1623.                 $dayKey strtolower($day);
  1624.                 $slots = [];
  1625.                 foreach ($hours as $period) {
  1626.                     $start strtotime($period['open']);
  1627.                     $end strtotime($period['close']);
  1628.                     while ($start $end) {
  1629.                         $slots[] = date('H:i'$start);
  1630.                         $start strtotime('+30 minutes'$start);
  1631.                     }
  1632.                 }
  1633.                 $availableHours[$dayKey] = $slots;
  1634.             }
  1635.         }
  1636.         foreach ($holidays['fixed'] as $holiday => $hours) {
  1637.             if (isset($holidayDates[$holiday]) && $holidayDates[$holiday] === $requestDate) {
  1638.                 $holidaySlots = [];
  1639.                 if (!empty($hours)) {
  1640.                     foreach ($hours as $period) {
  1641.                         $start strtotime($period['open']);
  1642.                         $end strtotime($period['close']);
  1643.                         while ($start $end) {
  1644.                             $holidaySlots[] = date('H:i'$start);
  1645.                             $start strtotime('+30 minutes'$start);
  1646.                         }
  1647.                     }
  1648.                     $availableHours[$dayInFrench] = $holidaySlots;
  1649.                 } else {
  1650.                     $availableHours[$dayInFrench] = [];
  1651.                 }
  1652.                 break;
  1653.             }
  1654.         }
  1655.         return $availableHours;
  1656.     }
  1657.     /**
  1658.      * @Route("/audio/{id}/rdvsTest/", name="getAudioRdvsTest", methods={"GET","HEAD"})
  1659.      */
  1660.     public function getAudioRdvsTest(Request $requestAudio $audio)
  1661.     {
  1662.         if (!$request->query->get('token')) {
  1663.             return new Response(json_encode([
  1664.                 "message" => "Pas de token n'a été spécifié",
  1665.                 "status" => 401,
  1666.             ]), 401);
  1667.         }
  1668.         $entityManager $this->getDoctrine()->getManager();
  1669.         /** @var Token */
  1670.         $token $this->getDoctrine()
  1671.             ->getRepository(Token::class)
  1672.             ->findOneBy(['token' => $request->query->get('token')]);
  1673.         if (!$token) {
  1674.             return new Response(json_encode([
  1675.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1676.                 "status" => 404,
  1677.             ]), 404);
  1678.         }
  1679.         // get token age
  1680.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1681.         // if the token if older than 7 days
  1682.         if ($dateDiff->7) {
  1683.             $entityManager->remove($token);
  1684.             $entityManager->flush();
  1685.             return $this->json([
  1686.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1687.                 'path' => 'src/Controller/ClientController.php',
  1688.                 "status" => 401,
  1689.             ], 401);
  1690.         }
  1691.         if ($audio != $token->getIdAudio()) {
  1692.             return new Response(json_encode([
  1693.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1694.                 "status" => 404,
  1695.             ]), 404);
  1696.         }
  1697.         /** @var Rdv[] */
  1698.         if (($request->query->get('debut')) && ($request->query->get('fin'))) {
  1699.             $rdvs $this->getDoctrine()
  1700.                 ->getRepository(Rdv::class)
  1701.                 ->findBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1702.         } else {
  1703.             $rdvs $this->getDoctrine()
  1704.                 ->getRepository(Rdv::class)
  1705.                 ->findBy(['id_audio' => $audio->getId()]);
  1706.         }
  1707.         $rdvResult = new ArrayCollection();
  1708.         foreach ($rdvs as $rdv) {
  1709.             if ($rdv->getIdEtat()->getId() != null) {
  1710.                 /** @var AudioMotif */
  1711.                 $audioMotif $this->getDoctrine()
  1712.                     ->getRepository(AudioMotif::class)
  1713.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $audio->getId()]);
  1714.                 if (!isset($audioMotif)) {
  1715.                     continue;
  1716.                 }
  1717.                 $motif $this->getDoctrine()
  1718.                     ->getRepository(Motif::class)
  1719.                     ->findOneBy(['id' => $rdv->getIdMotif()->getId()]);
  1720.                 $dateFin = new DateTime($rdv->getDate()->format('Y-m-d H:i:s'));
  1721.                 $dateFin $dateFin->add(new DateInterval("PT" $audioMotif->getDuration() . "M"));
  1722.                 $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  1723.                 $name $rdv->getIdProche() ? $rdv->getIdProche()->getName() : $client->getName();
  1724.                 $lastName $rdv->getIdProche() ? $rdv->getIdProche()->getLastname() : $client->getLastname();
  1725.                 $rdvItem = [
  1726.                     "id" => $rdv->getId(),
  1727.                     "title" => $lastName ' ' $name,
  1728.                     "start" => $rdv->getDate()->format('Y-m-d H:i:s'),
  1729.                     "end"   => $dateFin->format('Y-m-d H:i:s'),
  1730.                     "backgroundColor" => $audioMotif->getColor(),
  1731.                     "editable" => true,
  1732.                     "durationEditable" => false,
  1733.                     "resourceEditable" => true,
  1734.                     "cache" => false,
  1735.                     "motif_id" => $rdv->getIdMotif()->getId(),
  1736.                     "motif" => $motif->getTitre(),
  1737.                     "duree" => $audioMotif->getDuration(),
  1738.                     "color" => $audioMotif->getColor(),
  1739.                     "color_motif" => $audioMotif->getColor(),
  1740.                     "client_id" => $client->getId(),
  1741.                     "clientName" => $name,
  1742.                     "clientLastName" => $lastName,
  1743.                     "mail" => $client->getMail(),
  1744.                     "telephone" => $client->getPhone(),
  1745.                     "birthday" => $client->getBirthdate(),
  1746.                     "etat_id" => $rdv->getIdEtat()->getId(),
  1747.                     "dateDeb" => $rdv->getDate()->format('Y-m-d H:i:s'),
  1748.                     "dateFin" => $dateFin->format('Y-m-d H:i:s'),
  1749.                     "commentaire" => $rdv->getNote(),
  1750.                     "event_title" => "<b>" $lastName "</b> " $name,
  1751.                 ];
  1752.                 //  if ($rdv->getDate() >= new DateTime())
  1753.                 $rdvResult->add($rdvItem);
  1754.             }
  1755.         }
  1756.         if (count($rdvResult) > 0) {
  1757.             return new Response(json_encode(
  1758.                 $rdvResult->toArray(),
  1759.             ));
  1760.         } else {
  1761.             $rdvItem = [];
  1762.             //$rdvResult->add($rdvItem);
  1763.             return new Response(json_encode(
  1764.                 $rdvResult->toArray(),
  1765.             ));
  1766.         }
  1767.     }
  1768.     /**
  1769.      * @Route("/audio/{id}/rdvs/count", name="getCountAudioRdvs", methods={"GET","HEAD"})
  1770.      */
  1771.     public function getCountAudioRdvs(Request $requestAudio $audio)
  1772.     {
  1773.         if (!$request->query->get('token')) {
  1774.             return new Response(json_encode([
  1775.                 "message" => "Pas de token n'a été spécifié",
  1776.                 "status" => 401,
  1777.             ]), 401);
  1778.         }
  1779.         $entityManager $this->getDoctrine()->getManager();
  1780.         /** @var Token */
  1781.         $token $this->getDoctrine()
  1782.             ->getRepository(Token::class)
  1783.             ->findOneBy(['token' => $request->query->get('token')]);
  1784.         if (!$token) {
  1785.             return new Response(json_encode([
  1786.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1787.                 "status" => 404,
  1788.             ]), 404);
  1789.         }
  1790.         // get token age
  1791.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1792.         // if the token if older than 7 days
  1793.         if ($dateDiff->7) {
  1794.             $entityManager->remove($token);
  1795.             $entityManager->flush();
  1796.             return $this->json([
  1797.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1798.                 'path' => 'src/Controller/ClientController.php',
  1799.                 "status" => 401,
  1800.             ], 401);
  1801.         }
  1802.         if ($audio != $token->getIdAudio()) {
  1803.             return new Response(json_encode([
  1804.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1805.                 "status" => 404,
  1806.             ]), 404);
  1807.         }
  1808.         /** @var Rdv[] */
  1809.         $rdvs $this->getDoctrine()
  1810.             ->getRepository(Rdv::class)
  1811.             ->findBy(['id_audio' => $audio->getId()]);
  1812.         return new Response(json_encode(([
  1813.             "content" => count($rdvs),
  1814.             "status" => 200,
  1815.         ])));
  1816.     }
  1817.     /**
  1818.      * @Route("/audio/{id}/rdvsDate/count", name="getCountAudioRdvsBetweenDate", methods={"GET","HEAD"})
  1819.      */
  1820.     public function getCountAudioRdvsBetweenDate(Request $requestAudio $audio)
  1821.     {
  1822.         if (!$request->query->get('token')) {
  1823.             return new Response(json_encode([
  1824.                 "message" => "Pas de token n'a été spécifié",
  1825.                 "status" => 401,
  1826.             ]), 401);
  1827.         }
  1828.         $entityManager $this->getDoctrine()->getManager();
  1829.         /** @var Token */
  1830.         $token $this->getDoctrine()
  1831.             ->getRepository(Token::class)
  1832.             ->findOneBy(['token' => $request->query->get('token')]);
  1833.         if (!$token) {
  1834.             return new Response(json_encode([
  1835.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  1836.                 "status" => 404,
  1837.             ]), 404);
  1838.         }
  1839.         // get token age
  1840.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  1841.         // if the token if older than 7 days
  1842.         if ($dateDiff->7) {
  1843.             $entityManager->remove($token);
  1844.             $entityManager->flush();
  1845.             return $this->json([
  1846.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  1847.                 'path' => 'src/Controller/ClientController.php',
  1848.                 "status" => 401,
  1849.             ], 401);
  1850.         }
  1851.         if ($audio != $token->getIdAudio()) {
  1852.             return new Response(json_encode([
  1853.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  1854.                 "status" => 404,
  1855.             ]), 404);
  1856.         }
  1857.         /** @var Rdv[] */
  1858.         $allRdvs $this->getDoctrine()
  1859.             ->getRepository(Rdv::class)
  1860.             ->findOnlyRdvAudioBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1861.         /** @var Rdv[] */
  1862.         $rdvs $this->getDoctrine()
  1863.             ->getRepository(Rdv::class)
  1864.             ->findOnlyRdvAudioWithoutTestBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1865.         /** @var Rdv[] */
  1866.         $rdvsWithTest $this->getDoctrine()
  1867.             ->getRepository(Rdv::class)
  1868.             ->findOnlyRdvAudioWithTestBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1869.         /** @var Rdv[] */
  1870.         $allRdvsCanceled $this->getDoctrine()
  1871.             ->getRepository(Rdv::class)
  1872.             ->findCanceledRdvAudioBetweenDate($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1873.         /** @var Rdv[] */
  1874.         $allRdvsCanceledCentre $this->getDoctrine()
  1875.             ->getRepository(Rdv::class)
  1876.             ->findCanceledRdvCentreBetweenDate(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1877.         /** @var Rdv[] */
  1878.         $rdvsClosed $this->getDoctrine()
  1879.             ->getRepository(Rdv::class)
  1880.             ->findClosedRdvBetweenDate(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1881.         $myLead 0;
  1882.         $rdvsCanceled $this->getDoctrine()
  1883.             ->getRepository(Rdv::class)
  1884.             ->findCanceledRdvAudioBetweenDateWithoutTest($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1885.         foreach ($rdvsCanceled as $rdvc) {
  1886.             if (!is_null($rdvc->getIdClient())) {
  1887.                 $rdvClient $this->getDoctrine()
  1888.                     ->getRepository(Rdv::class)
  1889.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1890.                 if (count($rdvClient) == 0) {
  1891.                     $myLead $myLead 1;
  1892.                 }
  1893.             }
  1894.         }
  1895.         $myLeadAdvanced 0;
  1896.         $rdvsCanceledA $this->getDoctrine()
  1897.             ->getRepository(Rdv::class)
  1898.             ->findCanceledRdvAudioBetweenDateWithTest($audio->getId(), new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1899.         foreach ($rdvsCanceledA as $rdvc) {
  1900.             if (!is_null($rdvc->getIdClient())) {
  1901.                 $rdvClient $this->getDoctrine()
  1902.                     ->getRepository(Rdv::class)
  1903.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1904.                 if (count($rdvClient) == 0) {
  1905.                     $myLeadAdvanced $myLeadAdvanced 1;
  1906.                 }
  1907.             }
  1908.         }
  1909.         /**** MY RDV Centre****/
  1910.         $myrdvCentre 0;
  1911.         $rdvs $this->getDoctrine()
  1912.             ->getRepository(Rdv::class)
  1913.             ->findRDVCentreBetweenDateWithoutTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1914.         $myrdvCentre count($rdvs);
  1915.         /**** MY RDV ADVANCED ****/
  1916.         $myRdvAdvancedCentre 0;
  1917.         $rdvsA $this->getDoctrine()
  1918.             ->getRepository(Rdv::class)
  1919.             ->findRDVCentreBetweenDateWithTestId(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1920.         $myRdvAdvancedCentre count($rdvsA);
  1921.         /**** FIRST RDV BY MOTIF PREMIER RDV ****/
  1922.         $myFirstRdv 0;
  1923.         $rdvsFirst $this->getDoctrine()
  1924.             ->getRepository(Rdv::class)
  1925.             ->findFirstRdv(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1926.         $myFirstRdv count($rdvsFirst);
  1927.         /****  RDV BY RECHERCHE RESULT VIA MYAUDIO ****/
  1928.         $myAudioRdv 0;
  1929.         $audioRdv $this->getDoctrine()
  1930.             ->getRepository(Rdv::class)
  1931.             ->findRdvMyAudio(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1932.         $myAudioRdv count($audioRdv);
  1933.         /****  RDV BY GENDER ****/
  1934.         $myRdvByGender 0;
  1935.         $audioRdvGender $this->getDoctrine()
  1936.             ->getRepository(Rdv::class)
  1937.             ->countMaleAndFemalePatient(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1938.         $myRdvByGender $audioRdvGender;
  1939.         /****  RDV BY AGE ****/
  1940.         $myRdvByAge 0;
  1941.         $audioRdvAge $this->getDoctrine()
  1942.             ->getRepository(Rdv::class)
  1943.             ->countClientsByAgeGroupsPatient(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1944.         $myRdvByAge $audioRdvAge;
  1945.         //  dd($myRdvByAge);
  1946.         /**** MY LEAD ****/
  1947.         $myLeadCentre 0;
  1948.         $rdvsCanceled $this->getDoctrine()
  1949.             ->getRepository(Rdv::class)
  1950.             ->findCanceledRdvCentreBetweenDateWithoutTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1951.         foreach ($rdvsCanceled as $rdvc) {
  1952.             if (!is_null($rdvc->getIdClient())) {
  1953.                 $rdvClient $this->getDoctrine()
  1954.                     ->getRepository(Rdv::class)
  1955.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1956.                 if (count($rdvClient) == 0) {
  1957.                     $myLeadCentre $myLeadCentre 1;
  1958.                 }
  1959.             }
  1960.         }
  1961.         /**** MY LEAD ADVANCED****/
  1962.         $myLeadAdvancedCentre 0;
  1963.         $rdvsCanceledA $this->getDoctrine()
  1964.             ->getRepository(Rdv::class)
  1965.             ->findCanceledRdvCentreBetweenDateWithTest(new DateTime($request->query->get('debut')), new DateTime($request->query->get('fin')), $request->query->get('centre'));
  1966.         foreach ($rdvsCanceledA as $rdvc) {
  1967.             if (!is_null($rdvc->getIdClient())) {
  1968.                 $rdvClient $this->getDoctrine()
  1969.                     ->getRepository(Rdv::class)
  1970.                     ->findRDVLeadByClient(new DateTime($request->query->get('debut')), $request->query->get('centre'), $rdvc->getIdClient()->getID());
  1971.                 if (count($rdvClient) == 0) {
  1972.                     $myLeadAdvancedCentre $myLeadAdvancedCentre 1;
  1973.                 }
  1974.             }
  1975.         }
  1976.         return $this->json([
  1977.             "rdvs" => count($rdvs),
  1978.             "rdvsFromTest" => count($rdvsWithTest),
  1979.             "allRdvs" => count($allRdvs),
  1980.             "rdvsCanceled" => count($allRdvsCanceled),
  1981.             "rdvsClosed" => $rdvsClosed,
  1982.             "myRdvByGender" => $myRdvByGender,
  1983.             "myLead" => $myLead,
  1984.             "myRdvByAge" => $myRdvByAge,
  1985.             "myAudioRdv" => $myAudioRdv,
  1986.             "myLeadAdvanced" => $myLeadAdvanced,
  1987.             "myRDVCentre" => $myrdvCentre,
  1988.             "myRDVAdancedCentre" => $myRdvAdvancedCentre,
  1989.             "myLeadCentre" => $myLeadCentre,
  1990.             "myLeadAdvancedCentre" => $myLeadAdvancedCentre,
  1991.             "rdvsCanceledCentre" => count($allRdvsCanceledCentre),
  1992.             "myFirstRdv" => $myFirstRdv,
  1993.             "status" => 200,
  1994.         ]);
  1995.     }
  1996.     /**
  1997.      * @Route("/rdvs/old/clientTemp/{id}", name="getOldRdvsByClientTempId", methods={"GET","HEAD"})
  1998.      */
  1999.     public function getOldRdvsByClientTempId(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2000.     {
  2001.         if (!$request->query->get('token')) {
  2002.             return new Response(json_encode([
  2003.                 "message" => "Pas de token n'a été spécifié",
  2004.                 "status" => 401,
  2005.             ]), 401);
  2006.         }
  2007.         $entityManager $this->getDoctrine()->getManager();
  2008.         /** @var Token */
  2009.         $token $this->getDoctrine()
  2010.             ->getRepository(Token::class)
  2011.             ->findOneBy(['token' => $request->query->get('token')]);
  2012.         if (!$token) {
  2013.             return new Response(json_encode([
  2014.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2015.                 "status" => 404,
  2016.             ]), 404);
  2017.         }
  2018.         // get token age
  2019.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2020.         // if the token if older than 7 days
  2021.         if ($dateDiff->7) {
  2022.             $entityManager->remove($token);
  2023.             $entityManager->flush();
  2024.             return $this->json([
  2025.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2026.                 'path' => 'src/Controller/ClientController.php',
  2027.                 "status" => 401,
  2028.             ], 401);
  2029.         }
  2030.         if ($clientTemp->getIdAudio() != $token->getIdAudio()) {
  2031.             return new Response(json_encode([
  2032.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2033.                 "status" => 404,
  2034.             ]), 404);
  2035.         }
  2036.         if ($request->query->get('audio')) {
  2037.             /** @var ActivityRepository */
  2038.             $activityRepo $this->getDoctrine()->getRepository(Rdv::class);
  2039.             if ($request->query->get('limit')) {
  2040.                 /** @var Rdv[] */
  2041.                 $rdvs $activityRepo
  2042.                     ->findLastsOldRdvsWithLimitTemp($request->query->get('limit'), $clientTemp->getId(), $request->query->get('audio'), new DateTime());
  2043.                 $rdvResult = new ArrayCollection();
  2044.             } else {
  2045.                 /** @var Rdv[] */
  2046.                 $rdvs $activityRepo
  2047.                     ->findOldRdvsTemp($clientTemp->getId(), $request->query->get('audio'), new DateTime());
  2048.                 $rdvResult = new ArrayCollection();
  2049.             }
  2050.             foreach ($rdvs as $rdv) {
  2051.                 if ($rdv->getIdEtat()->getId() != 1) {
  2052.                     continue;
  2053.                 }
  2054.                 /** @var AudioMotif */
  2055.                 $audioMotif $this->getDoctrine()
  2056.                     ->getRepository(AudioMotif::class)
  2057.                     ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  2058.                 if (!$audioMotif) {
  2059.                     continue;
  2060.                 }
  2061.                 $duration '';
  2062.                 if (is_null($rdv->getDuration())) {
  2063.                     $duration $audioMotif->getDuration();
  2064.                 } else {
  2065.                     $duration $rdv->getDuration();
  2066.                 }
  2067.                 $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  2068.                 /** @var Rdv[] */
  2069.                 $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2070.                     ->findAllReviewsCentre($rdvCentre->getId());
  2071.                 $rdvItem = [
  2072.                     "id" => $rdv->getId(),
  2073.                     "motif_id" => $rdv->getIdMotif()->getId(),
  2074.                     "duration" => $duration,
  2075.                     "color" => $audioMotif->getColor(),
  2076.                     "audio_id" => $rdv->getIdAudio()->getId(),
  2077.                     "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2078.                     "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2079.                     "client_id_temp" => $rdv->getIdClientTemp()->getId(),
  2080.                     "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2081.                     "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2082.                     "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2083.                     "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2084.                     "testclient" => $rdv->getTestClient() ? [
  2085.                         "result" => $rdv->getTestClient()->getResultTonal(),
  2086.                         "date" => $rdv->getTestClient()->getDate(),
  2087.                         "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  2088.                     ] : null,
  2089.                     "name" => $rdvCentre->getName(),
  2090.                     "phone" => $rdvCentre->getPhone(),
  2091.                     "imgUrl" => $rdvCentre->getImgUrl(),
  2092.                     "address" => $rdvCentre->getAddress(),
  2093.                     "postale" => $rdvCentre->getPostale(),
  2094.                     "city" => $rdvCentre->getCity(),
  2095.                     "etat_id" => $rdvCentre->getId(),
  2096.                     "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2097.                     "nbrReview" => count($centreRdvs),
  2098.                     "acceptedCurrency" => "CB Chèque",
  2099.                     "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2100.                     "note" => $rdv->getNote(),
  2101.                     "comment" => $rdv->getComment(),
  2102.                     "review" => $rdv->getReview(),
  2103.                 ];
  2104.                 $rdvResult->add($rdvItem);
  2105.             }
  2106.         }
  2107.         if (count($rdvResult) > 0) {
  2108.             return new Response(json_encode(([
  2109.                 "rdv" => $rdvResult->toArray(),
  2110.                 "status" => 200,
  2111.             ])));
  2112.         } else {
  2113.             return new Response(json_encode(([
  2114.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  2115.                 'path' => 'src/Controller/RdvController.php',
  2116.                 "status" => 404,
  2117.             ])));
  2118.         }
  2119.     }
  2120.     /**
  2121.      * @Route("/rdvs/old/clientTemp/{id}/centre", name="getOldRdvsByClientTempIdByCentre", methods={"GET","HEAD"})
  2122.      */
  2123.     public function getOldRdvsByClientTempIdByCentre(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2124.     {
  2125.         if (!$request->query->get('token')) {
  2126.             return new Response(json_encode([
  2127.                 "message" => "Pas de token n'a été spécifié",
  2128.                 "status" => 401,
  2129.             ]), 401);
  2130.         }
  2131.         $entityManager $this->getDoctrine()->getManager();
  2132.         /** @var Token */
  2133.         $token $this->getDoctrine()
  2134.             ->getRepository(Token::class)
  2135.             ->findOneBy(['token' => $request->query->get('token')]);
  2136.         if (!$token) {
  2137.             return new Response(json_encode([
  2138.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2139.                 "status" => 404,
  2140.             ]), 404);
  2141.         }
  2142.         // get token age
  2143.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2144.         // if the token if older than 7 days
  2145.         if ($dateDiff->7) {
  2146.             $entityManager->remove($token);
  2147.             $entityManager->flush();
  2148.             return $this->json([
  2149.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2150.                 'path' => 'src/Controller/ClientController.php',
  2151.                 "status" => 401,
  2152.             ], 401);
  2153.         }
  2154.         $audioCentre $this->getDoctrine()
  2155.             ->getRepository(AudioCentre::class)
  2156.             ->findOneBy(['id_audio' => $token->getIdAudio()]);
  2157.         // we add the multi-centre so we wil desable the autorisation 
  2158.         /*
  2159.         if ($clientTemp->getIdCentre() != $audioCentre->getIdCentre()) {
  2160.             return new Response(json_encode([
  2161.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2162.                 "status" => 404,
  2163.             ]), 404);
  2164.         }
  2165. */
  2166.         /** @var ActivityRepository */
  2167.         $activityRepo $this->getDoctrine()->getRepository(Rdv::class);
  2168.         if ($request->query->get('limit')) {
  2169.             /** @var Rdv[] */
  2170.             $rdvs $activityRepo
  2171.                 ->findLastsOldRdvsWithLimitTempByCentre($request->query->get('limit'), $clientTemp->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  2172.             $rdvResult = new ArrayCollection();
  2173.         } else {
  2174.             /** @var Rdv[] */
  2175.             $rdvs $activityRepo
  2176.                 ->findOldRdvsTempByCentre($clientTemp->getId(), $audioCentre->getIdCentre()->getId(), new DateTime());
  2177.             $rdvResult = new ArrayCollection();
  2178.         }
  2179.         foreach ($rdvs as $rdv) {
  2180.             /*if ($rdv->getIdEtat()->getId() != 1) {
  2181.                 continue;
  2182.             }*/
  2183.             /** @var AudioMotif */
  2184.             $audioMotif $this->getDoctrine()
  2185.                 ->getRepository(AudioMotif::class)
  2186.                 ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  2187.             if (!$audioMotif) {
  2188.                 continue;
  2189.             }
  2190.             $duration '';
  2191.             if (is_null($rdv->getDuration())) {
  2192.                 $duration $audioMotif->getDuration();
  2193.             } else {
  2194.                 $duration $rdv->getDuration();
  2195.             }
  2196.             $rdvCentre $rdv->getIdLieu() ? $rdv->getIdLieu() : $rdv->getIdCentre();
  2197.             /** @var Rdv[] */
  2198.             $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2199.                 ->findAllReviewsCentre($rdvCentre->getId());
  2200.             $rdvItem = [
  2201.                 "id" => $rdv->getId(),
  2202.                 "motif_id" => $rdv->getIdMotif()->getId(),
  2203.                 "duration" => $duration,
  2204.                 "color" => $audioMotif->getColor(),
  2205.                 "audio_id" => $rdv->getIdAudio()->getId(),
  2206.                 "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2207.                 "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2208.                 "client_id_temp" => $rdv->getIdClientTemp()->getId(),
  2209.                 "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2210.                 "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2211.                 "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2212.                 "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2213.                 "testclient" => $rdv->getTestClient() ? [
  2214.                     "result" => $rdv->getTestClient()->getResultTonal(),
  2215.                     "date" => $rdv->getTestClient()->getDate(),
  2216.                     "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  2217.                 ] : null,
  2218.                 "name" => $rdvCentre->getName(),
  2219.                 "phone" => $rdvCentre->getPhone(),
  2220.                 "imgUrl" => $rdvCentre->getImgUrl(),
  2221.                 "address" => $rdvCentre->getAddress(),
  2222.                 "postale" => $rdvCentre->getPostale(),
  2223.                 "city" => $rdvCentre->getCity(),
  2224.                 "etat_id" => $rdvCentre->getId(),
  2225.                 "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2226.                 "nbrReview" => count($centreRdvs),
  2227.                 "acceptedCurrency" => "CB Chèque",
  2228.                 "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2229.                 "note" => $rdv->getNote(),
  2230.                 "comment" => $rdv->getComment(),
  2231.                 "review" => $rdv->getReview(),
  2232.                 "status" => $rdv->getIdEtat()->getLibelle()
  2233.             ];
  2234.             $rdvResult->add($rdvItem);
  2235.         }
  2236.         if (count($rdvResult) > 0) {
  2237.             return new Response(json_encode(([
  2238.                 "rdv" => $rdvResult->toArray(),
  2239.                 "status" => 200,
  2240.             ])));
  2241.         } else {
  2242.             return new Response(json_encode(([
  2243.                 "message" => "Aucun rendez-vous n'a été trouvé!",
  2244.                 'path' => 'src/Controller/RdvController.php',
  2245.                 "status" => 404,
  2246.             ])));
  2247.         }
  2248.     }
  2249.     /**
  2250.      * @Route("/rdvs/clientTemp/{id}", name="getRdvsByClientTempID", methods={"GET","HEAD"})
  2251.      */
  2252.     public function getRdvsByClientTempID(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2253.     {
  2254.         if (!$request->query->get('token')) {
  2255.             return new Response(json_encode([
  2256.                 "message" => "Pas de token n'a été spécifié",
  2257.                 "status" => 401,
  2258.             ]), 401);
  2259.         }
  2260.         $entityManager $this->getDoctrine()->getManager();
  2261.         /** @var Token */
  2262.         $token $this->getDoctrine()
  2263.             ->getRepository(Token::class)
  2264.             ->findOneBy(['token' => $request->query->get('token')]);
  2265.         if (!$token) {
  2266.             return new Response(json_encode([
  2267.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2268.                 "status" => 404,
  2269.             ]), 404);
  2270.         }
  2271.         // get token age
  2272.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2273.         // if the token if older than 7 days
  2274.         if ($dateDiff->7) {
  2275.             $entityManager->remove($token);
  2276.             $entityManager->flush();
  2277.             return $this->json([
  2278.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2279.                 'path' => 'src/Controller/ClientController.php',
  2280.                 "status" => 401,
  2281.             ], 401);
  2282.         }
  2283.         if ($clientTemp->getIdAudio() != $token->getIdAudio()) {
  2284.             return new Response(json_encode([
  2285.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2286.                 "status" => 404,
  2287.             ]), 404);
  2288.         }
  2289.         /** @var Rdv[] */
  2290.         $rdvs $this->getDoctrine()
  2291.             ->getRepository(Rdv::class)
  2292.             ->findBy(['id_client_temp' => $clientTemp->getId(), 'id_audio' => $token->getIdAudio()]);
  2293.         $rdvResult = new ArrayCollection();
  2294.         if ($request->query->get('old')) {
  2295.             $oldRdvResult = new ArrayCollection();
  2296.         }
  2297.         foreach ($rdvs as $rdv) {
  2298.             if ($rdv->getIdEtat()->getId() != null) {
  2299.                 if ($rdv->getIdEtat()->getId() == 1) {
  2300.                     /** @var AudioMotif */
  2301.                     $audioMotif $this->getDoctrine()
  2302.                         ->getRepository(AudioMotif::class)
  2303.                         ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $token->getIdAudio()]);
  2304.                     /** @var Rdv[] */
  2305.                     $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2306.                         ->findAllReviewsCentre($rdv->getIdCentre()->getId());
  2307.                     $duration '';
  2308.                     if (is_null($rdv->getDuration())) {
  2309.                         $duration $audioMotif->getDuration();
  2310.                     } else {
  2311.                         $duration $rdv->getDuration();
  2312.                     }
  2313.                     $rdvItem = [
  2314.                         "id" => $rdv->getId(),
  2315.                         "motif_id" => $rdv->getIdMotif()->getId(),
  2316.                         "duration" => $duration,
  2317.                         "color" => $audioMotif->getColor(),
  2318.                         "audio_id" => $rdv->getIdAudio()->getId(),
  2319.                         "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2320.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2321.                         "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  2322.                         "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2323.                         "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2324.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2325.                         "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2326.                         "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2327.                         "nbrReview" => count($centreRdvs),
  2328.                         "acceptedCurrency" => "CB Chèque",
  2329.                         "name" => $rdv->getIdCentre()->getName(),
  2330.                         "imgUrl" => $rdv->getIdCentre()->getImgUrl(),
  2331.                         "address" => $rdv->getIdCentre()->getAddress(),
  2332.                         "phone" => $rdv->getIdCentre()->getPhone(),
  2333.                         "etat_id" => $rdv->getIdEtat()->getId(),
  2334.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2335.                         "comment" => $rdv->getComment(),
  2336.                         "note" => $rdv->getNote(),
  2337.                         "review" => $rdv->getReview(),
  2338.                     ];
  2339.                     if ($rdv->getDate() >= new DateTime()) {
  2340.                         $rdvResult->add($rdvItem);
  2341.                     } else if ($request->query->get('old')) {
  2342.                         $oldRdvResult->add($rdvItem);
  2343.                     }
  2344.                 }
  2345.             }
  2346.         }
  2347.         if ($request->query->get('old')) {
  2348.             if (count($rdvResult) > || count($oldRdvResult) > 0) {
  2349.                 return new Response(json_encode(([
  2350.                     "rdv" => $rdvResult->toArray(),
  2351.                     "oldRdv" => $oldRdvResult->toArray(),
  2352.                     "status" => 200,
  2353.                 ])));
  2354.             } else {
  2355.                 return new Response(json_encode(([
  2356.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2357.                     'path' => 'src/Controller/RdvController.php',
  2358.                     "status" => 404,
  2359.                 ])));
  2360.             }
  2361.         } else {
  2362.             if (count($rdvResult) > 0) {
  2363.                 return new Response(json_encode(([
  2364.                     "content" => $rdvResult->toArray(),
  2365.                     "status" => 200,
  2366.                 ])));
  2367.             } else {
  2368.                 return new Response(json_encode(([
  2369.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2370.                     'path' => 'src/Controller/RdvController.php',
  2371.                     "status" => 404,
  2372.                 ])));
  2373.             }
  2374.         }
  2375.     }
  2376.     /**
  2377.      * @Route("/rdvs/clientTemp/{id}/centre", name="getRdvsByClientTempIDByCentre", methods={"GET","HEAD"})
  2378.      */
  2379.     public function getRdvsByClientTempIDByCentre(Request $requestClientTemp $clientTempPublicFunction $publicFunction)
  2380.     {
  2381.         if (!$request->query->get('token')) {
  2382.             return new Response(json_encode([
  2383.                 "message" => "Pas de token n'a été spécifié",
  2384.                 "status" => 401,
  2385.             ]), 401);
  2386.         }
  2387.         $entityManager $this->getDoctrine()->getManager();
  2388.         /** @var Token */
  2389.         $token $this->getDoctrine()
  2390.             ->getRepository(Token::class)
  2391.             ->findOneBy(['token' => $request->query->get('token')]);
  2392.         if (!$token) {
  2393.             return new Response(json_encode([
  2394.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2395.                 "status" => 404,
  2396.             ]), 404);
  2397.         }
  2398.         // get token age
  2399.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2400.         // if the token if older than 7 days
  2401.         if ($dateDiff->7) {
  2402.             $entityManager->remove($token);
  2403.             $entityManager->flush();
  2404.             return $this->json([
  2405.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2406.                 'path' => 'src/Controller/ClientController.php',
  2407.                 "status" => 401,
  2408.             ], 401);
  2409.         }
  2410.         $audioCentre $this->getDoctrine()
  2411.             ->getRepository(AudioCentre::class)
  2412.             ->findOneBy(['id_audio' => $token->getIdAudio()]);
  2413.         // we add the multi-centre so we wil desable the autorisation 
  2414.         /*    
  2415.         if ($clientTemp->getIdCentre() != $audioCentre->getIdCentre()) {
  2416.             return new Response(json_encode([
  2417.                 "message" => "Vous n'êtes pas authorisé à voir les rendez-vous de cet audioprothèsiste",
  2418.                 "status" => 404,
  2419.             ]), 404);
  2420.         }*/
  2421.         /** @var Rdv[] */
  2422.         $rdvs $this->getDoctrine()
  2423.             ->getRepository(Rdv::class)
  2424.             ->findBy(['id_client_temp' => $clientTemp->getId(), 'id_centre' => $audioCentre->getIdCentre()]);
  2425.         $rdvResult = new ArrayCollection();
  2426.         if ($request->query->get('old')) {
  2427.             $oldRdvResult = new ArrayCollection();
  2428.         }
  2429.         foreach ($rdvs as $rdv) {
  2430.             if ($rdv->getIdEtat()->getId() != null) {
  2431.                 if ($rdv->getIdEtat()->getId() != 6) {
  2432.                     // if ($rdv->getIdEtat()->getId() == 1) {
  2433.                     /** @var AudioMotif */
  2434.                     $audioMotif $this->getDoctrine()
  2435.                         ->getRepository(AudioMotif::class)
  2436.                         ->findOneBy(['id_motif' => $rdv->getIdMotif()->getId(), 'id_audio' => $rdv->getIdAudio()]);
  2437.                     /** @var Rdv[] */
  2438.                     $centreRdvs $this->getDoctrine()->getRepository(Rdv::class)
  2439.                         ->findAllReviewsCentre($rdv->getIdCentre()->getId());
  2440.                     $duration '';
  2441.                     if (is_null($rdv->getDuration())) {
  2442.                         $duration $audioMotif->getDuration();
  2443.                     } else {
  2444.                         $duration $rdv->getDuration();
  2445.                     }
  2446.                     $rdvItem = [
  2447.                         "id" => $rdv->getId(),
  2448.                         "motif_id" => $rdv->getIdMotif()->getId(),
  2449.                         "duration" => $duration,
  2450.                         "color" => $audioMotif->getColor(),
  2451.                         "audio_id" => $rdv->getIdAudio()->getId(),
  2452.                         "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  2453.                         "audio_name" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  2454.                         "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  2455.                         "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  2456.                         "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  2457.                         "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  2458.                         "client_name" => $rdv->getIdClientTemp()->getName() . " " $rdv->getIdClientTemp()->getLastname(),
  2459.                         "averageRating" => $publicFunction->calculateRating($centreRdvs),
  2460.                         "nbrReview" => count($centreRdvs),
  2461.                         "acceptedCurrency" => "CB Chèque",
  2462.                         "name" => $rdv->getIdCentre()->getName(),
  2463.                         "imgUrl" => $rdv->getIdCentre()->getImgUrl(),
  2464.                         "address" => $rdv->getIdCentre()->getAddress(),
  2465.                         "phone" => $rdv->getIdCentre()->getPhone(),
  2466.                         "etat_id" => $rdv->getIdEtat()->getId(),
  2467.                         "date" => $rdv->getDate()->format('Y-m-d\TH:i:s'),
  2468.                         "comment" => $rdv->getComment(),
  2469.                         "note" => $rdv->getNote(),
  2470.                         "review" => $rdv->getReview(),
  2471.                         "status" => $rdv->getIdEtat()->getLibelle()
  2472.                     ];
  2473.                     if ($rdv->getDate() >= new DateTime()) {
  2474.                         $rdvResult->add($rdvItem);
  2475.                     } else if ($request->query->get('old')) {
  2476.                         $oldRdvResult->add($rdvItem);
  2477.                     }
  2478.                 }
  2479.             }
  2480.         }
  2481.         if ($request->query->get('old')) {
  2482.             if (count($rdvResult) > || count($oldRdvResult) > 0) {
  2483.                 return new Response(json_encode(([
  2484.                     "rdv" => $rdvResult->toArray(),
  2485.                     "oldRdv" => $oldRdvResult->toArray(),
  2486.                     "status" => 200,
  2487.                 ])));
  2488.             } else {
  2489.                 return new Response(json_encode(([
  2490.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2491.                     'path' => 'src/Controller/RdvController.php',
  2492.                     "status" => 404,
  2493.                 ])));
  2494.             }
  2495.         } else {
  2496.             if (count($rdvResult) > 0) {
  2497.                 return new Response(json_encode(([
  2498.                     "content" => $rdvResult->toArray(),
  2499.                     "status" => 200,
  2500.                 ])));
  2501.             } else {
  2502.                 return new Response(json_encode(([
  2503.                     "message" => "Aucun rendez-vous n'a été trouvé!",
  2504.                     'path' => 'src/Controller/RdvController.php',
  2505.                     "status" => 404,
  2506.                 ])));
  2507.             }
  2508.         }
  2509.     }
  2510.     /**
  2511.      * @Route("/rdv", name="postRdv", methods={"POST"})
  2512.      */
  2513.     public function postRdv(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSmsAppointmentCallService $Callservice): Response
  2514.     {
  2515.         $data json_decode($request->getContent(), true);
  2516.         if (!isset($data["token"])) {
  2517.             return new Response(json_encode([
  2518.                 "message" => "Pas de token n'a été spécifié",
  2519.                 "status" => 401,
  2520.             ]), 401);
  2521.         }
  2522.         $entityManager $this->getDoctrine()->getManager();
  2523.         /** @var Token */
  2524.         $token $this->getDoctrine()
  2525.             ->getRepository(Token::class)
  2526.             ->findOneBy(['token' => $data["token"]]);
  2527.         if (!$token) {
  2528.             return new Response(json_encode([
  2529.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  2530.                 "status" => 404,
  2531.             ]), 404);
  2532.         }
  2533.         // get token age
  2534.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  2535.         // if the token if older than 7 days
  2536.         if ($dateDiff->7) {
  2537.             $entityManager->remove($token);
  2538.             $entityManager->flush();
  2539.             return $this->json([
  2540.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  2541.                 'path' => 'src/Controller/ClientController.php',
  2542.                 "status" => 401,
  2543.             ], 401);
  2544.         }
  2545.         // makes the rdv
  2546.         $rdv = new Rdv();
  2547.         if ($token->getIdAudio()) {
  2548.             //if the token if for an audio
  2549.             $audio $token->getIdAudio();
  2550.             if ((isset($data["client_id"]))) {
  2551.                 $client $this->getDoctrine()
  2552.                     ->getRepository(Client::class)
  2553.                     ->findOneBy(['id' => $data["client_id"]]);
  2554.             } else {
  2555.                 $client $this->getDoctrine()
  2556.                     ->getRepository(ClientTemp::class)
  2557.                     ->findOneBy(['id' => $data["client_id_temp"]]);
  2558.             }
  2559.             if ($client == null) {
  2560.                 return new Response(json_encode(([
  2561.                     'message' => 'Error, no client found at this id',
  2562.                     'path' => 'src/Controller/RdvController.php',
  2563.                     "status" => 400,
  2564.                 ])), 400);
  2565.             }
  2566.         } elseif ($token->getIdClient()) {
  2567.             //if the token if for a client
  2568.             $client $token->getIdClient();
  2569.             /** @var ActivityRepository */
  2570.             $activityRepo $this->getDoctrine();
  2571.             /** @var TestClient */
  2572.             $testClient $activityRepo
  2573.                 ->getRepository(TestClient::class)
  2574.                 ->getLatestTestClient($client);
  2575.             // add the test to the rdv if the client had one
  2576.             if ($testClient)
  2577.             // add the test to the rdv if the test isn't already on another rdv
  2578.             {
  2579.                 if (!$testClient->getRdv()) {
  2580.                     $rdv->setTestClient($testClient);
  2581.                 }
  2582.             }
  2583.             /** @var Audio */
  2584.             $audio $this->getDoctrine()
  2585.                 ->getRepository(Audio::class)
  2586.                 ->findOneBy(['id' => $data["audio_id"]]);
  2587.             if (isset($data["proche_id"])) {
  2588.                 $proche $this->getDoctrine()
  2589.                     ->getRepository(Proches::class)
  2590.                     ->findOneBy(['id' => $data["proche_id"], "id_client" => $client]);
  2591.             }
  2592.             if (!$audio) {
  2593.                 return new Response(json_encode(([
  2594.                     'message' => "Erreur, pas d'audio n'a été trouvé à cette id.",
  2595.                     'path' => 'src/Controller/RdvController.php',
  2596.                 ])), 400);
  2597.             }
  2598.             /** @var ClientBlocked */
  2599.             $clientBlocked $this->getDoctrine()
  2600.                 ->getRepository(ClientBlocked::class)
  2601.                 ->findOneBy(["id_audio" => $audio"id_client" => $client]);
  2602.             if ($clientBlocked) {
  2603.                 return new Response(json_encode(([
  2604.                     'message' => 'Erreur, vous avez été bloqué par cette audioprothésiste.',
  2605.                     'path' => 'src/Controller/RdvController.php',
  2606.                 ])), 400);
  2607.             }
  2608.             // set the rdv test
  2609.         } else {
  2610.             return new Response(json_encode(([
  2611.                 'message' => "Erreur, ce token n'est pas celui d'un client ou audioprothèsiste.",
  2612.                 'path' => 'src/Controller/RdvController.php',
  2613.             ])), 400);
  2614.         }
  2615.         $rdv->setIdAudio($audio);
  2616.         if (isset($proche)) {
  2617.             $rdv->setIdProche($proche);
  2618.         }
  2619.         if (isset($data["client_id_temp"])) {
  2620.             $rdv->setIdClientTemp($client);
  2621.         } else {
  2622.             $rdv->setIdClient($client);
  2623.         }
  2624.         if (isset($data["isMyaudio"])) {
  2625.             $rdv->setIsMyaudio(true);
  2626.         }
  2627.         if (isset($data["isRdvLead"])) {
  2628.             $rdv->setIsRdvLp(true);
  2629.         }
  2630.         if (isset($data["isRdvRapide"])) {
  2631.             $rdv->setIsRdvRapide(true);
  2632.         }
  2633.         if (isset($data["duree"])) {
  2634.             $rdv->setDuration($data["duree"]);
  2635.         }
  2636.         if (isset($data["color"])) {
  2637.             $rdv->setColor($data["color"]);
  2638.         }
  2639.         if (isset($data["lead"])) {
  2640.             $lead $this->getDoctrine()
  2641.                 ->getRepository(LeadRdv::class)
  2642.                 ->find($data["lead"]);
  2643.             $lead->setRdv($rdv);
  2644.             $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
  2645.             if ($leadStatus) {
  2646.                 $lead->setLeadStatus($leadStatus);
  2647.             }
  2648.         }
  2649.         /** @var Centre */
  2650.         if (isset($data["centre_id"])) {
  2651.             $centre $this->getDoctrine()
  2652.                 ->getRepository(Centre::class)
  2653.                 ->findOneBy(['id' => $data["centre_id"]]);
  2654.             if ($centre == null) {
  2655.                 return new Response(json_encode(([
  2656.                     'message' => 'Error, no centre found at this id',
  2657.                     'path' => 'src/Controller/RdvController.php',
  2658.                     "status" => 400,
  2659.                 ])), 400);
  2660.             }
  2661.             /** @var AudioCentre */
  2662.             $liaison $this->getDoctrine()
  2663.                 ->getRepository(AudioCentre::class)
  2664.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  2665.             if ($liaison == null) {
  2666.                 return new Response(json_encode(([
  2667.                     'message' => 'Error, audio isnt part of the centre',
  2668.                     'path' => 'src/Controller/RdvController.php',
  2669.                     "status" => 400,
  2670.                 ])), 400);
  2671.             }
  2672.             $rdv->setIdCentre($centre);
  2673.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  2674.             // tries to set the lieu if it's an audio indie
  2675.             $lieu $this->getDoctrine()
  2676.                 ->getRepository(Lieu::class)
  2677.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  2678.             if ($lieu == null) {
  2679.                 return new Response(json_encode(([
  2680.                     'message' => 'Error, no lieu found at this id',
  2681.                     'path' => 'src/Controller/RdvController.php',
  2682.                     "status" => 400,
  2683.                 ])), 400);
  2684.             }
  2685.             $rdv->setIdLieu($lieu);
  2686.         } else {
  2687.             return new Response(json_encode(([
  2688.                 'message' => 'Error, no lieu/centre id',
  2689.                 'path' => 'src/Controller/RdvController.php',
  2690.                 "status" => 400,
  2691.             ])), 400);
  2692.         }
  2693.         /** @var Motif */
  2694.         $motif $this->getDoctrine()
  2695.             ->getRepository(Motif::class)
  2696.             ->find($data["motif_id"]);
  2697.         if ($motif == null) {
  2698.             return new Response(json_encode(([
  2699.                 'message' => 'Error, no motif found at this id',
  2700.                 'path' => 'src/Controller/RdvController.php',
  2701.                 "status" => 400,
  2702.             ])), 400);
  2703.         }
  2704.         /** @var AudioMotif */
  2705.         $audioMotif $this->getDoctrine()
  2706.             ->getRepository(AudioMotif::class)
  2707.             ->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
  2708.         if ($audioMotif == null) {
  2709.             return new Response(json_encode(([
  2710.                 'message' => 'Error, no motif of this id found at this audio',
  2711.                 'path' => 'src/Controller/RdvController.php',
  2712.                 "status" => 400,
  2713.             ])), 400);
  2714.         }
  2715.         // remove the taken schedule by rdv to make sure there is no overlap
  2716.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  2717.         if (isset($data["note"])) {
  2718.             $rdv->setNote($data["note"]);
  2719.         }
  2720.         // test if the audio is available
  2721.         if ($audio->getIsIndie()) {
  2722.             if (isset($data["centre_id"])) {
  2723.                 if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  2724.                     return new Response(json_encode(([
  2725.                         'message' => 'Error, no horaire found for this audio',
  2726.                         'path' => 'src/Controller/RdvController.php',
  2727.                         "status" => 400,
  2728.                     ])), 400);
  2729.                 }
  2730.                 if ($publicFunction->calculScheduleFitDate($audio\DateTime::createFromFormat("d/m/Y H:i"$data["date"]), $audioMotif->getDuration(), $centre) == false) {
  2731.                     return new Response(json_encode(([
  2732.                         'message' => 'Error, no timestamp found at this time. Line n°' __LINE__,
  2733.                         'path' => 'src/Controller/RdvController.php',
  2734.                         "status" => 400,
  2735.                     ])), 400);
  2736.                 }
  2737.                 $remplacant_id $publicFunction->checkIfRemplacant($liaison->getHoraire(), $date);
  2738.             } else {
  2739.                 if ($lieu->getHoraire() == null || $lieu->getHoraire() == []) {
  2740.                     return new Response(json_encode(([
  2741.                         'message' => 'Error, no horaire found for this audio',
  2742.                         'path' => 'src/Controller/RdvController.php',
  2743.                         "status" => 400,
  2744.                     ])), 400);
  2745.                 }
  2746.                 if ($publicFunction->calculScheduleFitDate($audio\DateTime::createFromFormat("d/m/Y H:i"$data["date"]), $audioMotif->getDuration(), null$lieu) == false) {
  2747.                     return new Response(json_encode(([
  2748.                         'message' => 'Error, no timestamp found at this time. Line n°' __LINE__,
  2749.                         'path' => 'src/Controller/RdvController.php',
  2750.                         "status" => 400,
  2751.                     ])), 400);
  2752.                 }
  2753.                 $remplacant_id $publicFunction->checkIfRemplacant($lieu->getHoraire(), $date);
  2754.             }
  2755.         } else {
  2756.             if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  2757.                 return new Response(json_encode(([
  2758.                     'message' => 'Error, no horaire found for this audio',
  2759.                     'path' => 'src/Controller/RdvController.php',
  2760.                     "status" => 400,
  2761.                 ])), 400);
  2762.             }
  2763.             /*  if (!$publicFunction->calculScheduleFitDate($audio, \DateTime::createFromFormat("d/m/Y H:i", $data["date"]), $audioMotif->getDuration(), $centre))
  2764.                 return new Response(json_encode(([
  2765.                     'message' => "Error, no timestamp found at this time. Motif size: {$audioMotif->getDuration()} Line n°" . __LINE__,
  2766.                     'path' => 'src/Controller/RdvController.php',
  2767.                     "status" => 400,
  2768.                 ])), 400);*/
  2769.             $remplacant_id $publicFunction->checkIfRemplacant($liaison->getHoraire(), \DateTime::createFromFormat("d/m/Y H:i"$data["date"]));
  2770.         }
  2771.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  2772.         $existingRdv $this->getDoctrine()
  2773.             ->getRepository(Rdv::class)
  2774.             ->findOneBy([
  2775.                 'date' => $date,
  2776.                 'id_audio' => $audio,
  2777.                 'id_centre' => $rdv->getIdCentre() ?? null,
  2778.                 'id_lieu' => $rdv->getIdLieu()   ?? null,
  2779.             ]);
  2780.         if ($existingRdv) {
  2781.             return new Response(json_encode([
  2782.                 'message' => 'Un rendez-vous est déjà pris pour cette date et ce créneau.',
  2783.                 'status' => 400,
  2784.             ]), 400);
  2785.         }
  2786.         $rdv->setDate($date);
  2787.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  2788.         /** @var EtatRdv */
  2789.         $etat $this->getDoctrine()
  2790.             ->getRepository(EtatRdv::class)
  2791.             ->findOneBy(['id' => $data["etat_id"]]);
  2792.         if ($etat == null) {
  2793.             return new Response(json_encode(([
  2794.                 'message' => 'Error, no etat found at this id',
  2795.                 'path' => 'src/Controller/RdvController.php',
  2796.                 "status" => 400,
  2797.             ])), 400);
  2798.         }
  2799.         $rdv->setIdEtat($etat);
  2800.         $rdv->setIdMotif($motif);
  2801.         $rdv->setIsAbsence(0);
  2802.         $rdv->setCacher(0);
  2803.         if ($remplacant_id != -1) {
  2804.             $remplacant $this->getDoctrine()
  2805.                 ->getRepository(Remplacant::class)
  2806.                 ->find($remplacant_id);
  2807.             $rdv->setRemplacant($remplacant);
  2808.         }
  2809.         $entityManager $this->getDoctrine()->getManager();
  2810.         $entityManager->persist($rdv);
  2811.         $entityManager->flush();
  2812.         /// SMSEMAIL A décommenter pour autoriser l'envoi de sms / email à la création de rdv par l'audio / le client SMSEMAIL ///
  2813.         $date $rdv->getDate();
  2814.         $smsDate $date->format('d-m-Y H:i');
  2815.         $locale 'fr_FR';
  2816.         $formatter = new IntlDateFormatter(
  2817.             $locale,
  2818.             IntlDateFormatter::FULL,
  2819.             IntlDateFormatter::SHORT,
  2820.             null,
  2821.             IntlDateFormatter::GREGORIAN,
  2822.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  2823.         );
  2824.         $smsDateLongFormat $formatter->format($date);
  2825.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  2826.         $client->setIdCentre($rdv->getIdCentre());
  2827.         $client->setIdAudio($rdv->getIdAudio());
  2828.         $entityManager->persist($client);
  2829.         $entityManager->flush();
  2830.         // client notif mail Sms
  2831.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  2832.         $frenchDate ucfirst($frenchDate);
  2833.         $responses = [
  2834.             'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
  2835.             'situations' => (isset($data['situations']) && !empty($data['situations'])) ? implode(", "$data['situations']) : null,
  2836.             'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
  2837.             'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
  2838.             'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
  2839.             'ordonance' => isset($data['ordonnance']) ? $data['ordonnance'] : null,
  2840.             'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
  2841.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  2842.         ];
  2843.         $paramsSourceLead = [
  2844.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  2845.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  2846.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  2847.         ];
  2848.         $params = array(
  2849.             "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  2850.             "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  2851.             "date" => $smsDateLongFormat,
  2852.             "RdvDate" => $smsDateLongFormat,
  2853.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  2854.             "centerName" => $rdv->getIdCentre()->getName(),
  2855.             "prenom" => $client->getName(),
  2856.             "centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  2857.             "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  2858.             'motif' => $rdv->getIdMotif()->getTitre(),
  2859.             "centerCity" => $rdv->getIdCentre()->getCity(),
  2860.             "audioName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  2861.             'titre' => "Votre rendez-vous est validé le " substr($smsDate010) . " à "  substr($smsDate1115),
  2862.             "position" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  2863.             "address" => $rdv->getIdCentre()->getAddress(),
  2864.             "postal" => $rdv->getIdCentre()->getPostale(),
  2865.             "city" => $rdv->getIdCentre()->getCity(),
  2866.             "clientEmail" => $client->getMail(),
  2867.             "clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
  2868.             "clientAddress" => $client->getAddress(),
  2869.             "clientPostal" => $client->getPostal(),
  2870.             "clientCity" => $client->getCity(),
  2871.             "audioName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  2872.             "frenchDate" => $frenchDate,
  2873.             "heure" => substr($smsDate1115),
  2874.             "centerName" => $rdv->getIdCentre()->getName(),
  2875.             "audioMail" => $rdv->getIdAudio()->getMail(),
  2876.             "modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
  2877.         );
  2878.         $paramsPatient $params;
  2879.         $isNew false;
  2880.         if (isset($data["isLead"]) && isset($data["passwordGenerated"]) != null) {
  2881.             $subject "✅Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  2882.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject189);
  2883.             $isNew true;
  2884.         } else {
  2885.             $subject "Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  2886.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject181);
  2887.         }
  2888.         $sms "Votre RDV est validé le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'imprévu contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  2889.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  2890.         // audio Notif mail SMS
  2891.         $birthday $rdv->getIdClient()->getBirthdate();
  2892.         $params = array(
  2893.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  2894.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  2895.             "date" => substr($smsDate010),
  2896.             "heure" => substr($smsDate1115),
  2897.             "mail" => $client->getMail(),
  2898.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  2899.             'telClient' => $client->getPhone(),
  2900.             'phone' => $client->getPhone(),
  2901.             'clientCivilite' => $client->getCivilite(),
  2902.             'clientNom' => $client->getLastname(),
  2903.             'clientPrenom' => $client->getName(),
  2904.             'clientPostal' => $client->getPostal(),
  2905.             'clientMail' => $client->getMail(),
  2906.             'clientPhone' => $client->getPhone(),
  2907.             'motif' => $rdv->getIdMotif()->getTitre(),
  2908.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  2909.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  2910.             'centerName' => $rdv->getIdCentre()->getName(),
  2911.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  2912.             'centerCity' => $rdv->getIdCentre()->getCity(),
  2913.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  2914.             'idPatient' => $client->getId(),
  2915.             'proUrl' => "{$_ENV['BASE_logiciel']}",
  2916.             'frenchDate' => $frenchDate,
  2917.             'responses' => $responses,
  2918.         );
  2919.         $templateEmail 182;
  2920.         if (!empty($data['canMove'])) {
  2921.             $templateEmail 197;
  2922.         }
  2923.         $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  2924.         $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  2925.         if ($rdv->getIdAudio()->getConfirmRdvMail()) {
  2926.             $subject "✅Nouveau Rendez-vous My Audio le " $frenchDate " à " substr($smsDate1115);
  2927.             $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject$templateEmail);
  2928.         }
  2929.         if ($rdv->getIdAudio()->getConfirmRdvSms()) {
  2930.             $sms "Vous avez un nouveau RDV le " substr($smsDate010) . " à " substr($smsDate1115) . ", en cas d'aléas contactez votre patient " $client->getPhone() . " pour modifier votre consultation.\nNe pas répondre.";
  2931.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  2932.         }
  2933.         // send notif to admin
  2934.         $paramsAdmin = array(
  2935.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  2936.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  2937.             "RdvDate" => substr($smsDate010),
  2938.             "heure" => substr($smsDate1115),
  2939.             "clientMail" => $client->getMail(),
  2940.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  2941.             'telClient' => $client->getPhone(),
  2942.             'clientNom' => $client->getLastname(),
  2943.             'clientPrenom' => $client->getName(),
  2944.             'clientCivilite' => $client->getCivilite(),
  2945.             'clientPostal' => $client->getPostal(),
  2946.             'clientPhone' => $client->getPhone(),
  2947.             'motif' => $rdv->getIdMotif()->getTitre(),
  2948.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  2949.             'centerName' => $rdv->getIdCentre()->getName(),
  2950.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  2951.             'centerCity' => $rdv->getIdCentre()->getCity(),
  2952.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  2953.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  2954.             'date' => substr($smsDate010),
  2955.             'urlApi' => "{$_ENV['BASE_API']}",
  2956.             'clientId' => $client->getId(),
  2957.             'centerId' => $rdv->getIdCentre()->getId(),
  2958.             'frenchDate' => $frenchDate,
  2959.             'responses' => $responses,
  2960.             'paramsSourceLead' => $paramsSourceLead
  2961.         );
  2962.         $subject "Nouveau RDV MA | RR - " $rdv->getIdCentre()->getName();
  2963.         $templateEmail 183;
  2964.         if (!empty($data['canMove'])) {
  2965.             $templateEmail 190;
  2966.         }
  2967.         if (!isset($data["isLead"])) {
  2968.             $publicFunction->sendEmail($paramsAdmin"lead.myaudio@gmail.com""my audio"$subject$templateEmail);
  2969.         }
  2970.         //$publicFunction->sendEmail($paramsAdmin,"testpation1254@myaudio.fr","my audio", 'Nouveau RDV à My Audio Pro', $templateEmail);
  2971.         $publicFunction->sendEmail($paramsAdmin"contact@myaudio.fr""my audio"$subject$templateEmail);
  2972.         $publicFunction->sendEmail($paramsAdmin"lead.myaudio@gmail.com""my audio"$subject$templateEmail);
  2973.         // google calendar post
  2974.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  2975.             ->findBy(array('audio' => $audio->getId()));
  2976.         $data['rdv'] = $rdv->getId();
  2977.         if (isset($data['clientRdvLp']) && !empty($data['clientRdvLp'])) {
  2978.             $rdvLead $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
  2979.             if ($rdvLead) {
  2980.                 $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
  2981.                 if ($leadStatus) {
  2982.                     $rdvLead->setLeadStatus($leadStatus);
  2983.                     $rdvLead->setRdv($rdv);
  2984.                     $this->entityManager->flush();
  2985.                 }
  2986.             }
  2987.         }
  2988.         foreach ($synchronisations as $synchronisation) {
  2989.             if (!$synchronisation->getIsDeleted()) {
  2990.                 $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  2991.                 $googleCalendar->createEvent($synchronisation$data);
  2992.             }
  2993.         }
  2994.         if (isset($data["isMyaudio"]) || isset($data["isRdvLead"]) || isset($data["isRdvRapide"])) {
  2995.             try {
  2996.                 $Callservice->handleCallCenterAfterRdv(
  2997.                     $rdv
  2998.                 );
  2999.                 $rdv->setIsNotificationRdvCallSent(1);
  3000.                 $this->entityManager->flush();
  3001.             } catch (\Exception $e) {
  3002.                 $this->logger->error("Erreur lors de l'appel de notification pour le RDV #{$rdv->getId()}: " $e->getMessage());
  3003.             }
  3004.         }
  3005.         // After successfully creating the RDV
  3006.         $this->mercure->publishRdvUpdate($rdv'created');
  3007.          // Find the audio/user who owns the referral code
  3008.     $referrer $client// the user who shared the code
  3009.     // Make sure key exists
  3010.     $codeParrain $data['codeParrain'] ?? null;  // null if not provided
  3011.     if ($codeParrain) {
  3012.       // Find the new user/referee who is using the code 
  3013.       $referee $entityManager->getRepository(Client::class)->findOneBy([
  3014.           'referralCode' => $codeParrain
  3015.       ]);
  3016.     if ($referee) {
  3017.         $referral = new Referral();
  3018.         $referral->setReferrerType('patient'); 
  3019.         $referral->setReferrerId($referrer->getId()); 
  3020.         $referral->setRefereeType('patient'); 
  3021.         $referral->setRefereeId($referee->getId()); 
  3022.         $referral->setCodeUsed($codeParrain); 
  3023.         $referral->setStatus('completed');
  3024.         $referral->setRewardAmount(100); 
  3025.         $referral->setCreatedAt(new \DateTime());
  3026.         $entityManager->persist($referral);
  3027.         $entityManager->flush();
  3028.     }
  3029.     }
  3030.         return new Response(json_encode(([
  3031.             "id" => $rdv->getId(),
  3032.             "motif_id" => $rdv->getIdMotif()->getId(),
  3033.             "audio_id" => $rdv->getIdAudio()->getId(),
  3034.             "remplacant_id" => $remplacant_id == -null $remplacant_id,
  3035.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  3036.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  3037.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  3038.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  3039.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  3040.             "testclient" => $rdv->getTestClient() ? [
  3041.                 "result" => $rdv->getTestClient()->getResultTonal(),
  3042.                 "date" => $rdv->getTestClient()->getDate(),
  3043.                 "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  3044.             ] : null,
  3045.             "duration" => $audioMotif->getDuration(),
  3046.             "consigne" => $audioMotif->getConsigne(),
  3047.             "etat_id" => $rdv->getIdEtat()->getId(),
  3048.             "date" => $rdv->getDate(),
  3049.             "comment" => $rdv->getComment(),
  3050.             "centerName" => $rdv->getIdCentre()->getName(),
  3051.             "review" => $rdv->getReview(),
  3052.             "note" => $rdv->getNote(),
  3053.             "status" => 200,
  3054.             "paramsPatient" => $paramsPatient,
  3055.             "isNew" => $isNew,
  3056.         ])));
  3057.     }
  3058.     /**
  3059.      * @Route("/rdv/v2", name="postRdvV2", methods={"POST"})
  3060.      *
  3061.      * Version optimisée de la prise de rendez-vous pour les clients via le site
  3062.      * Gestion complète: validation, création RDV, notifications email/SMS
  3063.      */
  3064.     public function postRdvV2(
  3065.         Request $request,
  3066.         PublicFunction $publicFunction,
  3067.         GoogleCalendarService $googleCalendar,
  3068.         AppointmentCallService $callService
  3069.     ): JsonResponse {
  3070.         try {
  3071.             $data json_decode($request->getContent(), true);
  3072.             // Validation du token et récupération du client
  3073.             $validationResult $this->validateTokenAndGetClient($data);
  3074.             if ($validationResult instanceof Response) {
  3075.                 return new JsonResponse(json_decode($validationResult->getContent(), true), $validationResult->getStatusCode());
  3076.             }
  3077.             ['client' => $client'token' => $token] = $validationResult;
  3078.             // Récupération et validation de l'audio
  3079.             $audio $this->entityManager->getRepository(Audio::class)->find($data['audio_id'] ?? null);
  3080.             if (!$audio) {
  3081.                 return new JsonResponse([
  3082.                     'message' => "Aucun audioprothésiste trouvé avec cet ID.",
  3083.                     'status' => 404
  3084.                 ], 404);
  3085.             }
  3086.             // Vérification du blocage client
  3087.             $clientBlocked $this->entityManager->getRepository(ClientBlocked::class)
  3088.                 ->findOneBy(['id_audio' => $audio'id_client' => $client]);
  3089.             if ($clientBlocked) {
  3090.                 return new JsonResponse([
  3091.                     'message' => 'Vous avez été bloqué par cet audioprothésiste.',
  3092.                     'status' => 403
  3093.                 ], 403);
  3094.             }
  3095.             // Validation du centre/lieu
  3096.             $locationResult $this->validateLocation($data$audio);
  3097.             if ($locationResult instanceof Response) {
  3098.                 return new JsonResponse(json_decode($locationResult->getContent(), true), $locationResult->getStatusCode());
  3099.             }
  3100.             ['centre' => $centre'lieu' => $lieu'liaison' => $liaison] = $locationResult;
  3101.             // Validation du motif
  3102.             $motifResult $this->validateMotif($data$audio);
  3103.             if ($motifResult instanceof Response) {
  3104.                 return new JsonResponse(json_decode($motifResult->getContent(), true), $motifResult->getStatusCode());
  3105.             }
  3106.             ['motif' => $motif'audioMotif' => $audioMotif] = $motifResult;
  3107.             // Validation de la disponibilité
  3108.             $date \DateTime::createFromFormat("d/m/Y H:i"$data['date']);
  3109.             if (!$date) {
  3110.                 return new JsonResponse([
  3111.                     'message' => 'Format de date invalide. Utilisez le format: d/m/Y H:i',
  3112.                     'status' => 400
  3113.                 ], 400);
  3114.             }
  3115.             $availabilityResult $this->validateAvailability(
  3116.                 $audio,
  3117.                 $date,
  3118.                 $audioMotif->getDuration(),
  3119.                 $centre,
  3120.                 $lieu,
  3121.                 $liaison,
  3122.                 $publicFunction
  3123.             );
  3124.             if ($availabilityResult instanceof Response) {
  3125.                 return new JsonResponse(json_decode($availabilityResult->getContent(), true), $availabilityResult->getStatusCode());
  3126.             }
  3127.             $remplacant_id $availabilityResult;
  3128.             // Création du rendez-vous
  3129.             $rdv $this->createAppointment($data$client$audio$centre$lieu$motif$audioMotif$date$remplacant_id);
  3130.             // Envoi des notifications
  3131.             $this->sendNotifications($rdv$client$audio$publicFunction$data);
  3132.             // Synchronisation Google Calendar
  3133.             $this->syncGoogleCalendar($audio$rdv$googleCalendar$data);
  3134.             // Notification call center si nécessaire
  3135.             if (isset($data['isMyaudio']) || isset($data['isRdvLead']) || isset($data['isRdvRapide'])) {
  3136.                 try {
  3137.                     $callService->handleCallCenterAfterRdv($rdv);
  3138.                     $rdv->setIsNotificationRdvCallSent(1);
  3139.                     $this->entityManager->flush();
  3140.                 } catch (\Exception $e) {
  3141.                     $this->logger->error("Erreur notification call center RDV #{$rdv->getId()}: " $e->getMessage());
  3142.                 }
  3143.             }
  3144.             // Réponse finale
  3145.             return new JsonResponse([
  3146.                 'success' => true,
  3147.                 'message' => 'Rendez-vous créé avec succès',
  3148.                 'rdv' => [
  3149.                     'id' => $rdv->getId(),
  3150.                     'date' => $rdv->getDate()->format('d/m/Y H:i'),
  3151.                     'motif' => $motif->getTitre(),
  3152.                     'duration' => $audioMotif->getDuration(),
  3153.                     'centre' => $centre $centre->getName() : null,
  3154.                     'lieu' => $lieu $lieu->getName() : null,
  3155.                     'audio' => $audio->getName() . ' ' $audio->getLastName(),
  3156.                 ],
  3157.                 'status' => 201
  3158.             ], 201);
  3159.         } catch (\Exception $e) {
  3160.             $this->logger->error("Erreur lors de la création du RDV: " $e->getMessage());
  3161.             return new JsonResponse([
  3162.                 'success' => false,
  3163.                 'message' => 'Une erreur est survenue lors de la création du rendez-vous.',
  3164.                 'error' => $e->getMessage(),
  3165.                 'status' => 500
  3166.             ], 500);
  3167.         }
  3168.     }
  3169.     /**
  3170.      * Valide le token et récupère le client associé
  3171.      */
  3172.     private function validateTokenAndGetClient(array $data)
  3173.     {
  3174.         if (!isset($data['token'])) {
  3175.             return new Response(json_encode([
  3176.                 'message' => "Aucun token n'a été spécifié",
  3177.                 'status' => 401
  3178.             ]), 401);
  3179.         }
  3180.         $token $this->entityManager->getRepository(Token::class)
  3181.             ->findOneBy(['token' => $data['token']]);
  3182.         if (!$token) {
  3183.             return new Response(json_encode([
  3184.                 'message' => "Token invalide. Veuillez vous reconnecter.",
  3185.                 'status' => 404
  3186.             ]), 404);
  3187.         }
  3188.         // Vérification de l'âge du token
  3189.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  3190.         if ($dateDiff->7) {
  3191.             $this->entityManager->remove($token);
  3192.             $this->entityManager->flush();
  3193.             return new Response(json_encode([
  3194.                 'message' => 'Token expiré. Veuillez vous reconnecter.',
  3195.                 'status' => 401
  3196.             ]), 401);
  3197.         }
  3198.         // Récupération du client
  3199.         $client $token->getIdClient();
  3200.         if (!$client) {
  3201.             return new Response(json_encode([
  3202.                 'message' => "Ce token n'est pas associé à un client.",
  3203.                 'status' => 400
  3204.             ]), 400);
  3205.         }
  3206.         return ['client' => $client'token' => $token];
  3207.     }
  3208.     /**
  3209.      * Valide le centre ou lieu du rendez-vous
  3210.      */
  3211.     private function validateLocation(array $dataAudio $audio)
  3212.     {
  3213.         $centre null;
  3214.         $lieu null;
  3215.         $liaison null;
  3216.         if (isset($data['centre_id'])) {
  3217.             $centre $this->entityManager->getRepository(Centre::class)->find($data['centre_id']);
  3218.             if (!$centre) {
  3219.                 return new Response(json_encode([
  3220.                     'message' => 'Aucun centre trouvé avec cet ID',
  3221.                     'status' => 404
  3222.                 ]), 404);
  3223.             }
  3224.             $liaison $this->entityManager->getRepository(AudioCentre::class)
  3225.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  3226.             if (!$liaison) {
  3227.                 return new Response(json_encode([
  3228.                     'message' => "L'audioprothésiste n'est pas rattaché à ce centre",
  3229.                     'status' => 400
  3230.                 ]), 400);
  3231.             }
  3232.         } elseif (isset($data['lieu_id']) && $audio->getIsIndie()) {
  3233.             $lieu $this->entityManager->getRepository(Lieu::class)
  3234.                 ->findOneBy(['id' => $data['lieu_id'], 'id_gerant' => $audio->getId()]);
  3235.             if (!$lieu) {
  3236.                 return new Response(json_encode([
  3237.                     'message' => 'Aucun lieu trouvé avec cet ID',
  3238.                     'status' => 404
  3239.                 ]), 404);
  3240.             }
  3241.         } else {
  3242.             return new Response(json_encode([
  3243.                 'message' => 'Veuillez spécifier un centre ou un lieu',
  3244.                 'status' => 400
  3245.             ]), 400);
  3246.         }
  3247.         return ['centre' => $centre'lieu' => $lieu'liaison' => $liaison];
  3248.     }
  3249.     /**
  3250.      * Valide le motif du rendez-vous
  3251.      */
  3252.     private function validateMotif(array $dataAudio $audio)
  3253.     {
  3254.         if (!isset($data['motif_id'])) {
  3255.             return new Response(json_encode([
  3256.                 'message' => 'Aucun motif spécifié',
  3257.                 'status' => 400
  3258.             ]), 400);
  3259.         }
  3260.         $motif $this->entityManager->getRepository(Motif::class)->find($data['motif_id']);
  3261.         if (!$motif) {
  3262.             return new Response(json_encode([
  3263.                 'message' => 'Aucun motif trouvé avec cet ID',
  3264.                 'status' => 404
  3265.             ]), 404);
  3266.         }
  3267.         $audioMotif $this->entityManager->getRepository(AudioMotif::class)
  3268.             ->findOneBy(['id_audio' => $audio->getId(), 'id_motif' => $data['motif_id']]);
  3269.         if (!$audioMotif) {
  3270.             return new Response(json_encode([
  3271.                 'message' => "Ce motif n'est pas disponible pour cet audioprothésiste",
  3272.                 'status' => 400
  3273.             ]), 400);
  3274.         }
  3275.         return ['motif' => $motif'audioMotif' => $audioMotif];
  3276.     }
  3277.     /**
  3278.      * Valide la disponibilité du créneau
  3279.      */
  3280.     private function validateAvailability(
  3281.         Audio $audio,
  3282.         \DateTime $date,
  3283.         int $duration,
  3284.         ?Centre $centre,
  3285.         ?Lieu $lieu,
  3286.         ?AudioCentre $liaison,
  3287.         PublicFunction $publicFunction
  3288.     ) {
  3289.         // Vérification qu'il n'y a pas déjà un RDV à cette date
  3290.         $existingRdv $this->entityManager->getRepository(Rdv::class)
  3291.             ->findOneBy([
  3292.                 'date' => $date,
  3293.                 'id_audio' => $audio,
  3294.                 'id_centre' => $centre,
  3295.                 'id_lieu' => $lieu,
  3296.             ]);
  3297.         if ($existingRdv) {
  3298.             return new Response(json_encode([
  3299.                 'message' => 'Un rendez-vous existe déjà à ce créneau',
  3300.                 'status' => 409
  3301.             ]), 409);
  3302.         }
  3303.         // Vérification de la disponibilité selon le type d'audio
  3304.         if ($audio->getIsIndie()) {
  3305.             if ($centre && $liaison) {
  3306.                 if (!$liaison->getHoraire() || $liaison->getHoraire() == []) {
  3307.                     return new Response(json_encode([
  3308.                         'message' => 'Aucun horaire configuré pour cet audioprothésiste',
  3309.                         'status' => 400
  3310.                     ]), 400);
  3311.                 }
  3312.                 if (!$publicFunction->calculScheduleFitDate($audio$date$duration$centre)) {
  3313.                     return new Response(json_encode([
  3314.                         'message' => 'Créneau non disponible',
  3315.                         'status' => 400
  3316.                     ]), 400);
  3317.                 }
  3318.                 return $publicFunction->checkIfRemplacant($liaison->getHoraire(), $date);
  3319.             } else {
  3320.                 if (!$lieu->getHoraire() || $lieu->getHoraire() == []) {
  3321.                     return new Response(json_encode([
  3322.                         'message' => 'Aucun horaire configuré pour ce lieu',
  3323.                         'status' => 400
  3324.                     ]), 400);
  3325.                 }
  3326.                 if (!$publicFunction->calculScheduleFitDate($audio$date$durationnull$lieu)) {
  3327.                     return new Response(json_encode([
  3328.                         'message' => 'Créneau non disponible',
  3329.                         'status' => 400
  3330.                     ]), 400);
  3331.                 }
  3332.                 return $publicFunction->checkIfRemplacant($lieu->getHoraire(), $date);
  3333.             }
  3334.         } else {
  3335.             if (!$liaison || !$liaison->getHoraire() || $liaison->getHoraire() == []) {
  3336.                 return new Response(json_encode([
  3337.                     'message' => 'Aucun horaire configuré',
  3338.                     'status' => 400
  3339.                 ]), 400);
  3340.             }
  3341.             return $publicFunction->checkIfRemplacant($liaison->getHoraire(), $date);
  3342.         }
  3343.     }
  3344.     /**
  3345.      * Crée le rendez-vous en base de données
  3346.      */
  3347.     private function createAppointment(
  3348.         array $data,
  3349.         Client $client,
  3350.         Audio $audio,
  3351.         ?Centre $centre,
  3352.         ?Lieu $lieu,
  3353.         Motif $motif,
  3354.         AudioMotif $audioMotif,
  3355.         \DateTime $date,
  3356.         int $remplacant_id
  3357.     ): Rdv {
  3358.         $rdv = new Rdv();
  3359.         $rdv->setIdClient($client);
  3360.         $rdv->setIdAudio($audio);
  3361.         $rdv->setIdCentre($centre);
  3362.         $rdv->setIdLieu($lieu);
  3363.         $rdv->setIdMotif($motif);
  3364.         $rdv->setDate($date);
  3365.         $rdv->setDateCreation(new \DateTime());
  3366.         // Toujours mettre isMyaudio à true pour les RDV clients via le site
  3367.         $rdv->setIsMyaudio(true);
  3368.         $rdv->setIsRdvLp(isset($data['isRdvLead']));
  3369.         $rdv->setIsRdvRapide(isset($data['isRdvRapide']));
  3370.         $rdv->setIsAbsence(0);
  3371.         $rdv->setCacher(0);
  3372.         // Récupération du dernier test client si disponible
  3373.         $testClient $this->entityManager->getRepository(TestClient::class)
  3374.             ->getLatestTestClient($client);
  3375.         if ($testClient && !$testClient->getRdv()) {
  3376.             $rdv->setTestClient($testClient);
  3377.         }
  3378.         // Gestion proche si spécifié
  3379.         if (isset($data['proche_id'])) {
  3380.             $proche $this->entityManager->getRepository(Proches::class)
  3381.                 ->findOneBy(['id' => $data['proche_id'], 'id_client' => $client]);
  3382.             if ($proche) {
  3383.                 $rdv->setIdProche($proche);
  3384.             }
  3385.         }
  3386.         // Durée : utilise celle du motif par défaut ou celle fournie dans les données
  3387.         $rdv->setDuration($data['duree'] ?? $audioMotif->getDuration());
  3388.         // Couleur personnalisée
  3389.         if (isset($data['color'])) {
  3390.             $rdv->setColor($data['color']);
  3391.         }
  3392.         // Note
  3393.         if (isset($data['note'])) {
  3394.             $rdv->setNote($data['note']);
  3395.         }
  3396.         // État du rendez-vous
  3397.         $etat $this->entityManager->getRepository(EtatRdv::class)
  3398.             ->find($data['etat_id'] ?? 1); // État par défaut : 1
  3399.         if ($etat) {
  3400.             $rdv->setIdEtat($etat);
  3401.         }
  3402.         // Remplaçant si applicable
  3403.         if ($remplacant_id != -1) {
  3404.             $remplacant $this->entityManager->getRepository(Remplacant::class)->find($remplacant_id);
  3405.             if ($remplacant) {
  3406.                 $rdv->setRemplacant($remplacant);
  3407.             }
  3408.         }
  3409.         // Gestion lead
  3410.         if (isset($data['lead'])) {
  3411.             $lead $this->entityManager->getRepository(LeadRdv::class)->find($data['lead']);
  3412.             if ($lead) {
  3413.                 $lead->setRdv($rdv);
  3414.                 $leadStatus $this->entityManager->getRepository(LeadStatus::class)
  3415.                     ->findOneBy(['slug' => 'rdv_valider']);
  3416.                 if ($leadStatus) {
  3417.                     $lead->setLeadStatus($leadStatus);
  3418.                 }
  3419.             }
  3420.         }
  3421.         // Mise à jour du client avec centre et audio
  3422.         $client->setIdCentre($centre);
  3423.         $client->setIdAudio($audio);
  3424.         $this->entityManager->persist($client);
  3425.         $this->entityManager->persist($rdv);
  3426.         $this->entityManager->flush();
  3427.         return $rdv;
  3428.     }
  3429.     /**
  3430.      * Envoie toutes les notifications (email + SMS) au client, audio et admin
  3431.      */
  3432.     private function sendNotifications(Rdv $rdvClient $clientAudio $audioPublicFunction $publicFunction, array $data): void
  3433.     {
  3434.         $date $rdv->getDate();
  3435.         $smsDate $date->format('d-m-Y H:i');
  3436.         $formatter = new IntlDateFormatter(
  3437.             'fr_FR',
  3438.             IntlDateFormatter::FULL,
  3439.             IntlDateFormatter::SHORT,
  3440.             null,
  3441.             IntlDateFormatter::GREGORIAN,
  3442.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  3443.         );
  3444.         $smsDateLongFormat $formatter->format($date);
  3445.         $frenchDate ucfirst(preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat));
  3446.         // === Notification CLIENT ===
  3447.         $this->sendClientNotification($rdv$client$smsDate$smsDateLongFormat$frenchDate$publicFunction$data);
  3448.         // === Notification AUDIO ===
  3449.         if ($audio->getConfirmRdvMail() || $audio->getConfirmRdvSms()) {
  3450.             $this->sendAudioNotification($rdv$client$audio$smsDate$frenchDate$publicFunction$data);
  3451.         }
  3452.         // === Notification ADMIN ===
  3453.         $this->sendAdminNotification($rdv$client$smsDate$frenchDate$publicFunction$data);
  3454.     }
  3455.     /**
  3456.      * Envoie les notifications au client (email + SMS)
  3457.      */
  3458.     private function sendClientNotification(
  3459.         Rdv $rdv,
  3460.         Client $client,
  3461.         string $smsDate,
  3462.         string $smsDateLongFormat,
  3463.         string $frenchDate,
  3464.         PublicFunction $publicFunction,
  3465.         array $data
  3466.     ): void {
  3467.         $centre $rdv->getIdCentre();
  3468.         $params = [
  3469.             'lienModifer' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  3470.             'lienAnnule' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  3471.             'date' => $smsDateLongFormat,
  3472.             'RdvDate' => $smsDateLongFormat,
  3473.             'telCentre' => $centre->getPhone(),
  3474.             'centerName' => $centre->getName(),
  3475.             'prenom' => $client->getName(),
  3476.             'centerAddress' => $centre->getAddress() . ' ' $centre->getPostale() . ' ' $centre->getCity(),
  3477.             'centerPostalCode' => $centre->getPostale(),
  3478.             'motif' => $rdv->getIdMotif()->getTitre(),
  3479.             'centerCity' => $centre->getCity(),
  3480.             'audioName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3481.             'titre' => 'Votre rendez-vous est validé le ' substr($smsDate010) . ' à ' substr($smsDate1115),
  3482.             'frenchDate' => $frenchDate,
  3483.             'heure' => substr($smsDate1115),
  3484.             'clientEmail' => $client->getMail(),
  3485.             'clientPassword' => $data['passwordGenerated'] ?? null,
  3486.             'modifUrl' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  3487.         ];
  3488.         // Email client
  3489.         $templateId = (isset($data['isLead']) && isset($data['passwordGenerated'])) ? 189 181;
  3490.         $subject '✅ Rendez-vous My Audio confirmé le ' $smsDateLongFormat;
  3491.         $publicFunction->sendEmail(
  3492.             $params,
  3493.             $client->getMail(),
  3494.             $client->getName() . ' ' $client->getLastName(),
  3495.             $subject,
  3496.             $templateId
  3497.         );
  3498.         // SMS client
  3499.         $smsMessage "Votre RDV est validé le " substr($smsDate010) . " à " substr($smsDate1115) .
  3500.                       ", en cas d'imprévu contactez votre centre " $centre->getPhone() .
  3501.                       " pour modifier votre consultation.\nNe pas répondre.";
  3502.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$smsMessage$client->getPhone());
  3503.     }
  3504.     /**
  3505.      * Envoie les notifications à l'audioprothésiste (email + SMS)
  3506.      */
  3507.     private function sendAudioNotification(
  3508.         Rdv $rdv,
  3509.         Client $client,
  3510.         Audio $audio,
  3511.         string $smsDate,
  3512.         string $frenchDate,
  3513.         PublicFunction $publicFunction,
  3514.         array $data
  3515.     ): void {
  3516.         $responses = [
  3517.             'rangeAge' => $data['rangeAge'] ?? null,
  3518.             'situations' => (isset($data['situations']) && !empty($data['situations'])) ? implode(", "$data['situations']) : null,
  3519.             'equipeAppareil' => $data['equipe'] ?? null,
  3520.             'durationEquipe' => $data['durationEquipe'] ?? null,
  3521.             'bilanAuditif' => $data['bilanAuditif'] ?? null,
  3522.             'ordonance' => $data['ordonnance'] ?? null,
  3523.             'dateOrdonance' => $data['dateOrdonance'] ?? null,
  3524.             'canMove' => $data['canMove'] ?? null,
  3525.         ];
  3526.         $params = [
  3527.             'lienModifer' => $_ENV['BASE_logiciel'] . 'rdv',
  3528.             'lienAnnule' => $_ENV['BASE_logiciel'] . 'rdv',
  3529.             'date' => substr($smsDate010),
  3530.             'heure' => substr($smsDate1115),
  3531.             'audioproName' => $audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastName(),
  3532.             'phone' => $client->getPhone(),
  3533.             'clientCivilite' => $client->getCivilite(),
  3534.             'clientNom' => $client->getLastname(),
  3535.             'clientPrenom' => $client->getName(),
  3536.             'clientPostal' => $client->getPostal(),
  3537.             'clientMail' => $client->getMail(),
  3538.             'clientPhone' => $client->getPhone(),
  3539.             'motif' => $rdv->getIdMotif()->getTitre(),
  3540.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  3541.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  3542.             'centerName' => $rdv->getIdCentre()->getName(),
  3543.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  3544.             'centerCity' => $rdv->getIdCentre()->getCity(),
  3545.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  3546.             'idPatient' => $client->getId(),
  3547.             'proUrl' => $_ENV['BASE_logiciel'],
  3548.             'frenchDate' => $frenchDate,
  3549.             'responses' => $responses,
  3550.         ];
  3551.         $templateEmail = !empty($data['canMove']) ? 197 182;
  3552.         $mailAudio $audio->getMailNotif() ?? $audio->getMail();
  3553.         $phoneAudio $audio->getPhoneNotif() ?? $audio->getPhone();
  3554.         // Email audio
  3555.         if ($audio->getConfirmRdvMail()) {
  3556.             $subject '✅ Nouveau Rendez-vous My Audio le ' $frenchDate ' à ' substr($smsDate1115);
  3557.             $publicFunction->sendEmail($params$mailAudio$audio->getName() . ' ' $audio->getLastName(), $subject$templateEmail);
  3558.         }
  3559.         // SMS audio
  3560.         if ($audio->getConfirmRdvSms()) {
  3561.             $smsMessage "Vous avez un nouveau RDV le " substr($smsDate010) . " à " substr($smsDate1115) .
  3562.                           ", en cas d'aléas contactez votre patient " $client->getPhone() .
  3563.                           " pour modifier votre consultation.\nNe pas répondre.";
  3564.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$smsMessage$phoneAudio);
  3565.         }
  3566.     }
  3567.     /**
  3568.      * Envoie les notifications à l'admin
  3569.      */
  3570.     private function sendAdminNotification(
  3571.         Rdv $rdv,
  3572.         Client $client,
  3573.         string $smsDate,
  3574.         string $frenchDate,
  3575.         PublicFunction $publicFunction,
  3576.         array $data
  3577.     ): void {
  3578.         $responses = [
  3579.             'rangeAge' => $data['rangeAge'] ?? null,
  3580.             'situations' => (isset($data['situations']) && !empty($data['situations'])) ? implode(", "$data['situations']) : null,
  3581.             'equipeAppareil' => $data['equipe'] ?? null,
  3582.             'durationEquipe' => $data['durationEquipe'] ?? null,
  3583.             'bilanAuditif' => $data['bilanAuditif'] ?? null,
  3584.             'ordonance' => $data['ordonnance'] ?? null,
  3585.             'dateOrdonance' => $data['dateOrdonance'] ?? null,
  3586.             'canMove' => $data['canMove'] ?? null,
  3587.         ];
  3588.         $paramsSourceLead = [
  3589.             'trafficSource' => $data['traffic_source'] ?? null,
  3590.             'articleName' => $data['article_name'] ?? null,
  3591.             'lpVersion' => $data['lp_version'] ?? null,
  3592.         ];
  3593.         $paramsAdmin = [
  3594.             'lienModifer' => $_ENV['BASE_logiciel'] . 'rdv',
  3595.             'lienAnnule' => $_ENV['BASE_logiciel'] . 'rdv',
  3596.             'RdvDate' => substr($smsDate010),
  3597.             'heure' => substr($smsDate1115),
  3598.             'clientMail' => $client->getMail(),
  3599.             'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  3600.             'telClient' => $client->getPhone(),
  3601.             'clientNom' => $client->getLastname(),
  3602.             'clientPrenom' => $client->getName(),
  3603.             'clientCivilite' => $client->getCivilite(),
  3604.             'clientPostal' => $client->getPostal(),
  3605.             'clientPhone' => $client->getPhone(),
  3606.             'motif' => $rdv->getIdMotif()->getTitre(),
  3607.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  3608.             'centerName' => $rdv->getIdCentre()->getName(),
  3609.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  3610.             'centerCity' => $rdv->getIdCentre()->getCity(),
  3611.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  3612.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  3613.             'date' => substr($smsDate010),
  3614.             'urlApi' => $_ENV['BASE_API'],
  3615.             'clientId' => $client->getId(),
  3616.             'centerId' => $rdv->getIdCentre()->getId(),
  3617.             'frenchDate' => $frenchDate,
  3618.             'responses' => $responses,
  3619.             'paramsSourceLead' => $paramsSourceLead,
  3620.         ];
  3621.         $subject 'Nouveau RDV MA | RR - ' $rdv->getIdCentre()->getName();
  3622.         $templateEmail = !empty($data['canMove']) ? 190 183;
  3623.         if (!isset($data['isLead'])) {
  3624.             $publicFunction->sendEmail($paramsAdmin'lead.myaudio@gmail.com''my audio'$subject$templateEmail);
  3625.         }
  3626.         $publicFunction->sendEmail($paramsAdmin'contact@myaudio.fr''my audio'$subject$templateEmail);
  3627.     }
  3628.     /**
  3629.      * Synchronise le rendez-vous avec Google Calendar
  3630.      */
  3631.     private function syncGoogleCalendar(Audio $audioRdv $rdvGoogleCalendarService $googleCalendar, array $data): void
  3632.     {
  3633.         try {
  3634.             $synchronisations $this->entityManager->getRepository(SynchronisationSetting::class)
  3635.                 ->findBy(['audio' => $audio->getId()]);
  3636.             $data['rdv'] = $rdv->getId();
  3637.             foreach ($synchronisations as $synchronisation) {
  3638.                 if (!$synchronisation->getIsDeleted()) {
  3639.                     $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  3640.                     $googleCalendar->createEvent($synchronisation$data);
  3641.                 }
  3642.             }
  3643.         } catch (\Exception $e) {
  3644.             $this->logger->error("Erreur synchronisation Google Calendar pour RDV #{$rdv->getId()}: " $e->getMessage());
  3645.         }
  3646.     }
  3647.     /**
  3648.      * @Route("/rdv/{id}/v2", name="getRdvByIDV2", methods={"GET"})
  3649.      *
  3650.      * Version optimisée de getRdvByID
  3651.      * Retourne les informations complètes d'un rendez-vous
  3652.      */
  3653.     public function getRdvByIDV2(int $idRequest $requestPublicFunction $publicFunction): JsonResponse
  3654.     {
  3655.         try {
  3656.             // Validation du token
  3657.             $token $request->query->get('token');
  3658.             if (!$token) {
  3659.                 return new JsonResponse([
  3660.                     'message' => "Aucun token n'a été spécifié",
  3661.                     'status' => 401
  3662.                 ], 401);
  3663.             }
  3664.             $tokenEntity $this->entityManager->getRepository(Token::class)
  3665.                 ->findOneBy(['token' => $token]);
  3666.             if (!$tokenEntity) {
  3667.                 return new JsonResponse([
  3668.                     'message' => "Token invalide. Veuillez vous reconnecter.",
  3669.                     'status' => 404
  3670.                 ], 404);
  3671.             }
  3672.             // Vérification de l'âge du token
  3673.             $dateDiff $tokenEntity->getCreationDate()->diff(new DateTime());
  3674.             if ($dateDiff->7) {
  3675.                 $this->entityManager->remove($tokenEntity);
  3676.                 $this->entityManager->flush();
  3677.                 return new JsonResponse([
  3678.                     'message' => 'Token expiré. Veuillez vous reconnecter.',
  3679.                     'status' => 401
  3680.                 ], 401);
  3681.             }
  3682.             // Récupération du RDV
  3683.             $rdv $this->entityManager->getRepository(Rdv::class)->find($id);
  3684.             if (!$rdv) {
  3685.                 return new JsonResponse([
  3686.                     'message' => "Aucun rendez-vous trouvé avec cet ID",
  3687.                     'status' => 404
  3688.                 ], 404);
  3689.             }
  3690.             // Vérification des droits d'accès
  3691.             $client $tokenEntity->getIdClient();
  3692.             $audio $tokenEntity->getIdAudio();
  3693.             if ($rdv->getIdClient() != $client && $rdv->getIdAudio() != $audio) {
  3694.                 return new JsonResponse([
  3695.                     'message' => "Vous n'êtes pas autorisé à consulter ce rendez-vous",
  3696.                     'status' => 403
  3697.                 ], 403);
  3698.             }
  3699.             // Construction de la réponse
  3700.             $response $this->buildRdvResponse($rdv$publicFunction);
  3701.             return new JsonResponse([
  3702.                 'success' => true,
  3703.                 'rdv' => $response,
  3704.                 'status' => 200
  3705.             ], 200);
  3706.         } catch (\Exception $e) {
  3707.             $this->logger->error("Erreur lors de la récupération du RDV #{$id}: " $e->getMessage());
  3708.             return new JsonResponse([
  3709.                 'success' => false,
  3710.                 'message' => 'Une erreur est survenue lors de la récupération du rendez-vous.',
  3711.                 'error' => $e->getMessage(),
  3712.                 'status' => 500
  3713.             ], 500);
  3714.         }
  3715.     }
  3716.     /**
  3717.      * Construit la réponse complète pour un rendez-vous
  3718.      */
  3719.     private function buildRdvResponse(Rdv $rdvPublicFunction $publicFunction): array
  3720.     {
  3721.         $rdvCentre $rdv->getIdLieu() ?: $rdv->getIdCentre();
  3722.         $audio $rdv->getIdAudio();
  3723.         $centre $rdv->getIdCentre();
  3724.         // Récupération de la liaison audio-centre
  3725.         $liaison null;
  3726.         if ($centre) {
  3727.             $liaison $this->entityManager->getRepository(AudioCentre::class)
  3728.                 ->findOneBy(['id_audio' => $audio'id_centre' => $centre'isConfirmed' => true]);
  3729.         }
  3730.         // Informations de base du RDV
  3731.         $rdvData = [
  3732.             'id' => $rdv->getId(),
  3733.             'date' => $rdv->getDate()->format('Y-m-d H:i:s'),
  3734.             'dateCreation' => $rdv->getDateCreation() ? $rdv->getDateCreation()->format('Y-m-d H:i:s') : null,
  3735.             'duration' => $rdv->getDuration(),
  3736.             'note' => $rdv->getNote(),
  3737.             'comment' => $rdv->getComment(),
  3738.             'review' => $rdv->getReview(),
  3739.             'isMyaudio' => $rdv->getIsMyaudio(),
  3740.             'isRdvLp' => $rdv->getIsRdvLp(),
  3741.             'isRdvRapide' => $rdv->getIsRdvRapide(),
  3742.             'isAbsence' => $rdv->getIsAbsence(),
  3743.             'motif' => [
  3744.                 'id' => $rdv->getIdMotif()->getId(),
  3745.                 'titre' => $rdv->getIdMotif()->getTitre(),
  3746.             ],
  3747.             'etat' => [
  3748.                 'id' => $rdv->getIdEtat()->getId(),
  3749.                 'libelle' => $rdv->getIdEtat()->getLibelle(),
  3750.             ],
  3751.             'client' => $this->buildClientData($rdv),
  3752.             'proche' => $rdv->getIdProche() ? [
  3753.                 'id' => $rdv->getIdProche()->getId(),
  3754.                 'name' => $rdv->getIdProche()->getName(),
  3755.                 'lastname' => $rdv->getIdProche()->getLastname(),
  3756.             ] : null,
  3757.             'testClient' => $rdv->getTestClient() ? [
  3758.                 'result' => $rdv->getTestClient()->getResultTonal(),
  3759.                 'date' => $rdv->getTestClient()->getDate()->format('Y-m-d H:i:s'),
  3760.                 'device' => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  3761.             ] : null,
  3762.             'audio' => $this->buildAudioData($rdv$publicFunction),
  3763.             'centre' => $this->buildCentreData($rdv$rdvCentre$liaison$publicFunction),
  3764.             'remplacant' => $rdv->getRemplacant() ? [
  3765.                 'id' => $rdv->getRemplacant()->getId(),
  3766.                 'civilite' => $rdv->getRemplacant()->getCivilite(),
  3767.                 'name' => $rdv->getRemplacant()->getName(),
  3768.                 'lastname' => $rdv->getRemplacant()->getLastname(),
  3769.                 'imgUrl' => $rdv->getRemplacant()->getImgUrl(),
  3770.             ] : null,
  3771.         ];
  3772.         return $rdvData;
  3773.     }
  3774.     /**
  3775.      * Construit les données du client
  3776.      */
  3777.     private function buildClientData(Rdv $rdv): ?array
  3778.     {
  3779.         $client $rdv->getIdClient() ?: $rdv->getIdClientTemp();
  3780.         if (!$client) {
  3781.             return null;
  3782.         }
  3783.         return [
  3784.             'id' => $client->getId(),
  3785.             'civilite' => $client->getCivilite(),
  3786.             'name' => $client->getName(),
  3787.             'lastname' => $client->getLastname(),
  3788.             'mail' => $client->getMail(),
  3789.             'phone' => $client->getPhone(),
  3790.             'address' => $client->getAddress(),
  3791.             'postal' => $client->getPostal(),
  3792.             'city' => $client->getCity(),
  3793.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format('Y-m-d') : null,
  3794.         ];
  3795.     }
  3796.     /**
  3797.      * Construit les données de l'audio
  3798.      */
  3799.     private function buildAudioData(Rdv $rdvPublicFunction $publicFunction): array
  3800.     {
  3801.         $audio $rdv->getIdAudio();
  3802.         $remplacant $rdv->getRemplacant();
  3803.         // Récupération des reviews audio
  3804.         $audioRdvs $this->entityManager->getRepository(Rdv::class)
  3805.             ->findBy(['id_audio' => $audio->getId()]);
  3806.         $reviewsAudio array_filter($audioRdvs, function($r) {
  3807.             return $r->getReview() !== null && $r->getComment() !== null;
  3808.         });
  3809.         // Motifs
  3810.         $motifs $this->entityManager->getRepository(AudioMotif::class)
  3811.             ->findBy(['id_audio' => $audio->getId()]);
  3812.         $motifsData array_map(function($motif) {
  3813.             return [
  3814.                 'id' => $motif->getIdMotif()->getId(),
  3815.                 'titre' => $motif->getIdMotif()->getTitre(),
  3816.                 'consigne' => $motif->getConsigne(),
  3817.                 'duration' => $motif->getDuration(),
  3818.             ];
  3819.         }, $motifs);
  3820.         // Spécialités
  3821.         $specialities $this->entityManager->getRepository(AudioSpecialite::class)
  3822.             ->findBy(['id_audio' => $audio->getId()]);
  3823.         $specialitiesData array_map(function($spec) {
  3824.             return [
  3825.                 'id' => $spec->getIdSpecialite()->getId(),
  3826.                 'titre' => $spec->getIdSpecialite()->getLibelle(),
  3827.             ];
  3828.         }, $specialities);
  3829.         return [
  3830.             'id' => $remplacant $remplacant->getId() : $audio->getId(),
  3831.             'civilite' => $remplacant $remplacant->getCivilite() : $audio->getCivilite(),
  3832.             'name' => $remplacant $remplacant->getName() : $audio->getName(),
  3833.             'lastname' => $remplacant $remplacant->getLastname() : $audio->getLastname(),
  3834.             'imgUrl' => $remplacant $remplacant->getImgUrl() : $audio->getImgUrl(),
  3835.             'mail' => $remplacant $remplacant->getMail() : $audio->getMail(),
  3836.             'phone' => $remplacant $remplacant->getPhone() : $audio->getPhone(),
  3837.             'adeli' => $audio->getAdeli(),
  3838.             'pin' => $audio->getPin(),
  3839.             'description' => $audio->getDescription(),
  3840.             'averageRating' => $publicFunction->calculateRating($reviewsAudio),
  3841.             'nbrReview' => count($reviewsAudio),
  3842.             'motifs' => array_values($motifsData),
  3843.             'specialities' => array_values($specialitiesData),
  3844.         ];
  3845.     }
  3846.     /**
  3847.      * Construit les données du centre
  3848.      */
  3849.     private function buildCentreData(Rdv $rdv$rdvCentre, ?AudioCentre $liaisonPublicFunction $publicFunction): array
  3850.     {
  3851.         // Récupération des reviews centre
  3852.         $centreRdvs $this->entityManager->getRepository(Rdv::class)
  3853.             ->findBy($rdv->getIdCentre() ? ['id_centre' => $rdvCentre->getId()] : ['id_lieu' => $rdvCentre->getId()]);
  3854.         $reviewsCentre array_filter($centreRdvs, function($r) {
  3855.             return $r->getReview() !== null && $r->getComment() !== null;
  3856.         });
  3857.         // Accès centre
  3858.         $accessCentre $this->entityManager->getRepository(AccessCentre::class)
  3859.             ->findOneBy($rdv->getIdCentre() ? ['id_centre' => $rdvCentre] : ['id_lieu' => $rdvCentre]);
  3860.         // Prestations
  3861.         if ($rdv->getIdCentre()) {
  3862.             $prestations $this->entityManager->getRepository(CentrePrestation::class)
  3863.                 ->findBy(['id_centre' => $rdvCentre->getId()]);
  3864.         } else {
  3865.             $prestations $this->entityManager->getRepository(LieuPrestation::class)
  3866.                 ->findBy(['id_lieu' => $rdvCentre]);
  3867.         }
  3868.         $prestationsData array_map(function($prest) {
  3869.             return [
  3870.                 'id' => $prest->getIdPrestation()->getId(),
  3871.                 'titre' => $prest->getIdPrestation()->getLibelle(),
  3872.             ];
  3873.         }, $prestations);
  3874.         // Mutuelles (uniquement pour centres)
  3875.         $mutuellesData = [];
  3876.         if ($rdv->getIdCentre()) {
  3877.             $mutuelles $this->entityManager->getRepository(CentreMutuelle::class)
  3878.                 ->findBy(['id_centre' => $rdvCentre]);
  3879.             $mutuellesData array_map(function($mut) {
  3880.                 return [
  3881.                     'id' => $mut->getIdMutuelle()->getId(),
  3882.                     'titre' => $mut->getIdMutuelle()->getLibelle(),
  3883.                 ];
  3884.             }, $mutuelles);
  3885.         }
  3886.         // Tiers
  3887.         if ($rdv->getIdCentre()) {
  3888.             $tiers $this->entityManager->getRepository(CentreTier::class)
  3889.                 ->findBy(['id_centre' => $rdvCentre->getId()]);
  3890.         } else {
  3891.             $tiers $this->entityManager->getRepository(LieuTier::class)
  3892.                 ->findBy(['id_lieu' => $rdvCentre]);
  3893.         }
  3894.         $tiersData array_map(function($tier) {
  3895.             return [
  3896.                 'id' => $tier->getIdTier()->getId(),
  3897.                 'titre' => $tier->getIdTier()->getLibelle(),
  3898.             ];
  3899.         }, $tiers);
  3900.         // Horaire
  3901.         $schedule null;
  3902.         if ($rdv->getIdAudio()->getIsIndie() == false) {
  3903.             $schedule $rdv->getIdCentre() ? $rdv->getIdCentre()->getHoraire() : null;
  3904.         } else {
  3905.             $schedule $rdv->getIdLieu() ? $rdv->getIdLieu()->getHoraire() : ($liaison $liaison->getHoraire() : null);
  3906.         }
  3907.         return [
  3908.             'id' => $rdvCentre->getId(),
  3909.             'audio_id' => $rdvCentre->getIdGerant()->getId(),
  3910.             'name' => $rdvCentre->getName(),
  3911.             'imgUrl' => $rdvCentre->getImgUrl(),
  3912.             'isRdvDomicile' => $rdv->getIdCentre() ? $rdvCentre->getIsRdvDomicile() : $rdv->getIdAudio()->getIsRdvDomicileIndie(),
  3913.             'address' => $rdvCentre->getAddress(),
  3914.             'postal' => $rdvCentre->getPostale(),
  3915.             'city' => $rdvCentre->getCity(),
  3916.             'finess' => $rdvCentre->getFiness(),
  3917.             'siret' => $rdvCentre->getSiret(),
  3918.             'website' => $rdvCentre->getWebsite(),
  3919.             'phone' => $rdvCentre->getPhone(),
  3920.             'isHandicap' => $rdvCentre->getIsHandicap(),
  3921.             'longitude' => $rdvCentre->getLongitude(),
  3922.             'latitude' => $rdvCentre->getLatitude(),
  3923.             'description' => $rdv->getIdCentre() ? $rdv->getIdCentre()->getDescription() : null,
  3924.             'averageRating' => $publicFunction->calculateRating($reviewsCentre),
  3925.             'nbrReview' => count($reviewsCentre),
  3926.             'isLieu' => $rdv->getIdLieu() !== null,
  3927.             'schedule' => $schedule,
  3928.             'access' => $accessCentre ? [
  3929.                 'tram' => $accessCentre->getTram(),
  3930.                 'rer' => $accessCentre->getRer(),
  3931.                 'metro' => $accessCentre->getMetro(),
  3932.                 'bus' => $accessCentre->getBus(),
  3933.                 'parkingPublic' => $accessCentre->getParkingPublic(),
  3934.                 'parkingPrivate' => $accessCentre->getParkingPrivate(),
  3935.                 'other' => $accessCentre->getOther(),
  3936.             ] : null,
  3937.             'prestations' => array_values($prestationsData),
  3938.             'mutuelles' => array_values($mutuellesData),
  3939.             'tiers' => array_values($tiersData),
  3940.         ];
  3941.     }
  3942.     /**
  3943.      * @Route("/rdv/{id}/v2", name="editRdvByIDV2", methods={"PUT", "PATCH"})
  3944.      *
  3945.      * Version optimisée de editRdvByID pour les clients
  3946.      * Gestion complète: modification RDV, notifications email/SMS, Google Calendar
  3947.      */
  3948.     public function editRdvByIDV2(
  3949.         int $id,
  3950.         Request $request,
  3951.         PublicFunction $publicFunction,
  3952.         GoogleCalendarService $googleCalendar
  3953.     ): JsonResponse {
  3954.         try {
  3955.             $data json_decode($request->getContent(), true);
  3956.             // Validation du token et récupération du client
  3957.             $validationResult $this->validateTokenAndGetClient($data);
  3958.             if ($validationResult instanceof Response) {
  3959.                 return new JsonResponse(json_decode($validationResult->getContent(), true), $validationResult->getStatusCode());
  3960.             }
  3961.             ['client' => $client] = $validationResult;
  3962.             // Récupération du RDV
  3963.             $rdv $this->entityManager->getRepository(Rdv::class)->find($id);
  3964.             if (!$rdv) {
  3965.                 return new JsonResponse([
  3966.                     'message' => "Aucun rendez-vous trouvé avec cet ID",
  3967.                     'status' => 404
  3968.                 ], 404);
  3969.             }
  3970.             // Vérification des droits (seulement le client peut modifier son RDV)
  3971.             if ($rdv->getIdClient() != $client) {
  3972.                 return new JsonResponse([
  3973.                     'message' => "Vous n'êtes pas autorisé à modifier ce rendez-vous",
  3974.                     'status' => 403
  3975.                 ], 403);
  3976.             }
  3977.             // Sauvegarde des anciennes valeurs pour les notifications
  3978.             $oldDate $rdv->getDate();
  3979.             $oldDuration $rdv->getDuration();
  3980.             // Traitement de la modification
  3981.             $isModified false;
  3982.             $isCancelled false;
  3983.             // Modification de la date
  3984.             if (isset($data['date'])) {
  3985.                 $newDate \DateTime::createFromFormat("d/m/Y H:i"$data['date']);
  3986.                 if (!$newDate) {
  3987.                     return new JsonResponse([
  3988.                         'message' => 'Format de date invalide. Utilisez le format: d/m/Y H:i',
  3989.                         'status' => 400
  3990.                     ], 400);
  3991.                 }
  3992.                 // Vérification de la disponibilité
  3993.                 $audioMotif $this->entityManager->getRepository(AudioMotif::class)
  3994.                     ->findOneBy(['id_audio' => $rdv->getIdAudio(), 'id_motif' => $rdv->getIdMotif()]);
  3995.                 if (!$audioMotif) {
  3996.                     return new JsonResponse([
  3997.                         'message' => "Le motif n'est plus disponible pour cet audioprothésiste",
  3998.                         'status' => 400
  3999.                     ], 400);
  4000.                 }
  4001.                 // Vérification qu'il n'y a pas déjà un RDV à cette nouvelle date
  4002.                 $existingRdv $this->entityManager->getRepository(Rdv::class)
  4003.                     ->findOneBy([
  4004.                         'date' => $newDate,
  4005.                         'id_audio' => $rdv->getIdAudio(),
  4006.                         'id_centre' => $rdv->getIdCentre(),
  4007.                         'id_lieu' => $rdv->getIdLieu(),
  4008.                     ]);
  4009.                 if ($existingRdv && $existingRdv->getId() !== $rdv->getId()) {
  4010.                     return new JsonResponse([
  4011.                         'message' => 'Un rendez-vous existe déjà à ce créneau',
  4012.                         'status' => 409
  4013.                     ], 409);
  4014.                 }
  4015.                 $rdv->setDateOldRdv($oldDate);
  4016.                 $rdv->setDate($newDate);
  4017.                 $isModified true;
  4018.             }
  4019.             // Modification de la durée
  4020.             if (isset($data['duree']) && $data['duree'] !== $oldDuration) {
  4021.                 $rdv->setDuration($data['duree']);
  4022.                 $isModified true;
  4023.             }
  4024.             // Modification de la note
  4025.             if (isset($data['note'])) {
  4026.                 $rdv->setNote($data['note']);
  4027.             }
  4028.             // Gestion de l'annulation (état 2 = annulé)
  4029.             if (isset($data['etat_id']) && $data['etat_id'] == 2) {
  4030.                 $etat $this->entityManager->getRepository(EtatRdv::class)->find(2);
  4031.                 if ($etat) {
  4032.                     $rdv->setIdEtat($etat);
  4033.                     $isCancelled true;
  4034.                     // Suppression des événements Google Calendar
  4035.                     $this->deleteGoogleCalendarEvents($rdv$googleCalendar);
  4036.                 }
  4037.             }
  4038.             // Persistance des modifications
  4039.             $rdv->setGoogleAgendaImported(false);
  4040.             $this->entityManager->flush();
  4041.             // Envoi des notifications
  4042.             if ($isModified && !$isCancelled) {
  4043.                 $this->sendModificationNotifications($rdv$client$oldDate$publicFunction$data);
  4044.                 $this->updateGoogleCalendarEvents($rdv$googleCalendar$data);
  4045.             } elseif ($isCancelled) {
  4046.                 $this->sendCancellationNotifications($rdv$client$publicFunction$data);
  4047.             }
  4048.             // Réponse
  4049.             return new JsonResponse([
  4050.                 'success' => true,
  4051.                 'message' => $isCancelled 'Rendez-vous annulé avec succès' 'Rendez-vous modifié avec succès',
  4052.                 'rdv' => [
  4053.                     'id' => $rdv->getId(),
  4054.                     'date' => $rdv->getDate()->format('Y-m-d H:i:s'),
  4055.                     'duration' => $rdv->getDuration(),
  4056.                     'note' => $rdv->getNote(),
  4057.                     'etat' => [
  4058.                         'id' => $rdv->getIdEtat()->getId(),
  4059.                         'libelle' => $rdv->getIdEtat()->getLibelle(),
  4060.                     ],
  4061.                 ],
  4062.                 'status' => 200
  4063.             ], 200);
  4064.         } catch (\Exception $e) {
  4065.             $this->logger->error("Erreur lors de la modification du RDV #{$id}: " $e->getMessage());
  4066.             return new JsonResponse([
  4067.                 'success' => false,
  4068.                 'message' => 'Une erreur est survenue lors de la modification du rendez-vous.',
  4069.                 'error' => $e->getMessage(),
  4070.                 'status' => 500
  4071.             ], 500);
  4072.         }
  4073.     }
  4074.     /**
  4075.      * Envoie les notifications de modification de RDV
  4076.      */
  4077.     private function sendModificationNotifications(
  4078.         Rdv $rdv,
  4079.         Client $client,
  4080.         \DateTime $oldDate,
  4081.         PublicFunction $publicFunction,
  4082.         array $data
  4083.     ): void {
  4084.         $date $rdv->getDate();
  4085.         $smsDate $date->format('d-m-Y H:i');
  4086.         $formatter = new IntlDateFormatter(
  4087.             'fr_FR',
  4088.             IntlDateFormatter::FULL,
  4089.             IntlDateFormatter::SHORT,
  4090.             null,
  4091.             IntlDateFormatter::GREGORIAN,
  4092.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  4093.         );
  4094.         $smsDateLongFormat $formatter->format($date);
  4095.         $frenchDate ucfirst(preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat));
  4096.         // Notification CLIENT
  4097.         $paramsClient = [
  4098.             'lienModifer' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  4099.             'lienAnnule' => $_ENV['BASE_client'] . 'mes-rendez-vous',
  4100.             'date' => $smsDateLongFormat,
  4101.             'heure' => substr($smsDate1115),
  4102.             'motif' => $rdv->getIdMotif()->getTitre(),
  4103.             'centerName' => $rdv->getIdCentre()->getName(),
  4104.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4105.             'centerPostalCode' => $rdv->getIdCentre()->getPostale(),
  4106.             'audioMail' => $rdv->getIdAudio()->getMail(),
  4107.             'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4108.             'centerCity' => $rdv->getIdCentre()->getCity(),
  4109.             'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4110.             'titre' => 'Votre rendez-vous est modifié pour le',
  4111.             'frenchDate' => $frenchDate,
  4112.         ];
  4113.         $subject "🔀 Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  4114.         $publicFunction->sendEmail(
  4115.             $paramsClient,
  4116.             $client->getMail(),
  4117.             $client->getName() . ' ' $client->getLastName(),
  4118.             $subject,
  4119.             184
  4120.         );
  4121.         // SMS client si demandé
  4122.         if (isset($data['sms']) && $data['sms']) {
  4123.             $smsMessage "Votre RDV est modifié pour le " substr($smsDate010) . " à " substr($smsDate1115) .
  4124.                           ", en cas d'imprévu contactez votre centre " $rdv->getIdCentre()->getPhone() .
  4125.                           " pour modifier votre consultation.\nNe pas répondre.";
  4126.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$smsMessage$client->getPhone());
  4127.         }
  4128.         // Notification AUDIO
  4129.         $audio $rdv->getIdAudio();
  4130.         if ($audio->getModifRdvMail() || $audio->getModifRdvSms()) {
  4131.             $paramsAudio = [
  4132.                 'lienModifer' => $_ENV['BASE_logiciel'] . 'rdv',
  4133.                 'lienAnnule' => $_ENV['BASE_logiciel'] . 'rdv',
  4134.                 'date' => substr($smsDate010),
  4135.                 'frenchDate' => $frenchDate,
  4136.                 'heure' => substr($smsDate1115),
  4137.                 'motif' => $rdv->getIdMotif()->getTitre(),
  4138.                 'clientPhone' => $client->getPhone(),
  4139.                 'clientNom' => $client->getLastname(),
  4140.                 'clientPrenom' => $client->getName(),
  4141.                 'clientCivilite' => $client->getCivilite(),
  4142.                 'clientPostal' => $client->getPostal(),
  4143.                 'clientMail' => $client->getMail(),
  4144.                 'centerName' => $rdv->getIdCentre()->getName(),
  4145.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4146.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  4147.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4148.                 'idPatient' => $client->getId(),
  4149.                 'proUrl' => $_ENV['BASE_logiciel'],
  4150.                 'audioproName' => $audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastName(),
  4151.                 'titre' => 'Votre rendez-vous est modifié pour le :'
  4152.             ];
  4153.             $mailAudio $audio->getMailNotif() ?? $audio->getMail();
  4154.             if ($audio->getModifRdvMail()) {
  4155.                 $subjectAudio "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  4156.                 $publicFunction->sendEmail($paramsAudio$mailAudio$audio->getName() . ' ' $audio->getLastName(), $subjectAudio186);
  4157.             }
  4158.         }
  4159.     }
  4160.     /**
  4161.      * Envoie les notifications d'annulation de RDV
  4162.      */
  4163.     private function sendCancellationNotifications(
  4164.         Rdv $rdv,
  4165.         Client $client,
  4166.         PublicFunction $publicFunction,
  4167.         array $data
  4168.     ): void {
  4169.         $date $rdv->getDate();
  4170.         $smsDate $date->format('d-m-Y H:i');
  4171.         // Notification CLIENT
  4172.         $paramsClient = [
  4173.             'date' => substr($smsDate010),
  4174.             'lien' => $_ENV['BASE_client'] . 'search',
  4175.             'heure' => substr($smsDate1115),
  4176.             'patientName' => $client->getLastName(),
  4177.             'titre' => 'Votre rendez-vous est annulé :',
  4178.             'centerName' => $rdv->getIdCentre()->getName(),
  4179.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4180.             'centerCity' => $rdv->getIdCentre()->getCity(),
  4181.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4182.             'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4183.             'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4184.             'audioMail' => $rdv->getIdAudio()->getMail(),
  4185.             'motif' => $rdv->getIdMotif()->getTitre(),
  4186.         ];
  4187.         $subject "❌ Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  4188.         $publicFunction->sendEmail($paramsClient$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  4189.         // SMS client si demandé
  4190.         if (isset($data['sms']) && $data['sms']) {
  4191.             $smsMessage "Votre RDV a été annulé, contactez votre centre " $rdv->getIdCentre()->getPhone() .
  4192.                           " pour prendre un autre RDV.\nNe pas répondre.";
  4193.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$smsMessage$client->getPhone());
  4194.         }
  4195.         // Notification AUDIO
  4196.         $audio $rdv->getIdAudio();
  4197.         if ($audio->getModifRdvMail()) {
  4198.             $paramsAudio = [
  4199.                 'date' => substr($smsDate010),
  4200.                 'lien' => $_ENV['BASE_client'] . 'search',
  4201.                 'heure' => substr($smsDate1115),
  4202.                 'patientName' => $client->getLastName(),
  4203.                 'titre' => 'Votre rendez-vous est annulé :',
  4204.                 'centerName' => $rdv->getIdCentre()->getName(),
  4205.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4206.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  4207.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4208.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4209.                 'audioproName' => $audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastName(),
  4210.                 'audioMail' => $audio->getMail(),
  4211.                 'motif' => $rdv->getIdMotif()->getTitre(),
  4212.             ];
  4213.             $mailAudio $audio->getMailNotif() ?? $audio->getMail();
  4214.             $subjectAudio "❌ Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  4215.             $publicFunction->sendEmail($paramsAudio$mailAudio$audio->getName() . ' ' $audio->getLastName(), $subjectAudio188);
  4216.         }
  4217.     }
  4218.     /**
  4219.      * Supprime les événements Google Calendar associés au RDV
  4220.      */
  4221.     private function deleteGoogleCalendarEvents(Rdv $rdvGoogleCalendarService $googleCalendar): void
  4222.     {
  4223.         try {
  4224.             $rdvEvents $this->entityManager->getRepository(RdvEvent::class)
  4225.                 ->findBy(['rdv' => $rdv]);
  4226.             foreach ($rdvEvents as $rdvEvent) {
  4227.                 $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4228.                 $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  4229.                 $this->entityManager->remove($rdvEvent);
  4230.             }
  4231.             $this->entityManager->flush();
  4232.         } catch (\Exception $e) {
  4233.             $this->logger->error("Erreur suppression événements Google Calendar pour RDV #{$rdv->getId()}: " $e->getMessage());
  4234.         }
  4235.     }
  4236.     /**
  4237.      * Met à jour les événements Google Calendar
  4238.      */
  4239.     private function updateGoogleCalendarEvents(Rdv $rdvGoogleCalendarService $googleCalendar, array $data): void
  4240.     {
  4241.         try {
  4242.             $rdvEvents $this->entityManager->getRepository(RdvEvent::class)
  4243.                 ->findBy(['rdv' => $rdv]);
  4244.             $data['rdv'] = $rdv->getId();
  4245.             if ($rdv->getIdClient() !== null) {
  4246.                 $data['client_id'] = $rdv->getIdClient()->getId();
  4247.             }
  4248.             foreach ($rdvEvents as $rdvEvent) {
  4249.                 $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4250.                 $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  4251.             }
  4252.         } catch (\Exception $e) {
  4253.             $this->logger->error("Erreur mise à jour événements Google Calendar pour RDV #{$rdv->getId()}: " $e->getMessage());
  4254.         }
  4255.     }
  4256.     /**
  4257.      * @Route("/rdv/{id}/trusteduser", name="contactTrustedUser", methods={"POST"})
  4258.      */
  4259.     public function contactTrustedUser(Request $requestPublicFunction $publicFunction)
  4260.     {
  4261.         $pastDate $rdv->getDate();
  4262.         $data json_decode($request->getContent(), true);
  4263.         $entityManager $this->getDoctrine()->getManager();
  4264.         if (!isset($data["token"])) {
  4265.             return new Response(json_encode([
  4266.                 "message" => "Pas de token n'a été spécifié",
  4267.                 "status" => 401,
  4268.             ]), 401);
  4269.         }
  4270.         /** @var Token */
  4271.         $token $this->getDoctrine()
  4272.             ->getRepository(Token::class)
  4273.             ->findOneBy(['token' => $data["token"]]);
  4274.         if (!$token) {
  4275.             return new Response(json_encode([
  4276.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4277.                 "status" => 404,
  4278.             ]), 404);
  4279.         }
  4280.         // get token age
  4281.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4282.         // if the token if older than 7 days
  4283.         if ($dateDiff->7) {
  4284.             $entityManager->remove($token);
  4285.             $entityManager->flush();
  4286.             return $this->json([
  4287.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4288.                 'path' => 'src/Controller/ClientController.php',
  4289.                 "status" => 401,
  4290.             ], 401);
  4291.         }
  4292.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  4293.             return new Response(json_encode([
  4294.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  4295.                 "status" => 404,
  4296.             ]), 404);
  4297.         }
  4298.         if (isset($data["date"])) {
  4299.             // remove the taken schedule by rdv to make sure there is no overlap
  4300.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4301.             $audioMotif $this->getDoctrine()
  4302.                 ->getRepository(AudioMotif::class)
  4303.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  4304.             if ($audioMotif == null) {
  4305.                 return new Response(json_encode(([
  4306.                     'message' => 'Error, no motif of this id found at this audio',
  4307.                     'path' => 'src/Controller/RdvController.php',
  4308.                     "status" => 400,
  4309.                 ])), 400);
  4310.             }
  4311.             if ($rdv->getIdAudio()->getIsIndie()) {
  4312.                 if ($rdv->getIdCentre()) {
  4313.                     // regular centre audio indie
  4314.                     /** @var AudioCentre */
  4315.                     $liaison $this->getDoctrine()
  4316.                         ->getRepository(AudioCentre::class)
  4317.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  4318.                     if ($liaison == null) {
  4319.                         return new Response(json_encode(([
  4320.                             'message' => 'Error, audio isnt part of the centre',
  4321.                             'path' => 'src/Controller/RdvController.php',
  4322.                             "status" => 400,
  4323.                         ])), 400);
  4324.                     }
  4325.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  4326.                         return new Response(json_encode(([
  4327.                             'message' => 'Error, no horaire found for this audio',
  4328.                             'path' => 'src/Controller/RdvController.php',
  4329.                             "status" => 400,
  4330.                         ])), 400);
  4331.                     }
  4332.                     // if ($publicFunction->calculScheduleFitDate($liaison->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), $rdv->getIdCentre()) == false) {
  4333.                     //     return new Response(json_encode(([
  4334.                     //         'message' => 'Error, no timestamp found at this time',
  4335.                     //         'path' => 'src/Controller/RdvController.php',
  4336.                     //         "status" => 400,
  4337.                     //     ])),400);
  4338.                     // }
  4339.                 } else {
  4340.                     // lieu audio indie
  4341.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  4342.                         return new Response(json_encode(([
  4343.                             'message' => 'Error, no horaire found for this audio',
  4344.                             'path' => 'src/Controller/RdvController.php',
  4345.                             "status" => 400,
  4346.                         ])), 400);
  4347.                     }
  4348.                     // if ($publicFunction->calculScheduleFitDate($rdv->getIdLieu()->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), null, $rdv->getIdLieu()) == false) {
  4349.                     //     return new Response(json_encode(([
  4350.                     //         'message' => 'Error, no timestamp found at this time',
  4351.                     //         'path' => 'src/Controller/RdvController.php',
  4352.                     //         "status" => 400,
  4353.                     //     ])),400);
  4354.                     // }
  4355.                 }
  4356.             } else {
  4357.                 // regular centre
  4358.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  4359.                     return new Response(json_encode(([
  4360.                         'message' => 'Error, no horaire found for this audio',
  4361.                         'path' => 'src/Controller/RdvController.php',
  4362.                         "status" => 400,
  4363.                     ])), 400);
  4364.                 }
  4365.                 // if ($publicFunction->calculScheduleFitDate($rdv->getIdCentre()->getHoraire(), $rdv->getIdAudio(), $date, $audioMotif->getDuration(), $rdv->getIdCentre()) == false) {
  4366.                 //     return new Response(json_encode(([
  4367.                 //         'message' => 'Error, no timestamp found at this time',
  4368.                 //         'path' => 'src/Controller/RdvController.php',
  4369.                 //         "status" => 400,
  4370.                 //     ])),400);
  4371.                 // }
  4372.             }
  4373.             $rdv->setDate($date);
  4374.         }
  4375.         $date $rdv->getDate();
  4376.         $smsDate $date->format('d-m-Y H:i');
  4377.         $oldDate $pastDate->format('d-m-Y H:i');
  4378.         $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>");
  4379.         return new Response(json_encode(([
  4380.             "id" => $rdv->getId(),
  4381.             "status" => 200,
  4382.         ])));
  4383.     }
  4384.     /**
  4385.      * @Route("/rdv/{id}", name="editRdvByID", methods={"PUT"})
  4386.      */
  4387.     public function editRdvByID(PublicFunction $publicFunctionRdv $rdvRequest $requestGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  4388.     {
  4389.         $pastDate $rdv->getDate();
  4390.         $pastDuration $rdv->getDuration();
  4391.         $data json_decode($request->getContent(), true);
  4392.         $entityManager $this->getDoctrine()->getManager();
  4393.         if (!isset($data["token"])) {
  4394.             return new Response(json_encode([
  4395.                 "message" => "Pas de token n'a été spécifié",
  4396.                 "status" => 401,
  4397.             ]), 401);
  4398.         }
  4399.         /** @var Token */
  4400.         $token $this->getDoctrine()
  4401.             ->getRepository(Token::class)
  4402.             ->findOneBy(['token' => $data["token"]]);
  4403.         if (!$token) {
  4404.             return new Response(json_encode([
  4405.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4406.                 "status" => 404,
  4407.             ]), 404);
  4408.         }
  4409.         // get token age
  4410.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4411.         // if the token if older than 7 days
  4412.         if ($dateDiff->7) {
  4413.             $entityManager->remove($token);
  4414.             $entityManager->flush();
  4415.             return $this->json([
  4416.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4417.                 'path' => 'src/Controller/ClientController.php',
  4418.                 "status" => 401,
  4419.             ], 401);
  4420.         }
  4421.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  4422.             return new Response(json_encode([
  4423.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  4424.                 "status" => 404,
  4425.             ]), 404);
  4426.         }
  4427.         if (isset($data["etat_id"])) {
  4428.             $etat $this->getDoctrine()
  4429.                 ->getRepository(EtatRdv::class)
  4430.                 ->findOneBy(['id' => $data["etat_id"]]);
  4431.             if ($etat == null) {
  4432.                 return new Response(json_encode(([
  4433.                     'message' => 'Error, no etat found at this id',
  4434.                     'path' => 'src/Controller/TrustedUserController.php',
  4435.                     "status" => 400,
  4436.                 ])), 400);
  4437.             }
  4438.             $rdv->setIdEtat($etat);
  4439.         }
  4440.         if (isset($data["audio_id"])) {
  4441.             $audio $this->getDoctrine()
  4442.                 ->getRepository(Audio::class)
  4443.                 ->findOneBy(['id' => $data["audio_id"]]);
  4444.             if ($audio == null) {
  4445.                 return new Response(json_encode(([
  4446.                     'message' => 'Error, no audio found at this id',
  4447.                     'path' => 'src/Controller/TrustedUserController.php',
  4448.                     "status" => 400,
  4449.                 ])), 400);
  4450.             }
  4451.             $rdv->setIdAudio($audio);
  4452.         }
  4453.         if (isset($data["motif_id"])) {
  4454.             $motif $this->getDoctrine()
  4455.                 ->getRepository(Motif::class)
  4456.                 ->find($data["motif_id"]);
  4457.             if ($motif == null) {
  4458.                 return new Response(json_encode(([
  4459.                     'message' => 'Error, no motif found at this id',
  4460.                     'path' => 'src/Controller/TrustedUserController.php',
  4461.                     "status" => 400,
  4462.                 ])), 400);
  4463.             }
  4464.             $rdv->setIdMotif($motif);
  4465.         }
  4466.         if (isset($data["client_id"])) {
  4467.             $client $this->getDoctrine()
  4468.                 ->getRepository(Client::class)
  4469.                 ->findOneBy(['id' => $data["client_id"]]);
  4470.             if ($client == null) {
  4471.                 return new Response(json_encode(([
  4472.                     'message' => 'Error, no client found at this id',
  4473.                     'path' => 'src/Controller/TrustedUserController.php',
  4474.                     "status" => 400,
  4475.                 ])), 400);
  4476.             }
  4477.             $rdv->setIdClient($client);
  4478.         }
  4479.         // set client status
  4480.         if (isset($data["client_status_id"])) {
  4481.             $status $this->getDoctrine()
  4482.                 ->getRepository(ClientStatus::class)
  4483.                 ->findOneBy(['id' => $data["client_status_id"]]);
  4484.             if ($status == null) {
  4485.                 return new Response(json_encode(([
  4486.                     'message' => 'Error, no status found at this id',
  4487.                     'path' => 'src/Controller/TrustedUserController.php',
  4488.                     "status" => 400,
  4489.                 ])), 400);
  4490.             }
  4491.             $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  4492.             $client->setClientStatus($status);
  4493.             $client->setLastUpdateStatus(new \DateTimeImmutable);
  4494.         }
  4495.         if (isset($data["date"])) {
  4496.             $submittedDate $data['date'] ?? null;
  4497.             $newDate \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4498.             $currentDate $rdv->getDate();
  4499.             if (!$currentDate || $currentDate->format('d/m/Y H:i') !== $newDate->format('d/m/Y H:i')) {
  4500.                 $rdv->setDateOldRdv($currentDate);
  4501.             }
  4502.             // remove the taken schedule by rdv to make sure there is no overlap
  4503.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4504.             $dateInput \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4505.             $audioMotif $this->getDoctrine()
  4506.                 ->getRepository(AudioMotif::class)
  4507.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  4508.             if ($audioMotif == null) {
  4509.                 return new Response(json_encode(([
  4510.                     'message' => 'Error, no motif of this id found at this audio',
  4511.                     'path' => 'src/Controller/RdvController.php',
  4512.                     "status" => 400,
  4513.                 ])), 400);
  4514.             }
  4515.             if ($rdv->getIdAudio()->getIsIndie()) {
  4516.                 if ($rdv->getIdCentre()) {
  4517.                     // regular centre audio indie
  4518.                     /** @var AudioCentre */
  4519.                     $liaison $this->getDoctrine()
  4520.                         ->getRepository(AudioCentre::class)
  4521.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  4522.                     if ($liaison == null) {
  4523.                         return new Response(json_encode(([
  4524.                             'message' => 'Error, audio isnt part of the centre',
  4525.                             'path' => 'src/Controller/RdvController.php',
  4526.                             "status" => 400,
  4527.                         ])), 400);
  4528.                     }
  4529.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  4530.                         return new Response(json_encode(([
  4531.                             'message' => 'Error, no horaire found for this audio',
  4532.                             'path' => 'src/Controller/RdvController.php',
  4533.                             "status" => 400,
  4534.                         ])), 400);
  4535.                     }
  4536.                 } else {
  4537.                     // lieu audio indie
  4538.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  4539.                         return new Response(json_encode(([
  4540.                             'message' => 'Error, no horaire found for this audio',
  4541.                             'path' => 'src/Controller/RdvController.php',
  4542.                             "status" => 400,
  4543.                         ])), 400);
  4544.                     }
  4545.                 }
  4546.             } else {
  4547.                 // regular centre
  4548.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  4549.                     return new Response(json_encode(([
  4550.                         'message' => 'Error, no horaire found for this audio',
  4551.                         'path' => 'src/Controller/RdvController.php',
  4552.                         "status" => 400,
  4553.                     ])), 400);
  4554.                 }
  4555.             }
  4556.             $rdv->setDate($date);
  4557.         }
  4558.         if (isset($data["comment"]) && $token->getIdClient()) {
  4559.             $rdv->setComment($data["comment"]);
  4560.         }
  4561.         if (isset($data["review"]) && $token->getIdClient()) {
  4562.             $rdv->setReview($data["review"]);
  4563.         }
  4564.         if (isset($data["note"])) {
  4565.             $rdv->setNote($data["note"]);
  4566.         }
  4567.         if (isset($data["duree"])) {
  4568.             $rdv->setDuration($data["duree"]);
  4569.         }
  4570.         ////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
  4571.         $date $rdv->getDate();
  4572.         $smsDate $date->format('d-m-Y H:i');
  4573.         $oldDate $pastDate->format('d-m-Y H:i');
  4574.         $locale 'fr_FR';
  4575.         $formatter = new IntlDateFormatter(
  4576.             $locale,
  4577.             IntlDateFormatter::FULL,
  4578.             IntlDateFormatter::SHORT,
  4579.             null,
  4580.             IntlDateFormatter::GREGORIAN,
  4581.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  4582.         );
  4583.         $smsDateLongFormat $formatter->format($date);
  4584.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  4585.         $frenchDate ucfirst($frenchDate);
  4586.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  4587.         // notif client
  4588.         if ($rdv->getIdEtat()->getId() != 2) {
  4589.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  4590.                 if ($data["sms"]) {
  4591.                     $params = array(
  4592.                         "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4593.                         "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  4594.                         "date" => $smsDateLongFormat,
  4595.                         "heure" => substr($smsDate1115),
  4596.                         "motif" => $rdv->getIdMotif()->getTitre(),
  4597.                         "centerName" => $rdv->getIdCentre()->getName(),
  4598.                         "centerAddress" => $rdv->getIdCentre()->getAddress(),
  4599.                         "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  4600.                         "audioMail" => $rdv->getIdAudio()->getMail(),
  4601.                         "centerPhone" => $rdv->getIdCentre()->getPhone(),
  4602.                         "centerCity" => $rdv->getIdCentre()->getCity(),
  4603.                         "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  4604.                         'titre' => 'Votre rendez-vous est modifié pour le',
  4605.                         'frenchDate' => $frenchDate,
  4606.                     );
  4607.                     $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  4608.                     $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  4609.                     $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.";
  4610.                     $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  4611.                 }
  4612.             }
  4613.         }
  4614.         //     //// == suppression
  4615.         else if ($rdv->getIdEtat()->getId() == 2) {
  4616.             // delete google agenda event
  4617.             $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  4618.                 ->findBy(array('rdv' => $rdv));
  4619.             foreach ($rdvEvents as $rdvEvent) {
  4620.                 $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4621.                 if ($googleCalendar) {
  4622.                     $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  4623.                     $entityManager->remove($rdvEvent);
  4624.                     $entityManager->flush();
  4625.                 }
  4626.             }
  4627.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  4628.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {                   
  4629.             $params = array(
  4630.                 "date" => substr($smsDate010),
  4631.                 "lien" => "{$_ENV['BASE_client']}search",
  4632.                 "heure" => substr($smsDate1115),
  4633.                 "patientName" => $client->getLastName(),
  4634.                 'titre' => 'Votre rendez-vous est annulé :',
  4635.                 'centerName' => $rdv->getIdCentre()->getName(),
  4636.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4637.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  4638.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4639.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4640.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4641.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  4642.                 'motif' => $rdv->getIdMotif()->getTitre(),
  4643.             );
  4644.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  4645.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  4646.             if ($data["sms"]) {
  4647.                 $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  4648.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  4649.             }
  4650.             //}
  4651.         }
  4652.         // set center
  4653.         if (isset($data["centre_id"])) {
  4654.             $entityManager $this->getDoctrine()->getManager();
  4655.             $centreId $data["centre_id"];
  4656.             $centre $entityManager->getRepository(Centre::class)->find($centreId);
  4657.             if (!$centre) {
  4658.                 return $this->json([
  4659.                     'message' => 'Error, no Centre found with this ID',
  4660.                     'path' => 'src/Controller/YourController.php',
  4661.                 ]);
  4662.             }
  4663.             $rdv->setIdCentre($centre);
  4664.         }
  4665.         $rdv->setGoogleAgendaImported(false);
  4666.         //notif Audio
  4667.         if ($rdv->getIdEtat()->getId() != 2) {
  4668.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  4669.                 if ($data["sms"]) {
  4670.                     $params = array(
  4671.                         "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  4672.                         "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  4673.                         "date" => substr($smsDate010),
  4674.                         "frenchDate" => $frenchDate,
  4675.                         "heure" => substr($smsDate1115),
  4676.                         'motif' => $rdv->getIdMotif()->getTitre(),
  4677.                         'clientPhone' => $client->getPhone(),
  4678.                         'clientNom' => $client->getLastname(),
  4679.                         'clientPrenom' => $client->getName(),
  4680.                         'clientCivilite' => $client->getCivilite(),
  4681.                         'clientPostal' => $client->getPostal(),
  4682.                         'clientMail' => $client->getMail(),
  4683.                         'centerName' => $rdv->getIdCentre()->getName(),
  4684.                         'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4685.                         'centerCity' => $rdv->getIdCentre()->getCity(),
  4686.                         'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4687.                         'idPatient' => $client->getId(),
  4688.                         'proUrl' => "{$_ENV['BASE_logiciel']}",
  4689.                         'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4690.                         'titre' => 'Votre rendez-vous est modifié pour le :'
  4691.                     );
  4692.                     $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  4693.                     $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  4694.                     if ($rdv->getIdAudio()->getModifRdvMail()) {
  4695.                         $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  4696.                         $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  4697.                     }
  4698.                     if ($rdv->getIdAudio()->getModifRdvSms()) {
  4699.                         // we ignore the sms send to the audio for the case he modify the rdv (so lets commented)
  4700.                         $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.";
  4701.                         //$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  4702.                     }
  4703.                 }
  4704.             }
  4705.         } else if ($rdv->getIdEtat()->getId() == 2) {
  4706.             if ($data["sms"]) {
  4707.                 $params = array(
  4708.                     "date" => substr($smsDate010),
  4709.                     "lien" => "{$_ENV['BASE_client']}search",
  4710.                     "heure" => substr($smsDate1115),
  4711.                     "patientName" => $client->getLastName(),
  4712.                     'titre' => 'Votre rendez-vous est annulé :',
  4713.                     'centerName' => $rdv->getIdCentre()->getName(),
  4714.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  4715.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  4716.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  4717.                     'centerPhone' => $rdv->getIdCentre()->getPhone(),
  4718.                     'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  4719.                     'audioMail' => $rdv->getIdAudio()->getMail(),
  4720.                     'motif' => $rdv->getIdMotif()->getTitre(),
  4721.                 );
  4722.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  4723.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  4724.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  4725.                     $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  4726.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject188);
  4727.                 }
  4728.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  4729.                     $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.";
  4730.                     // $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  4731.                 }
  4732.             }
  4733.         }
  4734.         $entityManager->flush();
  4735.         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"]))) {
  4736.             if (is_null($rdv->getIdClientTemp())) {
  4737.                 $clientRDV $this->getDoctrine()
  4738.                     ->getRepository(Client::class)
  4739.                     ->findOneBy(['id' => $rdv->getIdClient()->getId()]);
  4740.                 $clientRDV->setName($data["prenom_patient"]);
  4741.                 $clientRDV->setLastname($data["nom_patient"]);
  4742.                 $clientRDV->setMail($data["mail_patient"]);
  4743.                 $clientRDV->setPhone($data["portable_patient"]);
  4744.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  4745.             } else {
  4746.                 $clientRDV $this->getDoctrine()
  4747.                     ->getRepository(ClientTemp::class)
  4748.                     ->findOneBy(['id' => $rdv->getIdClientTemp()->getId()]);
  4749.                 $clientRDV->setName($data["prenom_patient"]);
  4750.                 $clientRDV->setLastname($data["nom_patient"]);
  4751.                 $clientRDV->setMail($data["mail_patient"]);
  4752.                 $clientRDV->setPhone($data["portable_patient"]);
  4753.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  4754.             }
  4755.             if (!empty($data["birthday_patient"])) {
  4756.                 $birth \DateTime::createFromFormat("Y-m-d"$data["birthday_patient"]);
  4757.                 $clientRDV->setBirthdate($birth);
  4758.             }
  4759.             $entityManager->flush();
  4760.         }
  4761.         if (is_null($rdv->getIdClient())) {
  4762.             $prenom_patient $rdv->getIdClientTemp()->getName();
  4763.             $nom_patient $rdv->getIdClientTemp()->getLastname();
  4764.             $mail_patient $rdv->getIdClientTemp()->getMail();
  4765.             $portable_patient $rdv->getIdClientTemp()->getPhone();
  4766.             $fixe_patient $rdv->getIdClientTemp()->getPhoneFixe();
  4767.             $birthday $rdv->getIdClientTemp()->getBirthdate();
  4768.         } elseif (is_null($rdv->getIdClientTemp())) {
  4769.             $prenom_patient =  $rdv->getIdClient()->getName();
  4770.             $nom_patient $rdv->getIdClient()->getLastname();
  4771.             $mail_patient $rdv->getIdClient()->getMail();
  4772.             $portable_patient $rdv->getIdClient()->getPhone();
  4773.             $fixe_patient $rdv->getIdClient()->getPhoneFixe();
  4774.             $birthday $rdv->getIdClient()->getBirthdate();
  4775.         } else {
  4776.             $prenom_patient "";
  4777.             $nom_patient "";
  4778.             $mail_patient "";
  4779.             $portable_patient "";
  4780.             $fixe_patient "";
  4781.             $birthday "";
  4782.         }
  4783.         /* generate sms notif on update */
  4784.         // update sms notification     
  4785.         $rdvSms->updateRdvSms($rdv);
  4786.         // google calendar update
  4787.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  4788.             ->findBy(array('audio' => $rdv->getIdAudio()));
  4789.         $data['rdv'] = $rdv->getId();
  4790.         if ($rdv->getIdClient() !== null) {
  4791.             $data["client_id"] = $rdv->getIdClient()->getId();
  4792.         }
  4793.         if ($rdv->getIdClientTemp() !== null) {
  4794.             $data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
  4795.         }
  4796.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  4797.             ->findBy(array('rdv' => $rdv));
  4798.         foreach ($rdvEvents as $rdvEvent) {
  4799.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  4800.             $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  4801.         }
  4802.         $synchronisationCosium $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $rdv->getIdAudio()->getId()]);
  4803.         $cosiumCenter $this->getDoctrine()->getRepository(CosiumCenter::class)->findOneBy(["synchronisationCosium" => $synchronisationCosium"center" => $rdv->getIdCentre()]);
  4804.         if ($cosiumCenter) {
  4805.             $this->clientCosiumService->deleteRdv($synchronisationCosium$rdv);
  4806.             $this->clientCosiumService->createAgenda($synchronisationCosium$rdv$cosiumCenter);
  4807.         }
  4808.         // After successfully updating the RDV
  4809.         $this->mercure->publishRdvUpdate($rdv'updated');
  4810.         return new Response(json_encode(([
  4811.             "id" => $rdv->getId(),
  4812.             "motif_id" => $rdv->getIdMotif()->getId(),
  4813.             "motif_libelle" => $rdv->getIdMotif()->getTitre(),
  4814.             "audio_id" => $rdv->getIdAudio()->getId(),
  4815.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  4816.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  4817.             "fullName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  4818.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  4819.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  4820.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  4821.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  4822.             "centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
  4823.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  4824.             "etat_id" => $rdv->getIdEtat()->getId(),
  4825.             "date" => $rdv->getDate(),
  4826.             "comment" => $rdv->getComment(),
  4827.             "note" => $rdv->getNote(),
  4828.             "review" => $rdv->getReview(),
  4829.             "clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
  4830.             "prenom_patient" => $prenom_patient,
  4831.             "nom_patient" => $nom_patient,
  4832.             "mail_patient" => $mail_patient,
  4833.             "portable_patient" => $portable_patient,
  4834.             "fixe_patient" => $fixe_patient,
  4835.             "birthday" => $birthday,
  4836.             "status" => 200,
  4837.         ])));
  4838.     }
  4839.     /**
  4840.      * @Route("/rdv-by-patient/{id}", name="editRdvByIDFromPatient", methods={"PUT"})
  4841.      */
  4842.     public function editRdvByIDFromPatient(PublicFunction $publicFunctionRdv $rdvRequest $request): Response
  4843.     {
  4844.         $pastDate $rdv->getDate();
  4845.         $pastDuration $rdv->getDuration();
  4846.         $data json_decode($request->getContent(), true);
  4847.         $entityManager $this->getDoctrine()->getManager();
  4848.         if (!isset($data["token"])) {
  4849.             return new Response(json_encode([
  4850.                 "message" => "Pas de token n'a été spécifié",
  4851.                 "status" => 401,
  4852.             ]), 401);
  4853.         }
  4854.         /** @var Token */
  4855.         $token $this->getDoctrine()
  4856.             ->getRepository(Token::class)
  4857.             ->findOneBy(['token' => $data["token"]]);
  4858.         if (!$token) {
  4859.             return new Response(json_encode([
  4860.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  4861.                 "status" => 404,
  4862.             ]), 404);
  4863.         }
  4864.         // get token age
  4865.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  4866.         // if the token if older than 7 days
  4867.         if ($dateDiff->7) {
  4868.             $entityManager->remove($token);
  4869.             $entityManager->flush();
  4870.             return $this->json([
  4871.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  4872.                 'path' => 'src/Controller/ClientController.php',
  4873.                 "status" => 401,
  4874.             ], 401);
  4875.         }
  4876.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  4877.             return new Response(json_encode([
  4878.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  4879.                 "status" => 404,
  4880.             ]), 404);
  4881.         }
  4882.         if (isset($data["etat_id"])) {
  4883.             $etat $this->getDoctrine()
  4884.                 ->getRepository(EtatRdv::class)
  4885.                 ->findOneBy(['id' => $data["etat_id"]]);
  4886.             if ($etat == null) {
  4887.                 return new Response(json_encode(([
  4888.                     'message' => 'Error, no etat found at this id',
  4889.                     'path' => 'src/Controller/TrustedUserController.php',
  4890.                     "status" => 400,
  4891.                 ])), 400);
  4892.             }
  4893.             $rdv->setIdEtat($etat);
  4894.         }
  4895.         if (isset($data["audio_id"])) {
  4896.             $audio $this->getDoctrine()
  4897.                 ->getRepository(Audio::class)
  4898.                 ->findOneBy(['id' => $data["audio_id"]]);
  4899.             if ($audio == null) {
  4900.                 return new Response(json_encode(([
  4901.                     'message' => 'Error, no audio found at this id',
  4902.                     'path' => 'src/Controller/TrustedUserController.php',
  4903.                     "status" => 400,
  4904.                 ])), 400);
  4905.             }
  4906.             $rdv->setIdAudio($audio);
  4907.         }
  4908.         if (isset($data["motif_id"])) {
  4909.             $motif $this->getDoctrine()
  4910.                 ->getRepository(Motif::class)
  4911.                 ->find($data["motif_id"]);
  4912.             if ($motif == null) {
  4913.                 return new Response(json_encode(([
  4914.                     'message' => 'Error, no motif found at this id',
  4915.                     'path' => 'src/Controller/TrustedUserController.php',
  4916.                     "status" => 400,
  4917.                 ])), 400);
  4918.             }
  4919.             $rdv->setIdMotif($motif);
  4920.         }
  4921.         if (isset($data["client_id"])) {
  4922.             $client $this->getDoctrine()
  4923.                 ->getRepository(Client::class)
  4924.                 ->findOneBy(['id' => $data["client_id"]]);
  4925.             if ($client == null) {
  4926.                 return new Response(json_encode(([
  4927.                     'message' => 'Error, no client found at this id',
  4928.                     'path' => 'src/Controller/TrustedUserController.php',
  4929.                     "status" => 400,
  4930.                 ])), 400);
  4931.             }
  4932.             $rdv->setIdClient($client);
  4933.         }
  4934.         if (isset($data["date"])) {
  4935.             // remove the taken schedule by rdv to make sure there is no overlap
  4936.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4937.             $dateInput \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  4938.             $audioMotif $this->getDoctrine()
  4939.                 ->getRepository(AudioMotif::class)
  4940.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  4941.             if ($audioMotif == null) {
  4942.                 return new Response(json_encode(([
  4943.                     'message' => 'Error, no motif of this id found at this audio',
  4944.                     'path' => 'src/Controller/RdvController.php',
  4945.                     "status" => 400,
  4946.                 ])), 400);
  4947.             }
  4948.             if ($rdv->getIdAudio()->getIsIndie()) {
  4949.                 if ($rdv->getIdCentre()) {
  4950.                     // regular centre audio indie
  4951.                     /** @var AudioCentre */
  4952.                     $liaison $this->getDoctrine()
  4953.                         ->getRepository(AudioCentre::class)
  4954.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  4955.                     if ($liaison == null) {
  4956.                         return new Response(json_encode(([
  4957.                             'message' => 'Error, audio isnt part of the centre',
  4958.                             'path' => 'src/Controller/RdvController.php',
  4959.                             "status" => 400,
  4960.                         ])), 400);
  4961.                     }
  4962.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  4963.                         return new Response(json_encode(([
  4964.                             'message' => 'Error, no horaire found for this audio',
  4965.                             'path' => 'src/Controller/RdvController.php',
  4966.                             "status" => 400,
  4967.                         ])), 400);
  4968.                     }
  4969.                 } else {
  4970.                     // lieu audio indie
  4971.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  4972.                         return new Response(json_encode(([
  4973.                             'message' => 'Error, no horaire found for this audio',
  4974.                             'path' => 'src/Controller/RdvController.php',
  4975.                             "status" => 400,
  4976.                         ])), 400);
  4977.                     }
  4978.                 }
  4979.             } else {
  4980.                 // regular centre
  4981.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  4982.                     return new Response(json_encode(([
  4983.                         'message' => 'Error, no horaire found for this audio',
  4984.                         'path' => 'src/Controller/RdvController.php',
  4985.                         "status" => 400,
  4986.                     ])), 400);
  4987.                 }
  4988.             }
  4989.             $rdv->setDate($date);
  4990.         }
  4991.         if (isset($data["comment"]) && $token->getIdClient()) {
  4992.             $rdv->setComment($data["comment"]);
  4993.         }
  4994.         if (isset($data["review"]) && $token->getIdClient()) {
  4995.             $rdv->setReview($data["review"]);
  4996.         }
  4997.         if (isset($data["note"])) {
  4998.             $rdv->setNote($data["note"]);
  4999.         }
  5000.         if (isset($data["duree"])) {
  5001.             $rdv->setDuration($data["duree"]);
  5002.         }
  5003.         ////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
  5004.         $date $rdv->getDate();
  5005.         $smsDate $date->format('d-m-Y H:i');
  5006.         $oldDate $pastDate->format('d-m-Y H:i');
  5007.         $locale 'fr_FR';
  5008.         $formatter = new IntlDateFormatter(
  5009.             $locale,
  5010.             IntlDateFormatter::FULL,
  5011.             IntlDateFormatter::SHORT,
  5012.             null,
  5013.             IntlDateFormatter::GREGORIAN,
  5014.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  5015.         );
  5016.         $smsDateLongFormat $formatter->format($date);
  5017.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  5018.         $frenchDate ucfirst($frenchDate);
  5019.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  5020.         // notif client
  5021.         if ($rdv->getIdEtat()->getId() != 2) {
  5022.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  5023.                 $params = array(
  5024.                     "lienModifier" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5025.                     "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5026.                     "date" => $smsDateLongFormat,
  5027.                     "heure" => substr($smsDate1115),
  5028.                     "motif" => $rdv->getIdMotif()->getTitre(),
  5029.                     "centerName" => $rdv->getIdCentre()->getName(),
  5030.                     "centerAddress" => $rdv->getIdCentre()->getAddress(),
  5031.                     "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  5032.                     "audioMail" => $rdv->getIdAudio()->getMail(),
  5033.                     "centerPhone" => $rdv->getIdCentre()->getPhone(),
  5034.                     "centerCity" => $rdv->getIdCentre()->getCity(),
  5035.                     "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  5036.                     'titre' => 'Votre rendez-vous est modifié pour le',
  5037.                     'frenchDate' => $frenchDate,
  5038.                 );
  5039.                 $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  5040.                 $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  5041.                 $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.";
  5042.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5043.             }
  5044.         }
  5045.         //     //// == suppression
  5046.         else if ($rdv->getIdEtat()->getId() == 2) {
  5047.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  5048.             //if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {                   
  5049.             $params = array(
  5050.                 "date" => substr($smsDate010),
  5051.                 "lien" => "{$_ENV['BASE_client']}audioprothesiste/{$rdv->getIdCentre()->getCity()}/{$rdv->getIdCentre()->getPostale()}/{$rdv->getIdCentre()->getName()}/prise-de-rdv-audioprothesiste-rapide/{$rdv->getIdCentre()->getId()}",
  5052.                 "heure" => substr($smsDate1115),
  5053.                 "patientName" => $client->getLastName(),
  5054.                 'titre' => 'Votre rendez-vous est annulé :',
  5055.                 'centerName' => $rdv->getIdCentre()->getName(),
  5056.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5057.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  5058.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5059.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  5060.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5061.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  5062.                 'motif' => $rdv->getIdMotif()->getTitre(),
  5063.             );
  5064.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  5065.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject203);
  5066.             $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  5067.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5068.             //}
  5069.         }
  5070.         // set center
  5071.         if (isset($data["centre_id"])) {
  5072.             $entityManager $this->getDoctrine()->getManager();
  5073.             $centreId $data["centre_id"];
  5074.             $centre $entityManager->getRepository(Centre::class)->find($centreId);
  5075.             if (!$centre) {
  5076.                 return $this->json([
  5077.                     'message' => 'Error, no Centre found with this ID',
  5078.                     'path' => 'src/Controller/YourController.php',
  5079.                 ]);
  5080.             }
  5081.             $rdv->setIdCentre($centre);
  5082.         }
  5083.         $rdv->setGoogleAgendaImported(false);
  5084.         //notif Audio
  5085.         if ($rdv->getIdEtat()->getId() != 2) {
  5086.             if ($pastDate->format('Y-m-d H:i:s') !== $dateInput->format('Y-m-d H:i:s') || $data['duree'] !== $pastDuration) {
  5087.                 $params = array(
  5088.                     "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  5089.                     "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  5090.                     "date" => $pastDate->format("y-m-d"),
  5091.                     "heure" => $pastDate->format("H:i"),
  5092.                     'clientPhone' => $client->getPhone(),
  5093.                     'clientCivilite' => $client->getCivilite(),
  5094.                     'clientNom' => $client->getLastname(),
  5095.                     'clientPrenom' => $client->getName(),
  5096.                     'clientPostal' => $client->getPostal(),
  5097.                     'clientMail' => $client->getMail(),
  5098.                     "birthdate" => $rdv->getIdClient()->getBirthdate()->format("y-m-d"),
  5099.                     "mail" => $rdv->getIdClient()->getMail(),
  5100.                     "phone" => $rdv->getIdClient()->getPhone(),
  5101.                     "motif" => $rdv->getIdMotif()->getTitre(),
  5102.                     "address" => $rdv->getIdCentre()->getAddress(),
  5103.                     "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getLastName() . ' ' $rdv->getIdAudio()->getName(),
  5104.                     "newRdvDate" => substr($smsDate010),
  5105.                     "newRdvHour" => substr($smsDate1115),
  5106.                     "centerName" => $rdv->getIdCentre()->getName(),
  5107.                     "centerAddress" => $rdv->getIdCentre()->getAddress(),
  5108.                     "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  5109.                     'titre' => "Modification de Rendez-vous My Audio de {$rdv->getIdClient()->getLastname()}",
  5110.                     "urlPro" => "{$_ENV['BASE_logiciel']}",
  5111.                     "idPatient" => $rdv->getIdClient()->getId(),
  5112.                 );
  5113.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  5114.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  5115.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  5116.                     $subject "🔀 Rendez-vous My Audio modifié par " $client->getCivilite() . " " $client->getName() . " " $client->getLastname();
  5117.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject185);
  5118.                 }
  5119.                 $subjectMyAudio "🔀 Le patient " $client->getCivilite() . " " $client->getName() . " " $client->getLastname() . "  a modifié son rendez-vous My Audio";
  5120.                 $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subjectMyAudio204);
  5121.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  5122.                     $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.";
  5123.                     $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  5124.                 }
  5125.             }
  5126.         } else if ($rdv->getIdEtat()->getId() == 2) {
  5127.             $params = array(
  5128.                 "date" => substr($smsDate010),
  5129.                 "heure" => substr($smsDate1115),
  5130.                 "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  5131.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5132.                 "motif" => $rdv->getIdMotif()->getTitre(),
  5133.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  5134.                 "centerPostal" => $rdv->getIdCentre()->getPostale(),
  5135.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  5136.                 "centerName" => $rdv->getIdCentre()->getName(),
  5137.                 "clientNom" => $rdv->getIdClient()->getLastname(),
  5138.                 "clientPrenom" => $rdv->getIdClient()->getName(),
  5139.                 "clientMail" => $rdv->getIdClient()->getMail(),
  5140.                 "clientPhone" => $rdv->getIdClient()->getPhone(),
  5141.                 'titre' => "Annulation du Rendez-vous avec le patient {$rdv->getIdClient()->getLastname()}",
  5142.                 "proUrl" => "{$_ENV['BASE_logiciel']}",
  5143.                 "idPatient" => $rdv->getIdClient()->getId(),
  5144.             );
  5145.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  5146.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  5147.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  5148.                 $subject "❌ Annulation du rendez-vous par le patient " $client->getCivilite() . " " $client->getName() . " " $client->getLastname();
  5149.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject187);
  5150.             }
  5151.             $subject "❌ Annulation du rendez-vous par le patient " $client->getCivilite() . " " $client->getName() . " " $client->getLastname();
  5152.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject195);
  5153.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  5154.                 $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.";
  5155.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  5156.             }
  5157.         }
  5158.         $entityManager->flush();
  5159.         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"]))) {
  5160.             $birth \DateTime::createFromFormat("Y-m-d"$data["birthday_patient"]);
  5161.             if (is_null($rdv->getIdClientTemp())) {
  5162.                 $clientRDV $this->getDoctrine()
  5163.                     ->getRepository(Client::class)
  5164.                     ->findOneBy(['id' => $rdv->getIdClient()->getId()]);
  5165.                 $clientRDV->setName($data["prenom_patient"]);
  5166.                 $clientRDV->setLastname($data["nom_patient"]);
  5167.                 $clientRDV->setBirthdate($birth);
  5168.                 $clientRDV->setMail($data["mail_patient"]);
  5169.                 $clientRDV->setPhone($data["portable_patient"]);
  5170.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  5171.             } else {
  5172.                 $clientRDV $this->getDoctrine()
  5173.                     ->getRepository(ClientTemp::class)
  5174.                     ->findOneBy(['id' => $rdv->getIdClientTemp()->getId()]);
  5175.                 $clientRDV->setName($data["prenom_patient"]);
  5176.                 $clientRDV->setLastname($data["nom_patient"]);
  5177.                 $clientRDV->setBirthdate($birth);
  5178.                 $clientRDV->setMail($data["mail_patient"]);
  5179.                 $clientRDV->setPhone($data["portable_patient"]);
  5180.                 $clientRDV->setPhoneFixe($data["fixe_patient"]);
  5181.             }
  5182.             $entityManager->flush();
  5183.         }
  5184.         if (is_null($rdv->getIdClient())) {
  5185.             $prenom_patient $rdv->getIdClientTemp()->getName();
  5186.             $nom_patient $rdv->getIdClientTemp()->getLastname();
  5187.             $mail_patient $rdv->getIdClientTemp()->getMail();
  5188.             $portable_patient $rdv->getIdClientTemp()->getPhone();
  5189.             $fixe_patient $rdv->getIdClientTemp()->getPhoneFixe();
  5190.             $birthday $rdv->getIdClientTemp()->getBirthdate();
  5191.         } elseif (is_null($rdv->getIdClientTemp())) {
  5192.             $prenom_patient =  $rdv->getIdClient()->getName();
  5193.             $nom_patient $rdv->getIdClient()->getLastname();
  5194.             $mail_patient $rdv->getIdClient()->getMail();
  5195.             $portable_patient $rdv->getIdClient()->getPhone();
  5196.             $fixe_patient $rdv->getIdClient()->getPhoneFixe();
  5197.             $birthday $rdv->getIdClient()->getBirthdate();
  5198.         } else {
  5199.             $prenom_patient "";
  5200.             $nom_patient "";
  5201.             $mail_patient "";
  5202.             $portable_patient "";
  5203.             $fixe_patient "";
  5204.             $birthday "";
  5205.         }
  5206.         return new Response(json_encode(([
  5207.             "id" => $rdv->getId(),
  5208.             "motif_id" => $rdv->getIdMotif()->getId(),
  5209.             "motif_libelle" => $rdv->getIdMotif()->getTitre(),
  5210.             "audio_id" => $rdv->getIdAudio()->getId(),
  5211.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  5212.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  5213.             "fullName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  5214.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  5215.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  5216.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  5217.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  5218.             "centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
  5219.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  5220.             "etat_id" => $rdv->getIdEtat()->getId(),
  5221.             "date" => $rdv->getDate(),
  5222.             "comment" => $rdv->getComment(),
  5223.             "note" => $rdv->getNote(),
  5224.             "review" => $rdv->getReview(),
  5225.             "prenom_patient" => $prenom_patient,
  5226.             "nom_patient" => $nom_patient,
  5227.             "mail_patient" => $mail_patient,
  5228.             "portable_patient" => $portable_patient,
  5229.             "fixe_patient" => $fixe_patient,
  5230.             "birthday" => $birthday,
  5231.             "status" => 200,
  5232.         ])));
  5233.     }
  5234.     /**
  5235.      * @Route("/rdv/{id}/supp", name="suppRdvByID", methods={"PUT"})
  5236.      */
  5237.     public function suppRdvByID(PublicFunction $publicFunctionRdv $rdvRequest $requestGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  5238.     {
  5239.         $pastDate $rdv->getDate();
  5240.         $data json_decode($request->getContent(), true);
  5241.         $entityManager $this->getDoctrine()->getManager();
  5242.         if (!isset($data["token"])) {
  5243.             return new Response(json_encode([
  5244.                 "message" => "Pas de token n'a été spécifié",
  5245.                 "status" => 401,
  5246.             ]), 401);
  5247.         }
  5248.         /** @var Token */
  5249.         $token $this->getDoctrine()
  5250.             ->getRepository(Token::class)
  5251.             ->findOneBy(['token' => $data["token"]]);
  5252.         if (!$token) {
  5253.             return new Response(json_encode([
  5254.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5255.                 "status" => 404,
  5256.             ]), 404);
  5257.         }
  5258.         // get token age
  5259.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5260.         // if the token if older than 7 days
  5261.         if ($dateDiff->7) {
  5262.             $entityManager->remove($token);
  5263.             $entityManager->flush();
  5264.             return $this->json([
  5265.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5266.                 'path' => 'src/Controller/ClientController.php',
  5267.                 "status" => 401,
  5268.             ], 401);
  5269.         }
  5270.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  5271.             return new Response(json_encode([
  5272.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  5273.                 "status" => 404,
  5274.             ]), 404);
  5275.         }
  5276.         // delete google agenda event
  5277.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  5278.             ->findBy(array('rdv' => $rdv));
  5279.         //dd($rdvEvents);
  5280.         $synchronisationCosium $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $rdv->getIdAudio()->getId()]);
  5281.         $cosiumCenter $this->getDoctrine()->getRepository(CosiumCenter::class)->findBy(["synchronisationCosium" => $synchronisationCosium"center" => $rdv->getIdCentre()]);
  5282.         if ($cosiumCenter) {
  5283.             $this->clientCosiumService->deleteRdv($synchronisationCosium$rdv);
  5284.         }
  5285.         foreach ($rdvEvents as $rdvEvent) {
  5286.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  5287.             $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  5288.             $entityManager->remove($rdvEvent);
  5289.             $entityManager->flush();
  5290.         }
  5291.         $etat $this->getDoctrine()
  5292.             ->getRepository(EtatRdv::class)
  5293.             ->findOneBy(['id' => 2]);
  5294.         if ($etat == null) {
  5295.             return new Response(json_encode(([
  5296.                 'message' => 'Error, no etat found at this id',
  5297.                 'path' => 'src/Controller/TrustedUserController.php',
  5298.                 "status" => 400,
  5299.             ])), 400);
  5300.         }
  5301.         $rdv->setIdEtat($etat);
  5302.         $rdv->setCacher(1);
  5303.         ////// SMSEMAIL A décommenter pour activer l'envoi de SMS + MAIL pour modification annulation de RDV, coté audio / client SMSEMAIL ////
  5304.         $date $rdv->getDate();
  5305.         $smsDate $date->format('d-m-Y H:i');
  5306.         $oldDate $pastDate->format('d-m-Y H:i');
  5307.         $locale 'fr_FR';
  5308.         $formatter = new IntlDateFormatter(
  5309.             $locale,
  5310.             IntlDateFormatter::FULL,
  5311.             IntlDateFormatter::SHORT,
  5312.             null,
  5313.             IntlDateFormatter::GREGORIAN,
  5314.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  5315.         );
  5316.         $smsDateLongFormat $formatter->format($date);
  5317.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  5318.         $frenchDate ucfirst($frenchDate);
  5319.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  5320.         // notif client
  5321.         if ($rdv->getIdEtat()->getId() != 2) {
  5322.             $params = array(
  5323.                 "lienModifier" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5324.                 "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5325.                 "date" => $smsDateLongFormat,
  5326.                 "heure" => substr($smsDate1115),
  5327.                 "motif" => $rdv->getIdMotif()->getTitre(),
  5328.                 "centerName" => $rdv->getIdCentre()->getName(),
  5329.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  5330.                 "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  5331.                 "audioMail" => $rdv->getIdAudio()->getMail(),
  5332.                 "centerPhone" => $rdv->getIdCentre()->getPhone(),
  5333.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  5334.                 "clientEmail" => $client->getMail(),
  5335.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  5336.                 'titre' => 'Votre rendez-vous est modifié pour le',
  5337.                 'frenchDate' => $frenchDate
  5338.             );
  5339.             $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  5340.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject205);
  5341.             $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.";
  5342.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5343.             // creer un mail de notif pour myAudio + créé le template LP | MA | RR - Modification du RDV - Centre Auditif - MyAudio
  5344.             $subjectMyaudio "Rendez-vous My Audio a été modifié par l'audioprothésiste " $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName();
  5345.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$client->getName() . ' ' $client->getLastName(), $subjectMyaudio206);
  5346.         }
  5347.         //     //// == suppression
  5348.         else if ($rdv->getIdEtat()->getId() == 2) {
  5349.             $params = array(
  5350.                 "date" => substr($smsDate010),
  5351.                 "lien" => "{$_ENV['BASE_client']}search",
  5352.                 "heure" => substr($smsDate1115),
  5353.                 "patientName" => $client->getLastName() . ' ' $client->getName(),
  5354.                 'titre' => 'Votre rendez-vous est annulé :',
  5355.                 'centerName' => $rdv->getIdCentre()->getName(),
  5356.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5357.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  5358.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5359.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  5360.                 "clientEmail" => $client->getMail() ?? '',
  5361.                 "clientPhone" => $client->getPhone() ?? '',
  5362.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5363.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  5364.                 'motif' => $rdv->getIdMotif()->getTitre(),
  5365.             );
  5366.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  5367.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  5368.             $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  5369.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  5370.             // creer un mail de notif pour myAudio + créé le template LP | MA | RR - Annlation du RDV - Centre Auditif - MyAudio
  5371.             $subjectMyaudio $rdv->getIdCentre()->getName() . " a annulé un rendez-vous My Audio avec " $client->getName() . ' ' $client->getLastName();
  5372.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$client->getName() . ' ' $client->getLastName(), $subjectMyaudio207);
  5373.         }
  5374.         //notif Audio
  5375.         if ($rdv->getIdEtat()->getId() != 2) {
  5376.             $params = array(
  5377.                 "lienModifier" => "{$_ENV['BASE_logiciel']}rdv",
  5378.                 "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  5379.                 "date" => substr($smsDate010),
  5380.                 "frenchDate" => $frenchDate,
  5381.                 "heure" => substr($smsDate1115),
  5382.                 'motif' => $rdv->getIdMotif()->getTitre(),
  5383.                 'clientPhone' => $client->getPhone(),
  5384.                 'clientNom' => $client->getLastname(),
  5385.                 'clientPrenom' => $client->getName(),
  5386.                 'clientCivilite' => $client->getCivilite(),
  5387.                 'clientPostal' => $client->getPostal(),
  5388.                 'clientMail' => $client->getMail(),
  5389.                 'centerName' => $rdv->getIdCentre()->getName(),
  5390.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5391.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  5392.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5393.                 'idPatient' => $client->getId(),
  5394.                 'proUrl' => "{$_ENV['BASE_logiciel']}",
  5395.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  5396.                 'titre' => 'Votre rendez-vous est modifié pour le :'
  5397.             );
  5398.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  5399.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  5400.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  5401.                 $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  5402.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  5403.             }
  5404.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  5405.                 $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.";
  5406.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  5407.             }
  5408.         } else if ($rdv->getIdEtat()->getId() == 2) {
  5409.             /* $params = array(  
  5410.                     "date" => substr($smsDate, 0, 10),
  5411.                     "lien"=> "{$_ENV['BASE_client']}search",
  5412.                     "heure" =>substr($smsDate, 11, 15),
  5413.                     "patientName" => $client->getLastName(),
  5414.                     'titre' => 'Votre rendez-vous est annulé :',
  5415.                     'centerName' => $rdv->getIdCentre()->getName(),
  5416.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5417.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  5418.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5419.                     'centerPhone' => $rdv->getIdCentre()->getPhone(),
  5420.                     'audioproName' => $rdv->getIdAudio()->getCivilite().' '. $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(),                    
  5421.                     'audioMail' => $rdv->getIdAudio()->getMail(),
  5422.                     'motif' => $rdv->getIdMotif()->getTitre(),
  5423.                 );
  5424.                 $subject = "Rendez-vous My Audio annulé avec " . $rdv->getIdCentre()->getName();
  5425.                 $publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(), $subject, 188 );
  5426.                 $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.";
  5427.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());
  5428.                 */
  5429.         }
  5430.         // delete sms notification     
  5431.         $rdvSms->deleteAssociatedRdvSms($rdv);
  5432.         // delete client device
  5433.         /*$clientDevice = $this->getDoctrine()->getRepository(ClientDevice::class)->findOneBy(['rdv' => $rdv]);
  5434. if($clientDevice)
  5435. {
  5436. if ($client instanceof Client) {
  5437.     $nextRdvs = $this->getDoctrine()
  5438.         ->getRepository(Rdv::class)
  5439.         ->findBy([
  5440.             "id_client" => $rdv->getIdClient(),
  5441.             "id_motif" => ['106', '107', '108', '109'] 
  5442.         ]);
  5443.         $client->setClientStatus(null);
  5444. } elseif ($client instanceof ClientTemp) {
  5445.  $nextRdvs = $this->getDoctrine()
  5446.         ->getRepository(Rdv::class)
  5447.         ->findBy([
  5448.             "id_client_temp" => $rdv->getIdClientTemp(),
  5449.             "id_motif" => ['106', '107', '108', '109'] 
  5450.         ]);
  5451.         $client->setClientStatus(null);
  5452.     } 
  5453.     $locale = 'fr_FR';
  5454.     $fmt = new IntlDateFormatter($locale, IntlDateFormatter::FULL, IntlDateFormatter::NONE);
  5455.     $fmt->setPattern("EEEE dd MMMM yyyy"); 
  5456.     if($nextRdvs){
  5457.     $params = array(  
  5458.                 "title" => "Affectation de votre appareil et programmation de vos rendez-vous",
  5459.                 "centerName" => "{$rdv->getIdCentre()->getName()}",
  5460.                 "audioName" => "{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastName()}",
  5461.                 "centerAddress" => "{$rdv->getIdCentre()->getAddress()}",
  5462.                 "device" => "{$clientDevice->getDevice()->getModel()}",
  5463.                 "ears" => "{$clientDevice->getSettingDevice()->getName()}",
  5464.                 "rdvOneDate" => "{$fmt->format($nextRdvs['0']->getDate())}",
  5465.                 "rdvOneHour" => "{$nextRdvs['0']->getDate()->format('H:i')}",
  5466.                 "rdvTwoDate" => "{$fmt->format($nextRdvs['1']->getDate())}",
  5467.                 "rdvTwoHour" => "{$nextRdvs['1']->getDate()->format('H:i')}",
  5468.                 "rdvThreeDate" => "{$fmt->format($nextRdvs['2']->getDate())}",
  5469.                 "rdvThreeHour" => "{$nextRdvs['2']->getDate()->format('H:i')}",
  5470.                 "rdvFourDate" => "{$fmt->format($nextRdvs['3']->getDate())}",
  5471.                 "rdvFourHour" => "{$nextRdvs['3']->getDate()->format('H:i')}",
  5472.             );
  5473.     
  5474.             $publicFunction->sendEmail($params, $client->getMail(), $client->getName().' '.$client->getLastName(), "Annulation de vos prochains RDV", 162 );
  5475.         }
  5476.     foreach($nextRdvs as $rdv)
  5477.     {
  5478.         $entityManager->remove($rdv);
  5479.     }
  5480.     $entityManager->persist($client);
  5481.     $entityManager->remove($clientDevice);
  5482.     $entityManager->flush();
  5483. }*/
  5484.         // Before deleting, publish the deletion event
  5485.         $this->mercure->publishRdvDeletion($rdv);
  5486.         $entityManager->flush();
  5487.         return new Response(json_encode(([
  5488.             "id" => $rdv->getId(),
  5489.             "motif_id" => $rdv->getIdMotif()->getId(),
  5490.             "motif_libelle" => $rdv->getIdMotif()->getTitre(),
  5491.             "audio_id" => $rdv->getIdAudio()->getId(),
  5492.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  5493.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  5494.             "fullName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastname(),
  5495.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  5496.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  5497.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  5498.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  5499.             "centre_name" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getName() : null,
  5500.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  5501.             "etat_id" => $rdv->getIdEtat()->getId(),
  5502.             "date" => $rdv->getDate(),
  5503.             "comment" => $rdv->getComment(),
  5504.             "note" => $rdv->getNote(),
  5505.             "review" => $rdv->getReview(),
  5506.             "status" => 200,
  5507.         ])));
  5508.     }
  5509.     /**
  5510.      * @Route("/rdv/calendar", name="postRdvCalendar", methods={"POST"})
  5511.      */
  5512.     public function postRdvCalendar(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSmsPublisherInterface $publisher): Response
  5513.     {
  5514.         $data json_decode($request->getContent(), true);
  5515.         if (!isset($data["token"])) {
  5516.             return new Response(json_encode([
  5517.                 "message" => "Pas de token n'a été spécifié",
  5518.                 "status" => 401,
  5519.             ]), 401);
  5520.         }
  5521.         $entityManager $this->getDoctrine()->getManager();
  5522.         /** @var Token */
  5523.         $token $this->getDoctrine()
  5524.             ->getRepository(Token::class)
  5525.             ->findOneBy(['token' => $data["token"]]);
  5526.         if (!$token) {
  5527.             return new Response(json_encode([
  5528.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5529.                 "status" => 404,
  5530.             ]), 404);
  5531.         }
  5532.         // get token age
  5533.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5534.         // if the token if older than 7 days
  5535.         if ($dateDiff->7) {
  5536.             $entityManager->remove($token);
  5537.             $entityManager->flush();
  5538.             return $this->json([
  5539.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5540.                 'path' => 'src/Controller/ClientController.php',
  5541.                 "status" => 401,
  5542.             ], 401);
  5543.         }
  5544.         // makes the rdv
  5545.         $rdv = new Rdv();
  5546.         if ($token->getIdAudio()) {
  5547.             //if the token if for an audio
  5548.             $audio $token->getIdAudio();
  5549.             if ((isset($data["client_id"]))) {
  5550.                 $client $this->getDoctrine()
  5551.                     ->getRepository(Client::class)
  5552.                     ->findOneBy(['id' => $data["client_id"]]);
  5553.             } else {
  5554.                 $client $this->getDoctrine()
  5555.                     ->getRepository(ClientTemp::class)
  5556.                     ->findOneBy(['id' => $data["client_id_temp"]]);
  5557.             }
  5558.             if ($client == null) {
  5559.                 return new Response(json_encode(([
  5560.                     'message' => 'Error, no client found at this id',
  5561.                     'path' => 'src/Controller/RdvController.php',
  5562.                     "status" => 400,
  5563.                 ])), 400);
  5564.             }
  5565.         } elseif ($token->getIdClient()) {
  5566.             //if the token if for a client
  5567.             $client $token->getIdClient();
  5568.             /** @var Audio */
  5569.             $audio $this->getDoctrine()
  5570.                 ->getRepository(Audio::class)
  5571.                 ->findOneBy(['id' => $data["audio_id"]]);
  5572.             if (isset($data["proche_id"])) {
  5573.                 $proche $this->getDoctrine()
  5574.                     ->getRepository(Proches::class)
  5575.                     ->findOneBy(['id' => $data["proche_id"], "id_client" => $client]);
  5576.             }
  5577.             if ($audio == null) {
  5578.                 return new Response(json_encode(([
  5579.                     'message' => 'Error, no audio found at this id',
  5580.                     'path' => 'src/Controller/RdvController.php',
  5581.                     "status" => 400,
  5582.                 ])), 400);
  5583.             }
  5584.         } else {
  5585.             return new Response(json_encode(([
  5586.                 'message' => 'Error, token is not an audio token',
  5587.                 'path' => 'src/Controller/RdvController.php',
  5588.                 "status" => 400,
  5589.             ])), 400);
  5590.         }
  5591.         $rdv->setIdAudio($audio);
  5592.         if (isset($proche)) {
  5593.             $rdv->setIdProche($proche);
  5594.         }
  5595.         if (isset($data["client_id_temp"])) {
  5596.             $rdv->setIdClientTemp($client);
  5597.         } else {
  5598.             $rdv->setIdClient($client);
  5599.         }
  5600.         $rdv->setCacher(0);
  5601.         /** @var Centre */
  5602.         if (isset($data["centre_id"])) {
  5603.             $centre $this->getDoctrine()
  5604.                 ->getRepository(Centre::class)
  5605.                 ->findOneBy(['id' => $data["centre_id"]]);
  5606.             if ($centre == null) {
  5607.                 return new Response(json_encode(([
  5608.                     'message' => 'Error, no centre found at this id',
  5609.                     'path' => 'src/Controller/RdvController.php',
  5610.                     "status" => 400,
  5611.                 ])), 400);
  5612.             }
  5613.             /** @var AudioCentre */
  5614.             $liaison $this->getDoctrine()
  5615.                 ->getRepository(AudioCentre::class)
  5616.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  5617.             if ($liaison == null) {
  5618.                 return new Response(json_encode(([
  5619.                     'message' => 'Error, audio isnt part of the centre',
  5620.                     'path' => 'src/Controller/RdvController.php',
  5621.                     "status" => 400,
  5622.                 ])), 400);
  5623.             }
  5624.             $rdv->setIdCentre($centre);
  5625.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  5626.             // tries to set the lieu if it's an audio indie
  5627.             $lieu $this->getDoctrine()
  5628.                 ->getRepository(Lieu::class)
  5629.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  5630.             if ($lieu == null) {
  5631.                 return new Response(json_encode(([
  5632.                     'message' => 'Error, no lieu found at this id',
  5633.                     'path' => 'src/Controller/RdvController.php',
  5634.                     "status" => 400,
  5635.                 ])), 400);
  5636.             }
  5637.             $rdv->setIdLieu($lieu);
  5638.         } else {
  5639.             return new Response(json_encode(([
  5640.                 'message' => 'Error, no lieu/centre id',
  5641.                 'path' => 'src/Controller/RdvController.php',
  5642.                 "status" => 400,
  5643.             ])), 400);
  5644.         }
  5645.         /** @var Motif */
  5646.         $motif $this->getDoctrine()
  5647.             ->getRepository(Motif::class)
  5648.             ->find($data["motif_id"]);
  5649.         if ($motif == null) {
  5650.             return new Response(json_encode(([
  5651.                 'message' => 'Error, no motif found at this id',
  5652.                 'path' => 'src/Controller/RdvController.php',
  5653.                 "status" => 400,
  5654.             ])), 400);
  5655.         }
  5656.         /** @var AudioMotif */
  5657.         $audioMotif $this->getDoctrine()
  5658.             ->getRepository(AudioMotif::class)
  5659.             ->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
  5660.         if ($audioMotif == null) {
  5661.             return new Response(json_encode(([
  5662.                 'message' => 'Error, no motif of this id found at this audio',
  5663.                 'path' => 'src/Controller/RdvController.php',
  5664.                 "status" => 400,
  5665.             ])), 400);
  5666.         }
  5667.         // remove the taken schedule by rdv to make sure there is no overlap
  5668.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  5669.         if (isset($data["note"])) {
  5670.             $rdv->setNote($data["note"]);
  5671.         }
  5672.         // test if the audio is available
  5673.         /*   if (isset($data["lieu_id"]) && $audio->getIsIndie()){
  5674.             if ($publicFunction->calculScheduleFitDate($audio, $date, $audioMotif->getDuration(), null, $lieu) == false) {
  5675.                 return new Response(json_encode(([
  5676.                     'message' => 'Error, no timestamp found at this time',
  5677.                     'path' => 'src/Controller/RdvController.php',
  5678.                     "status" => 400,
  5679.                 ])), 400);
  5680.             }
  5681.         } else {
  5682.             if ($publicFunction->calculScheduleFitDate($audio, $date, $audioMotif->getDuration(), $centre , null) == true) {
  5683.                 return new Response(json_encode(([
  5684.                     'message' => 'Error, no timestamp found at this time',
  5685.                     'path' => 'src/Controller/RdvController.php',
  5686.                     "status" => 400,
  5687.                 ])), 400);
  5688.             }
  5689.         }*/
  5690.         $rdv->setDate($date);
  5691.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  5692.         /** @var EtatRdv */
  5693.         $etat $this->getDoctrine()
  5694.             ->getRepository(EtatRdv::class)
  5695.             ->findOneBy(['id' => $data["etat_id"]]);
  5696.         if ($etat == null) {
  5697.             return new Response(json_encode(([
  5698.                 'message' => 'Error, no etat found at this id',
  5699.                 'path' => 'src/Controller/RdvController.php',
  5700.                 "status" => 400,
  5701.             ])), 400);
  5702.         }
  5703.         $rdv->setIdEtat($etat);
  5704.         $rdv->setIdMotif($motif);
  5705.         $rdv->setDuration($data["duree"]);
  5706.         $rdv->setIsAbsence($data["is_absence"]);
  5707.         $entityManager $this->getDoctrine()->getManager();
  5708.         $entityManager->persist($rdv);
  5709.         $entityManager->flush();
  5710.         $date $rdv->getDate();
  5711.         $smsDate $date->format('d-m-Y H:i');
  5712.         $locale 'fr_FR';
  5713.         $formatter = new IntlDateFormatter(
  5714.             $locale,
  5715.             IntlDateFormatter::FULL,
  5716.             IntlDateFormatter::SHORT,
  5717.             null,
  5718.             IntlDateFormatter::GREGORIAN,
  5719.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  5720.         );
  5721.         $smsDateLongFormat $formatter->format($date);
  5722.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  5723.         // client notif mail Sms
  5724.         // we send parametre for the trait methid
  5725.         //$params = $this->emailNotificationService->prepareEmailParams($user);
  5726.         // send email notifcation
  5727.         //$this->emailNotificationService->sendEmail($params, 'admin@example.com', 'Nouvelle inscription à My Audio Pro', 1);
  5728.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  5729.         $frenchDate ucfirst($frenchDate);
  5730.         $params = array(
  5731.             "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5732.             "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5733.             "date" => $smsDateLongFormat,
  5734.             "prenom" => $client->getName(),
  5735.             //"heure" => $smsDatee,
  5736.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  5737.             "centerName" => $rdv->getIdCentre()->getName(),
  5738.             "centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  5739.             "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  5740.             "centerCity" => $rdv->getIdCentre()->getCity(),
  5741.             "motif" => $rdv->getIdMotif()->getTitre(),
  5742.             "RdvDate" => substr($smsDate010) . " à "  substr($smsDate1115),
  5743.             "audioName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  5744.             "clientMail" => $client->getMail(),
  5745.             "clientPhone" => $client->getPhone(),
  5746.             'titre' => "Votre rendez-vous est validé le " substr($smsDate010) . " à "  substr($smsDate1115),
  5747.             "address" => $rdv->getIdCentre()->getAddress(),
  5748.             "postal" => $rdv->getIdCentre()->getPostale(),
  5749.             "city" => $rdv->getIdCentre()->getCity(),
  5750.             "clientEmail" => $client->getMail(),
  5751.             "clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
  5752.             "clientAddress" => $client->getAddress(),
  5753.             "clientPostal" => $client->getPostal(),
  5754.             "clientCity" => $client->getCity(),
  5755.             "audioName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  5756.             "frenchDate" => $frenchDate,
  5757.             "heure" => substr($smsDate1115),
  5758.             "centerName" => $rdv->getIdCentre()->getName(),
  5759.             "audioMail" => $rdv->getIdAudio()->getMail(),
  5760.             "modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
  5761.         );
  5762.         $subject "Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  5763.         $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject181);
  5764.         $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.";
  5765.         // $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $client->getPhone());
  5766.         // audio Notif mail SMS
  5767.         /* $params = array(  
  5768.                         "lienModifer" =>"{$_ENV['BASE_logiciel']}rdv",
  5769.                         "lienAnnule"=> "{$_ENV['BASE_logiciel']}rdv",
  5770.                         "date" => substr($smsDate, 0, 10),
  5771.                         "heure" =>substr($smsDate, 11, 15),
  5772.                         'motif' => $rdv->getIdMotif()->getTitre(),
  5773.                         'clientPhone'=> $client->getPhone(),
  5774.                         'clientNom' =>$client->getLastname(),
  5775.                         'clientPrenom' =>$client->getName(),
  5776.                         'clientCivilite' => $client->getCivilite(),
  5777.                         'clientPostal' => $client->getPostal(),
  5778.                         'clientMail' => $client->getMail(),
  5779.                         'centerName' => $rdv->getIdCentre()->getName(),
  5780.                         'centerPostal' => $rdv->getIdCentre()->getPostale(),
  5781.                         'centerCity' => $rdv->getIdCentre()->getCity(),
  5782.                         'centerAddress' => $rdv->getIdCentre()->getAddress(),
  5783.                         'idPatient' => $client->getId(),
  5784.                         'proUrl' => "{$_ENV['BASE_logiciel']}",
  5785.                         'audioproName' => $rdv->getIdAudio()->getCivilite().' '.$rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(),
  5786.                         'titre' => 'Votre rendez-vous est modifié pour le :'
  5787.                     );
  5788.         $subject = "🔀 Rendez-vous My Audio modifié du ". $frenchDate . " à " . substr($smsDate, 11, 15);
  5789.         $publicFunction->sendEmail($params, $rdv->getIdAudio()->getMail(), $rdv->getIdAudio()->getName().' '.$rdv->getIdAudio()->getLastName(), $subject, 186 );
  5790.         $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.";
  5791.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $rdv->getIdAudio()->getPhone());*/
  5792.         // google calendar post
  5793.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  5794.             ->findBy(array('audio' => $audio->getId()));
  5795.         $data['rdv'] = $rdv->getId();
  5796.         $synchronisationCosium $this->getDoctrine()->getRepository(SynchronisationCosium::class)->findOneBy(["audio" => $audio->getId()]);
  5797.         $cosiumCenter $this->getDoctrine()->getRepository(CosiumCenter::class)->findOneBy(["synchronisationCosium" => $synchronisationCosium"center" => $rdv->getIdCentre()]);
  5798.         if ($cosiumCenter) {
  5799.             $this->clientCosiumService->createAgenda($synchronisationCosium$rdv$cosiumCenter);
  5800.         }
  5801.         foreach ($synchronisations as $synchronisation) {
  5802.             if (!$synchronisation->getIsDeleted()) {
  5803.                 try {
  5804.                     $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  5805.                     $googleCalendar->createEvent($synchronisation$data);
  5806.                 } catch (\Exception $e) {
  5807.                     error_log('Error refreshing access token or creating event: ' $e->getMessage());
  5808.                 }
  5809.             }
  5810.         }
  5811.         // create schedule notification sms
  5812.         $rdvSms->storeRdvSmsNotifications($rdv);
  5813.         if ($rdv->getClientDevice()) {
  5814.             $nextRdv $this->getDoctrine()
  5815.                 ->getRepository(Rdv::class)
  5816.                 ->find($rdv->getClientDevice()->getRdv()->getId());
  5817.             if ($nextRdv->getIdClientTemp()) {
  5818.                 $nextRdvs $this->getDoctrine()
  5819.                     ->getRepository(Rdv::class)
  5820.                     ->findBy([
  5821.                         "id_client_temp" => $nextRdv->getIdClientTemp(),
  5822.                         "id_motif" => ['106''107''108''109']
  5823.                     ]);
  5824.             } else {
  5825.                 $nextRdvs $this->getDoctrine()
  5826.                     ->getRepository(Rdv::class)
  5827.                     ->findBy([
  5828.                         "id_client" => $nextRdv->getIdClient(),
  5829.                         "id_motif" => ['106''107''108''109']
  5830.                     ]);
  5831.             }
  5832.             $mappedNextRdvs array_map(function ($rdv) {
  5833.                 return [
  5834.                     'id' => $rdv->getId(),
  5835.                     'date' => $rdv->getDate()->format('d-m-Y'),
  5836.                     'hours' => $rdv->getDate()->format('H:i'),
  5837.                     'duration' => $rdv->getDuration(),
  5838.                     "motif_id" => $rdv->getIdMotif()->getId(),
  5839.                     "motif_titre" => $rdv->getIdMotif()->getTitre(),
  5840.                     "duration" => $rdv->getDuration(),
  5841.                 ];
  5842.             }, $nextRdvs);
  5843.         }
  5844.         // After successfully creating the RDV
  5845.         $this->mercure->publishRdvUpdate($rdv'created');
  5846.         return new Response(json_encode(([
  5847.             "id" => $rdv->getId(),
  5848.             "motif_id" => $rdv->getIdMotif()->getId(),
  5849.             "audio_id" => $rdv->getIdAudio()->getId(),
  5850.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  5851.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  5852.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  5853.             "centerName" => $rdv->getIdCentre()->getName(),
  5854.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  5855.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  5856.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  5857.             "duration" => $data["duree"],
  5858.             "etat_id" => $rdv->getIdEtat()->getId(),
  5859.             "date" => $rdv->getDate(),
  5860.             "clientEtatId" => $client->getClientStatus() ? $client->getClientStatus()->getId() : 0,
  5861.             "isClient" => ($client instanceof Client) ? 0,
  5862.             "device" => $rdv->getClientDevice() ? [
  5863.                 "isDevice" => true,
  5864.                 "deviceID" => $rdv->getClientDevice()->getDevice()->getId(),
  5865.                 "clientDeviceID" => $rdv->getClientDevice()->getId(),
  5866.                 "deviceModel" => $rdv->getClientDevice()->getDevice()->getModel(),
  5867.                 "settingName" => $rdv->getClientDevice()->getSettingDevice()->getName(),
  5868.                 "settingDeviceId" => $rdv->getClientDevice()->getSettingDevice()->getSlug(),
  5869.                 "settingSlug" => $rdv->getClientDevice()->getSettingDevice()->getSlug(),
  5870.                 "nextRdvs" => $mappedNextRdvs
  5871.             ] : [
  5872.                 "isDevice" => false
  5873.             ],
  5874.             "comment" => $rdv->getComment(),
  5875.             "review" => $rdv->getReview(),
  5876.             "note" => $rdv->getNote(),
  5877.             "status" => 200,
  5878.         ])));
  5879.     }
  5880.     /**
  5881.      * @Route("/rdv/absence", name="postAbsenceCalendar", methods={"POST"})
  5882.      */
  5883.     public function postAbsenceCalendar(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendar): Response
  5884.     {
  5885.         $data json_decode($request->getContent(), true);
  5886.         if (!isset($data["token"])) {
  5887.             return new Response(json_encode([
  5888.                 "message" => "Pas de token n'a été spécifié",
  5889.                 "status" => 401,
  5890.             ]), 401);
  5891.         }
  5892.         $entityManager $this->getDoctrine()->getManager();
  5893.         /** @var Token */
  5894.         $token $this->getDoctrine()
  5895.             ->getRepository(Token::class)
  5896.             ->findOneBy(['token' => $data["token"]]);
  5897.         if (!$token) {
  5898.             return new Response(json_encode([
  5899.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  5900.                 "status" => 404,
  5901.             ]), 404);
  5902.         }
  5903.         // get token age
  5904.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  5905.         // if the token if older than 7 days
  5906.         if ($dateDiff->7) {
  5907.             $entityManager->remove($token);
  5908.             $entityManager->flush();
  5909.             return $this->json([
  5910.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  5911.                 'path' => 'src/Controller/ClientController.php',
  5912.                 "status" => 401,
  5913.             ], 401);
  5914.         }
  5915.         // makes the rdv
  5916.         $rdv = new Rdv();
  5917.         $audio $token->getIdAudio();
  5918.         $rdv->setIdAudio($audio);
  5919.         /** @var Centre */
  5920.         if (isset($data["centre_id"])) {
  5921.             $centre $this->getDoctrine()
  5922.                 ->getRepository(Centre::class)
  5923.                 ->findOneBy(['id' => $data["centre_id"]]);
  5924.             if ($centre == null) {
  5925.                 return new Response(json_encode(([
  5926.                     'message' => 'Error, no centre found at this id',
  5927.                     'path' => 'src/Controller/RdvController.php',
  5928.                     "status" => 400,
  5929.                 ])), 400);
  5930.             }
  5931.             /** @var AudioCentre */
  5932.             $liaison $this->getDoctrine()
  5933.                 ->getRepository(AudioCentre::class)
  5934.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  5935.             if ($liaison == null) {
  5936.                 return new Response(json_encode(([
  5937.                     'message' => 'Error, audio isnt part of the centre',
  5938.                     'path' => 'src/Controller/RdvController.php',
  5939.                     "status" => 400,
  5940.                 ])), 400);
  5941.             }
  5942.             $rdv->setIdCentre($centre);
  5943.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  5944.             // tries to set the lieu if it's an audio indie
  5945.             $lieu $this->getDoctrine()
  5946.                 ->getRepository(Lieu::class)
  5947.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  5948.             if ($lieu == null) {
  5949.                 return new Response(json_encode(([
  5950.                     'message' => 'Error, no lieu found at this id',
  5951.                     'path' => 'src/Controller/RdvController.php',
  5952.                     "status" => 400,
  5953.                 ])), 400);
  5954.             }
  5955.             $rdv->setIdLieu($lieu);
  5956.         } else {
  5957.             return new Response(json_encode(([
  5958.                 'message' => 'Error, no lieu/centre id',
  5959.                 'path' => 'src/Controller/RdvController.php',
  5960.                 "status" => 400,
  5961.             ])), 400);
  5962.         }
  5963.         // remove the taken schedule by rdv to make sure there is no overlap
  5964.         $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  5965.         $rdv->setDate($date);
  5966.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  5967.         /** @var EtatRdv */
  5968.         $etat $this->getDoctrine()
  5969.             ->getRepository(EtatRdv::class)
  5970.             ->findOneBy(['id' => $data["etat_id"]]);
  5971.         if ($etat == null) {
  5972.             return new Response(json_encode(([
  5973.                 'message' => 'Error, no etat found at this id',
  5974.                 'path' => 'src/Controller/RdvController.php',
  5975.                 "status" => 400,
  5976.             ])), 400);
  5977.         }
  5978.         $rdv->setIdEtat($etat);
  5979.         $rdv->setDuration($data["duree"]);
  5980.         $rdv->setIsAbsence($data["is_absence"]);
  5981.         $rdv->setMotifAbsence($data["motif"]);
  5982.         $rdv->setColor($data["color"]);
  5983.         $rdv->setNote($data["note"]);
  5984.         $rdv->setCacher(0);
  5985.         $entityManager $this->getDoctrine()->getManager();
  5986.         $entityManager->persist($rdv);
  5987.         $entityManager->flush();
  5988.         // create google calendar absence event
  5989.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  5990.             ->findBy(array('audio' => $audio->getId()));
  5991.         $data['rdv'] = $rdv->getId();
  5992.         $data['motif_absence'] = $rdv->getMotifAbsence() !== '' $rdv->getMotifAbsence() : "Absence";
  5993.         //        dd($data);
  5994.         foreach ($synchronisations as $synchronisation) {
  5995.             if (!$synchronisation->getIsDeleted()) {
  5996.                 try {
  5997.                     $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  5998.                     $googleCalendar->createAbsenceEvent($synchronisation$data);
  5999.                 } catch (\Google\Service\Exception $e) {
  6000.                     if ($e->getCode() === 403 && str_contains($e->getMessage(), 'insufficientPermissions')) {
  6001.                         error_log("Skipped synchronisation ID {$synchronisation->getId()} due to insufficient permissions.");
  6002.                         continue;
  6003.                     }
  6004.                     throw $e;
  6005.                 }
  6006.             }
  6007.         }
  6008.         return new Response(json_encode(([
  6009.             "id" => $rdv->getId(),
  6010.             "audio_id" => $rdv->getIdAudio()->getId(),
  6011.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  6012.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  6013.             "duration" => $data["duree"],
  6014.             "etat_id" => $rdv->getIdEtat()->getId(),
  6015.             "date" => $rdv->getDate(),
  6016.             "status" => 200,
  6017.         ])));
  6018.     }
  6019.     /**
  6020.      * @Route("/rdv/{id}/absence", name="puttAbsenceCalendar", methods={"PUT"})
  6021.      */
  6022.     public function putAbsenceCalendar(Request $requestRdv $rdvPublicFunction $publicFunctionGoogleCalendarService $googleCalendar): Response
  6023.     {
  6024.         $data json_decode($request->getContent(), true);
  6025.         if (!isset($data["token"])) {
  6026.             return new Response(json_encode([
  6027.                 "message" => "Pas de token n'a été spécifié",
  6028.                 "status" => 401,
  6029.             ]), 401);
  6030.         }
  6031.         $entityManager $this->getDoctrine()->getManager();
  6032.         /** @var Token */
  6033.         $token $this->getDoctrine()
  6034.             ->getRepository(Token::class)
  6035.             ->findOneBy(['token' => $data["token"]]);
  6036.         if (!$token) {
  6037.             return new Response(json_encode([
  6038.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6039.                 "status" => 404,
  6040.             ]), 404);
  6041.         }
  6042.         // get token age
  6043.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6044.         // if the token if older than 7 days
  6045.         if ($dateDiff->7) {
  6046.             $entityManager->remove($token);
  6047.             $entityManager->flush();
  6048.             return $this->json([
  6049.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6050.                 'path' => 'src/Controller/ClientController.php',
  6051.                 "status" => 401,
  6052.             ], 401);
  6053.         }
  6054.         // remove the taken schedule by rdv to make sure there is no overlap
  6055.         if (isset($data["date"])) {
  6056.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  6057.             $rdv->setDate($date);
  6058.         }
  6059.         if (isset($data["duree"])) {
  6060.             $rdv->setDuration($data["duree"]);
  6061.         }
  6062.         if (isset($data["motif"])) {
  6063.             $rdv->setMotifAbsence($data["motif"]);
  6064.         }
  6065.         if (isset($data["color"])) {
  6066.             $rdv->setColor($data["color"]);
  6067.         }
  6068.         if (isset($data["note"])) {
  6069.             $rdv->setNote($data["note"]);
  6070.         }
  6071.         $entityManager $this->getDoctrine()->getManager();
  6072.         $entityManager->flush();
  6073.         $data['rdv'] = $rdv->getId();
  6074.         $data['motif_absence'] = $rdv->getMotifAbsence() !== '' $rdv->getMotifAbsence() : "Absence";
  6075.         $data['note'] = $rdv->getNote();
  6076.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  6077.             ->findBy(array('rdv' => $rdv));
  6078.         foreach ($rdvEvents as $rdvEvent) {
  6079.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  6080.             $googleCalendar->updateAbsenceEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  6081.         }
  6082.         return new Response(json_encode(([
  6083.             "id" => $rdv->getId(),
  6084.             "audio_id" => $rdv->getIdAudio()->getId(),
  6085.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  6086.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  6087.             "duration" => $rdv->getDuration(),
  6088.             "etat_id" => $rdv->getIdEtat()->getId(),
  6089.             "date" => $rdv->getDate(),
  6090.             "status" => 200,
  6091.         ])));
  6092.     }
  6093.     /**
  6094.      * @Route("/rdv/{id}/calendar", name="editRdvCalendarByID", methods={"PUT"})
  6095.      */
  6096.     public function editRdvCalendarByID(SmsHandler $smsHandlerRdv $rdvRequest $requestGoogleCalendarService $googleCalendarPublicFunction $publicFunctionRdvSmsService $rdvSms): Response
  6097.     {
  6098.         $pastDate $rdv->getDate();
  6099.         $data json_decode($request->getContent(), true);
  6100.         $entityManager $this->getDoctrine()->getManager();
  6101.         if (!isset($data["token"])) {
  6102.             return new Response(json_encode([
  6103.                 "message" => "Pas de token n'a été spécifié",
  6104.                 "status" => 401,
  6105.             ]), 401);
  6106.         }
  6107.         /** @var Token */
  6108.         $token $this->getDoctrine()
  6109.             ->getRepository(Token::class)
  6110.             ->findOneBy(['token' => $data["token"]]);
  6111.         if (!$token) {
  6112.             return new Response(json_encode([
  6113.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6114.                 "status" => 404,
  6115.             ]), 404);
  6116.         }
  6117.         // get token age
  6118.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6119.         // if the token if older than 7 days
  6120.         if ($dateDiff->7) {
  6121.             $entityManager->remove($token);
  6122.             $entityManager->flush();
  6123.             return $this->json([
  6124.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6125.                 'path' => 'src/Controller/ClientController.php',
  6126.                 "status" => 401,
  6127.             ], 401);
  6128.         }
  6129.         if ($rdv->getIdClient() != $token->getIdClient() && $rdv->getIdAudio() != $token->getIdAudio()) {
  6130.             return new Response(json_encode([
  6131.                 "message" => "Vous n'êtes pas authorisé à modifier ce rendez-vous",
  6132.                 "status" => 404,
  6133.             ]), 404);
  6134.         }
  6135.         if (isset($data["etat_id"])) {
  6136.             $etat $this->getDoctrine()
  6137.                 ->getRepository(EtatRdv::class)
  6138.                 ->findOneBy(['id' => $data["etat_id"]]);
  6139.             if ($etat == null) {
  6140.                 return new Response(json_encode(([
  6141.                     'message' => 'Error, no etat found at this id',
  6142.                     'path' => 'src/Controller/TrustedUserController.php',
  6143.                     "status" => 400,
  6144.                 ])), 400);
  6145.             }
  6146.             $rdv->setIdEtat($etat);
  6147.         }
  6148.         if (isset($data["audio_id"])) {
  6149.             $audio $this->getDoctrine()
  6150.                 ->getRepository(Audio::class)
  6151.                 ->findOneBy(['id' => $data["audio_id"]]);
  6152.             if ($audio == null) {
  6153.                 return new Response(json_encode(([
  6154.                     'message' => 'Error, no audio found at this id',
  6155.                     'path' => 'src/Controller/TrustedUserController.php',
  6156.                     "status" => 400,
  6157.                 ])), 400);
  6158.             }
  6159.             $rdv->setIdAudio($audio);
  6160.         }
  6161.         if (isset($data["motif_id"])) {
  6162.             $motif $this->getDoctrine()
  6163.                 ->getRepository(Motif::class)
  6164.                 ->find($data["motif_id"]);
  6165.             if ($motif == null) {
  6166.                 return new Response(json_encode(([
  6167.                     'message' => 'Error, no motif found at this id',
  6168.                     'path' => 'src/Controller/TrustedUserController.php',
  6169.                     "status" => 400,
  6170.                 ])), 400);
  6171.             }
  6172.             $rdv->setIdMotif($motif);
  6173.         }
  6174.         if (isset($data["client_id"])) {
  6175.             $client $this->getDoctrine()
  6176.                 ->getRepository(Client::class)
  6177.                 ->findOneBy(['id' => $data["client_id"]]);
  6178.             if ($client == null) {
  6179.                 return new Response(json_encode(([
  6180.                     'message' => 'Error, no client found at this id',
  6181.                     'path' => 'src/Controller/TrustedUserController.php',
  6182.                     "status" => 400,
  6183.                 ])), 400);
  6184.             }
  6185.             $rdv->setIdClient($client);
  6186.         }
  6187.         if (isset($data["date"])) {
  6188.             // remove the taken schedule by rdv to make sure there is no overlap
  6189.             $date \DateTime::createFromFormat("d/m/Y H:i"$data["date"]);
  6190.             $audioMotif $this->getDoctrine()
  6191.                 ->getRepository(AudioMotif::class)
  6192.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  6193.             if ($audioMotif == null) {
  6194.                 return new Response(json_encode(([
  6195.                     'message' => 'Error, no motif of this id found at this audio',
  6196.                     'path' => 'src/Controller/RdvController.php',
  6197.                     "status" => 400,
  6198.                 ])), 400);
  6199.             }
  6200.             if ($rdv->getIdAudio()->getIsIndie()) {
  6201.                 if ($rdv->getIdCentre()) {
  6202.                     // regular centre audio indie
  6203.                     /** @var AudioCentre */
  6204.                     $liaison $this->getDoctrine()
  6205.                         ->getRepository(AudioCentre::class)
  6206.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  6207.                     if ($liaison == null) {
  6208.                         return new Response(json_encode(([
  6209.                             'message' => 'Error, audio isnt part of the centre',
  6210.                             'path' => 'src/Controller/RdvController.php',
  6211.                             "status" => 400,
  6212.                         ])), 400);
  6213.                     }
  6214.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  6215.                         return new Response(json_encode(([
  6216.                             'message' => 'Error, no horaire found for this audio',
  6217.                             'path' => 'src/Controller/RdvController.php',
  6218.                             "status" => 400,
  6219.                         ])), 400);
  6220.                     }
  6221.                 } else {
  6222.                     // lieu audio indie
  6223.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  6224.                         return new Response(json_encode(([
  6225.                             'message' => 'Error, no horaire found for this audio',
  6226.                             'path' => 'src/Controller/RdvController.php',
  6227.                             "status" => 400,
  6228.                         ])), 400);
  6229.                     }
  6230.                 }
  6231.             } else {
  6232.                 // regular centre
  6233.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  6234.                     return new Response(json_encode(([
  6235.                         'message' => 'Error, no horaire found for this audio',
  6236.                         'path' => 'src/Controller/RdvController.php',
  6237.                         "status" => 400,
  6238.                     ])), 400);
  6239.                 }
  6240.             }
  6241.             $rdv->setDate($date);
  6242.         }
  6243.         if (isset($data["comment"]) && $token->getIdClient()) {
  6244.             $rdv->setComment($data["comment"]);
  6245.         }
  6246.         if (isset($data["review"]) && $token->getIdClient()) {
  6247.             $rdv->setReview($data["review"]);
  6248.         }
  6249.         if (isset($data["note"])) {
  6250.             $rdv->setNote($data["note"]);
  6251.         }
  6252.         $entityManager->flush();
  6253.         $date $rdv->getDate();
  6254.         $smsDate $date->format('d-m-Y H:i');
  6255.         $oldDate $pastDate->format('d-m-Y H:i');
  6256.         $locale 'fr_FR';
  6257.         $formatter = new IntlDateFormatter(
  6258.             $locale,
  6259.             IntlDateFormatter::FULL,
  6260.             IntlDateFormatter::SHORT,
  6261.             null,
  6262.             IntlDateFormatter::GREGORIAN,
  6263.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  6264.         );
  6265.         $smsDateLongFormat $formatter->format($date);
  6266.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  6267.         $frenchDate ucfirst($frenchDate);
  6268.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  6269.         // notif client
  6270.         if ($rdv->getIdEtat()->getId() != 2) {
  6271.             $params = array(
  6272.                 "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  6273.                 "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  6274.                 "date" => $smsDateLongFormat,
  6275.                 "heure" => substr($smsDate1115),
  6276.                 "motif" => $rdv->getIdMotif()->getTitre(),
  6277.                 "centerName" => $rdv->getIdCentre()->getName(),
  6278.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  6279.                 "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  6280.                 "audioMail" => $rdv->getIdAudio()->getMail(),
  6281.                 "centerPhone" => $rdv->getIdCentre()->getPhone(),
  6282.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  6283.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  6284.                 'titre' => 'Votre rendez-vous est modifié pour le',
  6285.                 'frenchDate' => $frenchDate,
  6286.             );
  6287.             $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  6288.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  6289.             if ($data["sms"]) {
  6290.                 $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.";
  6291.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  6292.             }
  6293.         }
  6294.         //     //// == suppression
  6295.         else if ($rdv->getIdEtat()->getId() == 2) {
  6296.             $params = array(
  6297.                 "date" => substr($smsDate010),
  6298.                 "lien" => "{$_ENV['BASE_client']}search",
  6299.                 "heure" => substr($smsDate1115),
  6300.                 "patientName" => $client->getLastName(),
  6301.                 'titre' => 'Votre rendez-vous est annulé :',
  6302.                 'centerName' => $rdv->getIdCentre()->getName(),
  6303.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  6304.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  6305.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  6306.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  6307.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6308.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  6309.                 'motif' => $rdv->getIdMotif()->getTitre(),
  6310.             );
  6311.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  6312.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  6313.             if ($data["sms"]) {
  6314.                 $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  6315.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  6316.             }
  6317.         }
  6318.         //notif Audio
  6319.         if ($rdv->getIdEtat()->getId() != 2) {
  6320.             if ($data["sms"]) {
  6321.                 $params = array(
  6322.                     "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  6323.                     "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  6324.                     "date" => substr($smsDate010),
  6325.                     "frenchDate" => $frenchDate,
  6326.                     "heure" => substr($smsDate1115),
  6327.                     'motif' => $rdv->getIdMotif()->getTitre(),
  6328.                     'clientPhone' => $client->getPhone(),
  6329.                     'clientNom' => $client->getLastname(),
  6330.                     'clientPrenom' => $client->getName(),
  6331.                     'clientCivilite' => $client->getCivilite(),
  6332.                     'clientPostal' => $client->getPostal(),
  6333.                     'clientMail' => $client->getMail(),
  6334.                     'centerName' => $rdv->getIdCentre()->getName(),
  6335.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  6336.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  6337.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  6338.                     'idPatient' => $client->getId(),
  6339.                     'proUrl' => "{$_ENV['BASE_logiciel']}",
  6340.                     'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6341.                     'titre' => 'Votre rendez-vous est modifié pour le :'
  6342.                 );
  6343.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  6344.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  6345.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  6346.                     $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  6347.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  6348.                 }
  6349.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  6350.                     $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.";
  6351.                     // $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  6352.                 }
  6353.             }
  6354.         } else if ($rdv->getIdEtat()->getId() == 2) {
  6355.             if ($data["sms"]) {
  6356.                 $params = array(
  6357.                     "date" => substr($smsDate010),
  6358.                     "lien" => "{$_ENV['BASE_client']}search",
  6359.                     "heure" => substr($smsDate1115),
  6360.                     "patientName" => $client->getLastName(),
  6361.                     'titre' => 'Votre rendez-vous est annulé :',
  6362.                     'centerName' => $rdv->getIdCentre()->getName(),
  6363.                     'centerPostal' => $rdv->getIdCentre()->getPostale(),
  6364.                     'centerCity' => $rdv->getIdCentre()->getCity(),
  6365.                     'centerAddress' => $rdv->getIdCentre()->getAddress(),
  6366.                     'centerPhone' => $rdv->getIdCentre()->getPhone(),
  6367.                     'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  6368.                     'audioMail' => $rdv->getIdAudio()->getMail(),
  6369.                     'motif' => $rdv->getIdMotif()->getTitre(),
  6370.                 );
  6371.                 $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  6372.                 $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  6373.                 if ($rdv->getIdAudio()->getModifRdvMail()) {
  6374.                     $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  6375.                     $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject188);
  6376.                 }
  6377.                 if ($rdv->getIdAudio()->getModifRdvSms()) {
  6378.                     $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.";
  6379.                     //$publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb", $sms, $phoneAudio);
  6380.                 }
  6381.             }
  6382.         }
  6383.         /* generate sms notif on update */
  6384.         // update sms notification     
  6385.         $rdvSms->updateRdvSms($rdv);
  6386.         // google calendar update
  6387.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  6388.             ->findBy(array('audio' => $rdv->getIdAudio()));
  6389.         $data['rdv'] = $rdv->getId();
  6390.         $data['motif_id'] = $rdv->getIdMotif();
  6391.         $data['note'] = $rdv->getNote();
  6392.         if ($rdv->getIdClient() !== null) {
  6393.             $data["client_id"] = $rdv->getIdClient()->getId();
  6394.         }
  6395.         if ($rdv->getIdClientTemp() !== null) {
  6396.             $data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
  6397.         }
  6398.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  6399.             ->findBy(array('rdv' => $rdv));
  6400.         foreach ($rdvEvents as $rdvEvent) {
  6401.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  6402.             $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  6403.         }
  6404.         return new Response(json_encode(([
  6405.             "id" => $rdv->getId(),
  6406.             "motif_id" => $rdv->getIdMotif()->getId(),
  6407.             "audio_id" => $rdv->getIdAudio()->getId(),
  6408.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  6409.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  6410.             "fullName" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  6411.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  6412.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  6413.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  6414.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  6415.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  6416.             "centre_id" => $rdv->getIdCentre()->getId(),
  6417.             "centerName" => $rdv->getIdCentre()->getName(),
  6418.             "etat_id" => $rdv->getIdEtat()->getId(),
  6419.             "date" => $rdv->getDate(),
  6420.             "comment" => $rdv->getComment(),
  6421.             "note" => $rdv->getNote(),
  6422.             "review" => $rdv->getReview(),
  6423.             "status" => 200,
  6424.         ])));
  6425.     }
  6426.     /**
  6427.      * @Route("/rdv/{id}/absence", name="deletetAbsenceCalendar", methods={"DELETE"})
  6428.      */
  6429.     public function deletetAbsenceCalendar(Request $requestRdv $rdvGoogleCalendarService $googleCalendar): Response
  6430.     {
  6431.         $data json_decode($request->getContent(), true);
  6432.         if (!isset($data["token"])) {
  6433.             return new Response(json_encode([
  6434.                 "message" => "Pas de token n'a été spécifié",
  6435.                 "status" => 401,
  6436.             ]), 401);
  6437.         }
  6438.         $entityManager $this->getDoctrine()->getManager();
  6439.         /** @var Token */
  6440.         $token $this->getDoctrine()
  6441.             ->getRepository(Token::class)
  6442.             ->findOneBy(['token' => $data["token"]]);
  6443.         if (!$token) {
  6444.             return new Response(json_encode([
  6445.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  6446.                 "status" => 404,
  6447.             ]), 404);
  6448.         }
  6449.         // get token age
  6450.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  6451.         // if the token if older than 7 days
  6452.         if ($dateDiff->7) {
  6453.             $entityManager->remove($token);
  6454.             $entityManager->flush();
  6455.             return $this->json([
  6456.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  6457.                 'path' => 'src/Controller/ClientController.php',
  6458.                 "status" => 401,
  6459.             ], 401);
  6460.         }
  6461.         // delete google agenda event
  6462.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  6463.             ->findBy(array('rdv' => $rdv));
  6464.         //dd($rdvEvents);
  6465.         foreach ($rdvEvents as $rdvEvent) {
  6466.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  6467.             $googleCalendar->deleteEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId());
  6468.             $entityManager->remove($rdvEvent);
  6469.             $entityManager->flush();
  6470.         }
  6471.         $entityManager->remove($rdv);
  6472.         $entityManager->flush();
  6473.         return new Response(json_encode(([
  6474.             "message" => "Absence Supprime",
  6475.             "status" => 200,
  6476.         ])));
  6477.     }
  6478.     /**
  6479.      * @Route("/rdvs/facturation/rdv", name="getMyRDV", methods={"GET"})
  6480.      */
  6481.     public function getMyRDV(Request $request): Response
  6482.     {
  6483.         /* $date = new DateTime();
  6484.         $minutes_to_add = 10;
  6485.         $date->add(new DateInterval('PT' . $minutes_to_add . 'M'));
  6486.         $date->setTimezone(new DateTimeZone('Europe/Paris'));
  6487.         $currentDate = $date->format('Y-m-d H:i:00');
  6488.         $toSend = $this->getDoctrine()->getRepository(Rdv::class)
  6489.             ->findRdvsIn10Mins($currentDate); 
  6490.         */
  6491.     }
  6492.     /**
  6493.      * @Route("/rdvs/facturation/lead", name="getMyLead", methods={"GET"})
  6494.      */
  6495.     public function getMyLead(Request $request): Response {}
  6496.     /**
  6497.      * @Route("/rdvs/total-count", name="getRdvCount", methods={"GET"})
  6498.      */
  6499.     public function getRdvCount(Request $request): Response
  6500.     {
  6501.         $rdvs $this->getDoctrine()->getRepository(Rdv::class)->findAll();
  6502.         return new Response(count($rdvs));
  6503.     }
  6504.     /**
  6505.      * @Route("/admin/update-relance/{id}", name="admin_update_relance", methods={"POST"})
  6506.      */
  6507.     public function updateRelance(Request $requestLeadRdv $leadEntityManagerInterface $em): JsonResponse
  6508.     {
  6509.         $data json_decode($request->getContent(), true);
  6510.         $relanceCount $data['relanceCount'] ?? null;
  6511.         if ($relanceCount !== null) {
  6512.             $lead->setRelanceCallCount((int)$relanceCount);
  6513.             $em->flush();
  6514.             return new JsonResponse(['success' => true]);
  6515.         }
  6516.         return new JsonResponse(['success' => false], 400);
  6517.     }
  6518.     /**
  6519.      * @Route("/rdv/lead", name="postLeadRdv", methods={"POST"})
  6520.      */
  6521.     public function postLeadRdv(Request $requestEntityManagerInterface $entityManagerPublicFunction $publicFunctionGoogleCalendarService $googleCalendar): Response
  6522.     {
  6523.         $data json_decode($request->getContent(), true);
  6524.         $today = new DateTime();
  6525.         try {
  6526.             $client null;
  6527.             // Gestion du client via token ou création
  6528.             if (!empty($data['clientToken'])) {
  6529.                 $token $entityManager->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
  6530.                 $client $token $token->getIdClient() : null;
  6531.             } elseif (!empty($data['client'])) {
  6532.                 $clientData $this->createOrGetClient($data['client']);
  6533.                 $client $entityManager->getRepository(Client::class)->find($clientData['id']);
  6534.             }
  6535.             if (!$client) {
  6536.                 return $this->json(["status" => 400"message" => "Client non trouvé ou invalide"], 400);
  6537.             }
  6538.             // Création du rendez-vous LeadRdv
  6539.             $rdvLead = new LeadRdv();
  6540.             $rdvLead->setClient($client);
  6541.             if (isset($data['titleLead'])) {
  6542.                 $rdvLead->setTitleLead($data['titleLead']);
  6543.             }
  6544.             if (isset($data['rangeAge'])) {
  6545.                 $rdvLead->setRangeAge($data['rangeAge']);
  6546.             }
  6547.             if (isset($data['situations'])) {
  6548.                 $rdvLead->setSituationsGene($data['situations']);
  6549.             }
  6550.             if (isset($data['equipe'])) {
  6551.                 $rdvLead->setEquipeAppareil($data['equipe']);
  6552.             }
  6553.             if (isset($data['durationEquipe'])) {
  6554.                 $rdvLead->setDurationEquipeAppareil($data['durationEquipe']);
  6555.             }
  6556.             if (isset($data['bilanAuditif'])) {
  6557.                 $rdvLead->setBilanAuditif($data['bilanAuditif']);
  6558.             }
  6559.             if (isset($data['ordonance'])) {
  6560.                 $rdvLead->setOrdonance($data['ordonance']);
  6561.             }
  6562.             if (isset($data['dateOrdonance'])) {
  6563.                 $rdvLead->setDateOrdonance($data['dateOrdonance']);
  6564.             }
  6565.             if (isset($data['canMove'])) {
  6566.                 $rdvLead->setCanMove($data['canMove']);
  6567.             }
  6568.             if (isset($data['traffic_source'])) {
  6569.                 $rdvLead->setTrafficSource($data['traffic_source']);
  6570.             }
  6571.             if (isset($data['article_name'])) {
  6572.                 $rdvLead->setTrafficLpVersion($data['article_name']);
  6573.             }
  6574.             if (isset($data['lp_version'])) {
  6575.                 $rdvLead->setTrafficArticleName($data['lp_version']);
  6576.             }
  6577.             if (isset($data['isNewLp'])) {
  6578.                 $rdvLead->setIsNewLp($data['isNewLp']);
  6579.                 $leadStatus $entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'demande_contact']);
  6580.                 if ($leadStatus) {
  6581.                     $rdvLead->setLeadStatus($leadStatus);
  6582.                 }
  6583.             }
  6584.             $rdvLead->setDate($today);
  6585.             if (!empty($data['audio'])) {
  6586.                 $audio $entityManager->getRepository(Audio::class)->find($data['audio']);
  6587.                 if ($audio) {
  6588.                     $rdvLead->setAudio($audio);
  6589.                 }
  6590.             }
  6591.             if ($client->getPostal()) {
  6592.                 $centerCount $this->getMatchingCentresCount($client->getPostal());
  6593.                 $rdvLead->setCentersCount($centerCount);
  6594.                 if ($centerCount == 0) {
  6595.                     $leadStatus $entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'hors_zone']);
  6596.                     if ($leadStatus) {
  6597.                         $rdvLead->setLeadStatus($leadStatus);
  6598.                     }
  6599.                 }
  6600.             }
  6601.             // Création du Token
  6602.             $tokenString $publicFunction->generateRandomString(30);
  6603.             $token = (new Token())
  6604.                 ->setCreationDate(new DateTime())
  6605.                 ->setToken($tokenString)
  6606.                 ->setIdClient($client);
  6607.             $entityManager->persist($rdvLead);
  6608.             $entityManager->persist($token);
  6609.             $entityManager->flush();
  6610.             return $this->json([
  6611.                 "id" => $client->getId(),
  6612.                 "idRdvLead" => $rdvLead->getId(),
  6613.                 "name" => $client->getName(),
  6614.                 "lastname" => $client->getLastname(),
  6615.                 "token" => $tokenString,
  6616.                 "code" => $clientData['password'],
  6617.                 "postalCode" => $client->getPostal() ?? null,
  6618.                 "status" => 200,
  6619.             ]);
  6620.         } catch (\Exception $e) {
  6621.             return $this->json(["status" => 500"message" => $e->getMessage()], 500);
  6622.         }
  6623.     }
  6624.     /**
  6625.      * @Route("/testGenerateVoice", name="testGenerateVoice", methods={"GET"})
  6626.      */
  6627.     public function testGenerateVoice(AppointmentCallService $service): Response
  6628.     {
  6629.         // TEST LOCAL$rdv = $this->entityManager->getRepository(Rdv::class)->find(6653);
  6630.         $rdv $this->entityManager->getRepository(Rdv::class)->find(2306);
  6631.         $lead $this->entityManager->getRepository(LeadRdv::class)->find(496);
  6632.         // $service->handleCallCenterAfterRdv(
  6633.         //     $rdv
  6634.         // );
  6635.         // $service->handleReminderCallToPatient(
  6636.         //     $rdv
  6637.         // );
  6638.         $service->handleEquipmentStatusCall($rdv);
  6639.         // $service->handleReminderCallToPatientOneHourBefore(
  6640.         //     $rdv
  6641.         // );
  6642.         // $service->handleCallToPatientAfterRdv(
  6643.         //     $rdv
  6644.         // );
  6645.         // $service->handleFollowupCall15Days($rdv);
  6646.         // $service->handleNewLeadCall($lead, "+33743393532");
  6647.         // $service->handleFollowupCall31Days($rdv);
  6648.         return new Response(json_encode([
  6649.             "status" => 200,
  6650.         ]), 200, ['Content-Type' => 'application/json']);
  6651.     }
  6652.     /**
  6653.      * @Route("/testSynthflow", name="testSynthflow", methods={"POST"})
  6654.      */
  6655.     public function testSynthflow(SynthflowService $service): Response
  6656.     {
  6657.         // TEST LOCAL
  6658.         $lead $this->entityManager->getRepository(LeadRdv::class)->find(496);
  6659.         $service->initiateCall($lead);
  6660.         return new Response(json_encode([
  6661.             "status" => 200,
  6662.         ]), 200, ['Content-Type' => 'application/json']);
  6663.     }
  6664.     /**
  6665.      * Private method to create a new client or get existing one by phone
  6666.      */
  6667.     private function createOrGetClient(array $data): array
  6668.     {
  6669.         $clientRepository $this->entityManager->getRepository(Client::class);
  6670.         // check sur le mail et phone
  6671.         $existingClient $clientRepository->findOneBy(['mail' => $data['email']]);
  6672.         if ($existingClient) {
  6673.             if ($existingClient->getPostal() !== $data['postalCode']) {
  6674.                 $existingClient->setPostal($data['postalCode']);
  6675.                 $this->entityManager->persist($existingClient);
  6676.                 $this->entityManager->flush();
  6677.             }
  6678.             return ['id' => $existingClient->getId(), 'password' => 'Votre mot de passe'];
  6679.         }
  6680.         $randomPassword $this->generateRandomPassword(12);
  6681.         $client = new Client();
  6682.         $client->setLastname($data['lastname']);
  6683.         $client->setBirthdate(null);
  6684.         $client->setName($data['firstname']);
  6685.         $client->setPhone($data['phone']);
  6686.         $client->setMail($data['email']);
  6687.         $client->setSignupDate(new \DateTime());
  6688.         $client->setPassword(password_hash($randomPasswordPASSWORD_DEFAULT));
  6689.         $client->setPostal($data['postalCode']);
  6690.         $client->setAddress($data['address'] ?? null);
  6691.         $client->setCity($data['city'] ?? null);
  6692.         $client->setDesactivate(false);
  6693.         if (isset($data['civilite'])) {
  6694.             $civilite = ($data['civilite'] === 'Homme') ? 'Monsieur' 'Madame';
  6695.             $client->setCivilite($civilite);
  6696.         }
  6697.         $this->entityManager->persist($client);
  6698.         $this->entityManager->flush();
  6699.         return ['id' => $client->getId(), 'password' => $randomPassword];
  6700.     }
  6701.     private function generateRandomPassword($length 10): string
  6702.     {
  6703.         return bin2hex(random_bytes($length 2));
  6704.     }
  6705.     private function getMatchingCentresCount($clientPostal): int
  6706.     {
  6707.         // Récupérer les coordonnées GPS du code postal du client
  6708.         $clientCoordinates $this->entityManager
  6709.             ->getRepository(RegionDepartment::class)
  6710.             ->findOneBy(['codePostal' => $clientPostal]);
  6711.         $clientLat $clientCoordinates $clientCoordinates->getLatitude() : null;
  6712.         $clientLon $clientCoordinates $clientCoordinates->getLongitude() : null;
  6713.         $centres $this->entityManager->getRepository(Centre::class)->findAll();
  6714.         $count 0;
  6715.         foreach ($centres as $centre) {
  6716.             if ($centre->getZoneKm()) {
  6717.                 $latitude $centre->getLatitude();
  6718.                 $longitude $centre->getLongitude();
  6719.                 $radius $centre->getZoneKm();
  6720.                 $postals $this->entityManager->getRepository(RegionDepartment::class)->findPostalsWithinRadius($latitude$longitude$radius);
  6721.                 $postalCodes array_values(array_unique(array_column($postals'code_postal')));
  6722.                 if (in_array($clientPostal$postalCodes)) {
  6723.                     $count++;
  6724.                 }
  6725.             }
  6726.         }
  6727.         return $count;
  6728.     }
  6729.     /**
  6730.      * @Route("/rdv/send-map", name="getRdvMap", methods={"POST"})
  6731.      */
  6732.     public function sendEmailWithMap(Request $requestPublicFunction $publicFunction): Response
  6733.     {
  6734.         $data json_decode($request->getContent(), true);
  6735.         $mail "";
  6736.         $name "";
  6737.         $centre "";
  6738.         if (isset($data['clientToken'])) {
  6739.             $token $this->getDoctrine()->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
  6740.             $client $token->getIdClient();
  6741.             $mail $client->getMail();
  6742.             $name $client->getLastname() . " " $client->getName();
  6743.             $centre $this->getDoctrine()->getRepository(Centre::class)->findOneBy(['id' => $data['centre']['id']]);
  6744.         } else {
  6745.             $mail $data['email'];
  6746.             $name $data['name'];
  6747.         }
  6748.         $locale 'fr_FR';
  6749.         $dateTime DateTime::createFromFormat('d/m/Y H:i'$data['date']);
  6750.         if ($dateTime) {
  6751.             $fmt = new IntlDateFormatter($localeIntlDateFormatter::FULLIntlDateFormatter::NONE);
  6752.             $fmt->setPattern("EEEE dd MMMM");
  6753.             $formattedDate ucfirst($fmt->format($dateTime));
  6754.         } else {
  6755.             $formattedDate "Date invalide";
  6756.         }
  6757.         $params = [
  6758.             'date' => $data['date'],
  6759.             'time' => $data['time'],
  6760.             'frenchDate' => $formattedDate,
  6761.             'clientAddress' => $data['address'],
  6762.             'centerName' => $centre->getName(),
  6763.             'centerAddress' => $centre->getAddress(),
  6764.             'centerPostal' => $centre->getPostale(),
  6765.             'centerCity' => $centre->getCity(),
  6766.             'start' => $data['start'],
  6767.             'end' => $data['end'],
  6768.             'urlApi' => "{$_ENV['BASE_client']}",
  6769.         ];
  6770.         $publicFunction->sendEmail($params$mail$name"Votre Rendez-vous My Audio"198);
  6771.         return new Response(json_encode([
  6772.             "status" => 200,
  6773.             "params" => $params,
  6774.         ]), 200, ['Content-Type' => 'application/json']);
  6775.     }
  6776.     /**
  6777.      * @Route("/rdv/cantmove", name="notifCantMove", methods={"POST"})
  6778.      */
  6779.     public function notifCantMove(Request $requestPublicFunction $publicFunction): Response
  6780.     {
  6781.         $data json_decode($request->getContent(), true);
  6782.         $email "lead.myaudio@gmail.com";
  6783.         $centre "";
  6784.         $type "My Audio";
  6785.         $details "";
  6786.         $picto "❌";
  6787.         $ordo "sans ordo";
  6788.         $subject "";
  6789.         if (isset($data['ordonance'])) {
  6790.             if ($data["ordonance"] == "oui") {
  6791.                 $ordo "avec ordo";
  6792.             }
  6793.         } else {
  6794.             $ordo "";
  6795.         }
  6796.         if (isset($data['centre'])) {
  6797.             $centre $data['centre'];
  6798.             $subject $picto " Lead - demande de contact ne pouvant pas se déplacer " $data['postal'] . " " $ordo;
  6799.         } else {
  6800.             $centre "";
  6801.             $type "Hors Zone";
  6802.             $details "Pas de centre dans la zone";
  6803.             $subject $picto " Lead Hors Zone " $data['postal'] . " " $ordo " ne pouvant pas se déplacer";
  6804.         }
  6805.         $responses = [
  6806.             'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
  6807.             'situations' => isset($data['situations']) ? $data['situations'] : null,
  6808.             'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
  6809.             'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
  6810.             'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
  6811.             'ordonance' => isset($data['ordonance']) ? $data['ordonance'] : null,
  6812.             'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
  6813.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  6814.         ];
  6815.         $department $this->getDepartmentFromPostalCode($data['address']);
  6816.         $data['departmentCode'] = $department['departmentCode'];
  6817.         $data['departmentName'] = $department['departmentName'];
  6818.         $data['regionName'] = $department['regionName'];
  6819.         $data['city'] = $department['city'];
  6820.         $params = [
  6821.             'date' => $data['date'],
  6822.             'time' => $data['time'],
  6823.             'address' => $data['address'],
  6824.             'centre' => $centre,
  6825.             'type' => $type,
  6826.             'details' => $details,
  6827.             'responses' => $responses,
  6828.             'name' => $data['name'],
  6829.             'civilite' => $data['civilite'],
  6830.             'nom' => $data['firstname'],
  6831.             'prenom' => $data['lastname'],
  6832.             'codePostal' => $data['address'],
  6833.             'telephone' => $data['phone'],
  6834.             'email' => $data['email'],
  6835.             'departement' => $data['departmentName'],
  6836.             'ville' => $data['city'],
  6837.             'region' => $data['regionName'],
  6838.             'trangeAge' => isset($data['rangAge']) ? $data['rangAge'] : null,
  6839.             'situationVecu' => isset($data['situations']) ? implode(', '$data['situations']) : null,
  6840.             'dejaEquipe' => isset($data['equipeAppareil']) ? $data['equipeAppareil'] : null,
  6841.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  6842.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  6843.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  6844.         ];
  6845.         $publicFunction->sendEmail($params$email$data['name'], $subject208);
  6846.         return new Response(json_encode([
  6847.             "status" => 200,
  6848.         ]), 200, ['Content-Type' => 'application/json']);
  6849.     }
  6850.     /**
  6851.      * @Route("/rdv/cantmove/v2", name="notifCantMoveV2", methods={"POST"})
  6852.      */
  6853.     public function notifCantMoveV2(Request $requestPublicFunction $publicFunction): Response
  6854.     {
  6855.         $data json_decode($request->getContent(), true);
  6856.         $email "lead.myaudio@gmail.com";
  6857.         $centre "";
  6858.         $type "My Audio";
  6859.         $details "";
  6860.         $picto "❌";
  6861.         $subject "";
  6862.         $audio "";
  6863.         $subject $picto " Lead ne pouvant pas se déplacer";
  6864.         $department $this->getDepartmentFromPostalCode($data['address']);
  6865.         $data['departmentCode'] = $department['departmentCode'];
  6866.         $data['departmentName'] = $department['departmentName'];
  6867.         $data['regionName'] = $department['regionName'];
  6868.         $data['city'] = $department['city'];
  6869.         $password "";
  6870.         $params = [
  6871.             'name' => $data['name'],
  6872.             'civilite' => $data['civilite'],
  6873.             'nom' => $data['firstname'],
  6874.             'prenom' => $data['lastname'],
  6875.             'codePostal' => $data['address'],
  6876.             'telephone' => $data['phone'],
  6877.             'email' => $data['email'],
  6878.             'password' => $data['clientSecretCookie'],
  6879.             'trancheAge' => isset($data['rangAge']) ? $data['rangAge'] : null,
  6880.             'situationVecu' => isset($data['situations']) ? implode(', '$data['situations']) : null,
  6881.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  6882.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  6883.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  6884.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  6885.             'urlLogin' => "{$_ENV['BASE_client']}login"
  6886.         ];
  6887.         // Send email to MyAudio
  6888.         $publicFunction->sendEmail($params$email$data['name'], $subject220);
  6889.         $publicFunction->sendEmail($params'contact@myaudio.fr'$data['name'], $subject220);
  6890.         // Send email to patient
  6891.         $params = [
  6892.             'clientEmail' => $data['email'],
  6893.             'clientPassword' => $data['clientSecretCookie'],
  6894.             'rdv' => "https://www.myaudio.fr/search",
  6895.             'urlLogin' => "{$_ENV['BASE_client']}login"
  6896.         ];
  6897.         $publicFunction->sendEmail($params$data['email'], $data['name'], 'Rendez-vous My Audio - En cours de traitement'219);
  6898.         $rdvLead $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
  6899.         if ($rdvLead) {
  6900.             $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'cant_move']);
  6901.             if ($leadStatus) {
  6902.                 $rdvLead->setLeadStatus($leadStatus);
  6903.                 $this->entityManager->flush();
  6904.             }
  6905.         }
  6906.         return new Response(json_encode([
  6907.             "status" => 200,
  6908.         ]), 200, ['Content-Type' => 'application/json']);
  6909.     }
  6910.     /**
  6911.      * @Route("/rdv/notiflead", name="notifLead", methods={"POST"})
  6912.      */
  6913.     public function notifLeadRdv(Request $requestPublicFunction $publicFunction): Response
  6914.     {
  6915.         $data json_decode($request->getContent(), true);
  6916.         $email "lead.myaudio@gmail.com";
  6917.         $centre "";
  6918.         $type "My Audio";
  6919.         $details "";
  6920.         $picto "❌";
  6921.         $ordo "sans ordo";
  6922.         $subject "";
  6923.         $name "";
  6924.         $postal "";
  6925.         $emailPatient "";
  6926.         if (isset($data['clientToken']) && !empty($data['clientToken'])) {
  6927.             $token $this->getDoctrine()->getRepository(Token::class)->findOneBy(['token' => $data['clientToken']]);
  6928.             $client $token->getIdClient();
  6929.             $name $client->getLastname() . " " $client->getName();
  6930.             $postal $client->getPostal();
  6931.             $emailPatient $client->getMail();
  6932.         } else {
  6933.             if (isset($data['postal'])) {
  6934.                 $postal $data['postal'];
  6935.             }
  6936.             if (isset($data['name'])) {
  6937.                 $name $data['name'];
  6938.             }
  6939.             if (isset($data['email'])) {
  6940.                 $email $data['email'];
  6941.             }
  6942.             if (isset($data['email'])) {
  6943.                 $emailPatient $data['email'];
  6944.             }
  6945.         }
  6946.         if (isset($data["ordonance"])) {
  6947.             if ($data["ordonance"] == "oui") {
  6948.                 $ordo "avec ordo";
  6949.             }
  6950.         }
  6951.         if (isset($data['centre'])) {
  6952.             $centre $data['centre'];
  6953.             $picto "✅";
  6954.             $subject $picto " Lead booké " $postal " " $ordo;
  6955.         } else {
  6956.             $centre "";
  6957.             $type "Hors Zone";
  6958.             $details "Pas de centre dans la zone";
  6959.             $subject $picto " Lead Hors Zone " $postal " " $ordo;
  6960.         }
  6961.         $responses = [
  6962.             'rangeAge' => isset($data['rangeAge']) ? $data['rangeAge'] : null,
  6963.             'situations' => isset($data['situations']) ? $data['situations'] : null,
  6964.             'equipeAppareil' => isset($data['equipe']) ? $data['equipe'] : null,
  6965.             'durationEquipe' => isset($data['durationEquipe']) ? $data['durationEquipe'] : null,
  6966.             'bilanAuditif' => isset($data['bilanAuditif']) ? $data['bilanAuditif'] : null,
  6967.             'ordonance' => isset($data['ordonance']) ? $data['ordonance'] : null,
  6968.             'dateOrdonance' => isset($data['dateOrdonance']) ? $data['dateOrdonance'] : null,
  6969.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  6970.         ];
  6971.         $params = [
  6972.             'date' => $data['date'],
  6973.             'time' => $data['time'],
  6974.             'address' => $data['address'],
  6975.             'centre' => $centre,
  6976.             'type' => $type,
  6977.             'details' => $details,
  6978.             'responses' => $responses,
  6979.             'name' => $name,
  6980.             'email' => $emailPatient,
  6981.         ];
  6982.         $publicFunction->sendEmail($params$email$name$subject180);
  6983.         return new Response(json_encode([
  6984.             "status" => 200,
  6985.             "params" => $params,
  6986.             "responses" => $responses
  6987.         ]), 200, ['Content-Type' => 'application/json']);
  6988.     }
  6989.     /**
  6990.      *  Met à jour l'état d'un rendez-vous.
  6991.      *
  6992.      * Cette fonction permet de modifier l'état d'un rendez-vous en fonction des données envoyées
  6993.      * via une requête PUT. Elle effectue plusieurs vérifications, notamment :
  6994.      * - La présence et la validité du token d'authentification.
  6995.      * - L'existence du rendez-vous et du nouvel état.
  6996.      * - L'expiration du token (plus de 7 jours).
  6997.      * 
  6998.      * Si le rendez-vous est marqué comme "Absence injustifiée" (état ID 3), un email et un SMS sont envoyés
  6999.      * au client et à l'équipe MyAudio pour les informer.
  7000.      * 
  7001.      * @Route("api/save-etat-rdv", name="saveEtatRdv", methods={"PUT"})
  7002.      */
  7003.     public function saveEtatRdv(Request $requestPublicFunction $publicFunction): Response
  7004.     {
  7005.         $entityManager $this->getDoctrine()->getManager();
  7006.         $data json_decode($request->getContent(), true);
  7007.         if (!$data['token']) {
  7008.             return new Response(json_encode([
  7009.                 "message" => "Pas de token n'a été spécifié",
  7010.                 "status" => 401,
  7011.             ]), 401);
  7012.         }
  7013.         /** @var Token */
  7014.         $token $this->getDoctrine()
  7015.             ->getRepository(Token::class)
  7016.             ->findOneBy(['token' => $data['token'], 'id_audio' => $data['audio']]);
  7017.         if (!$token) {
  7018.             return new Response(json_encode([
  7019.                 "message" => "Pas de token trouvé dans la base de données. Veuillez vous reconnecter.",
  7020.                 "status" => 404,
  7021.             ]), 404);
  7022.         }
  7023.         // get token age
  7024.         $dateDiff $token->getCreationDate()->diff(new DateTime());
  7025.         // if the token if older than 7 days
  7026.         if ($dateDiff->7) {
  7027.             $entityManager->remove($token);
  7028.             $entityManager->flush();
  7029.             return $this->json([
  7030.                 'message' => 'Ce token est obselète. Veuillez vous reconnecter.',
  7031.                 'path' => 'src/Controller/ClientController.php',
  7032.                 "status" => 401,
  7033.             ], 401);
  7034.         }
  7035.         $rdv $this->getDoctrine()->getRepository(Rdv::class)->find($data['rdv']);
  7036.         if (!$rdv) {
  7037.             return new Response(json_encode([
  7038.                 "message" => "Rdv not found.",
  7039.                 "status" => 404,
  7040.             ]), 404);
  7041.         }
  7042.         $rdvEtat $this->getDoctrine()
  7043.             ->getRepository(EtatRdv::class)
  7044.             ->find($data['etat']);
  7045.         if (!$rdvEtat) {
  7046.             return new Response(json_encode([
  7047.                 "message" => "Rdv etat not found.",
  7048.                 "status" => 404,
  7049.             ]), 404);
  7050.         }
  7051.         $rdv->setIdEtat($rdvEtat);
  7052.         $entityManager->flush();
  7053.         $encodedNomDuCentre rawurlencode($rdv->getIdCentre()->getName());
  7054.         $urlApi "audioprothesiste/{$rdv->getIdCentre()->getCity()}/{$rdv->getIdCentre()->getPostale()}/{$encodedNomDuCentre}/prise-de-rdvaudioprothesiste-rapide/{$rdv->getIdCentre()->getId()}";
  7055.         if ($rdvEtat->getId() == 3) {
  7056.             // Send email to client
  7057.             $date $rdv->getDate();
  7058.             $smsDate $date->format('d-m-Y H:i');
  7059.             $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  7060.             $params = array(
  7061.                 "date" => substr($smsDate010),
  7062.                 "lien" => "{$_ENV['BASE_client']}$urlApi,
  7063.                 "heure" => substr($smsDate1115),
  7064.                 'centerName' => $rdv->getIdCentre()->getName() ?? '',
  7065.                 'centerPostal' => $rdv->getIdCentre()->getPostale() ?? '',
  7066.                 'centerCity' => $rdv->getIdCentre()->getCity() ?? '',
  7067.                 'centerAddress' => $rdv->getIdCentre()->getAddress() ?? '',
  7068.                 'centerPhone' => $rdv->getIdCentre()->getPhone() ?? '',
  7069.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName() ?? '',
  7070.                 'audioMail' => $rdv->getIdAudio()->getMail() ?? '',
  7071.             );
  7072.             $subject "Vous avez manqué votre rendez-vous MyAudio avec " $rdv->getIdCentre()->getName();
  7073.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject214);
  7074.             // Send sms to client
  7075.             $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();
  7076.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  7077.             // Send email to MyAudio
  7078.             $date $rdv->getDate();
  7079.             $smsDate $date->format('d-m-Y H:i');
  7080.             $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  7081.             $params = array(
  7082.                 "date" => substr($smsDate010),
  7083.                 "lien" => "{$_ENV['BASE_client']}search",
  7084.                 "heure" => substr($smsDate1115),
  7085.                 'centerName' => $rdv->getIdCentre()->getName() ?? '',
  7086.                 'centerPostal' => $rdv->getIdCentre()->getPostale() ?? '',
  7087.                 'centerCity' => $rdv->getIdCentre()->getCity() ?? '',
  7088.                 'centerAddress' => $rdv->getIdCentre()->getAddress() ?? '',
  7089.                 'centerPhone' => $rdv->getIdCentre()->getPhone() ?? '',
  7090.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName() ?? '',
  7091.                 'audioMail' => $rdv->getIdAudio()->getMail() ?? '',
  7092.                 'clientName' => $client->getName() . ' ' $client->getLastName() ?? '',
  7093.                 'clientMail' => $client->getMail() ?? '',
  7094.                 'clientPhone' => $client->getPhone() ?? '',
  7095.             );
  7096.             $subject "Le patient " $client->getName() . ' ' $client->getLastName() . " a manqué son rendez-vous MyAudio avec le centre " $rdv->getIdCentre()->getName();
  7097.             $publicFunction->sendEmail($params"lead.myaudio@gmail.com"$client->getName() . ' ' $client->getLastName(), $subject215);
  7098.         }
  7099.         return new Response(json_encode([
  7100.             "message" => "rdvEtat has been successfully updated",
  7101.             "status" => 200,
  7102.         ]));
  7103.     }
  7104.     /**
  7105.      * 
  7106.      * @Route("api/send-email/clientnotcompletebook", name="askToContact", methods={"POST"})
  7107.      */
  7108.     public function askToContact(Request $requestPublicFunction $publicFunction): Response
  7109.     {
  7110.         $data json_decode($request->getContent(), true);
  7111.         $staticToken "3f3a8b74f3e5b2d0c4917f5f9a7c07efb1a0f1e5e8c907ec9c4e9df129e3125e9";
  7112.         $token $data['token'] ?? null;
  7113.         if ($token !== $staticToken) {
  7114.             return new JsonResponse(
  7115.                 [
  7116.                     'status' => 'error',
  7117.                     'code' => 'unauthorized',
  7118.                     'message' => 'Unauthorized access.'
  7119.                 ],
  7120.                 JsonResponse::HTTP_UNAUTHORIZED
  7121.             );
  7122.         }
  7123.         $params = [
  7124.             'clientCivilite' => isset($data['civilite']) ? $data['civilite'] : 'Pas indiqué',
  7125.             'clientNom' => isset($data['firstname']) ? $data['firstname'] : null,
  7126.             'clientPrenom' => isset($data['lastname']) ? $data['lastname'] : null,
  7127.             'clientPostal' => isset($data['postalCode']) ? $data['postalCode'] : null,
  7128.             'clientPhone' => isset($data['phone']) ? $data['phone'] : null,
  7129.             'clientMail' => isset($data['email']) ? $data['email'] : null,
  7130.             'password' => isset($data['clientSecretCookie']) ? $data['clientSecretCookie'] : null,
  7131.             'rangeAge' => isset($data['trancheAge']) ? $data['trancheAge'] : null,
  7132.             'canMove' => isset($data['canMove']) ? $data['canMove'] : null,
  7133.             'situations' => isset($data['situations']) ? implode(', '$data['situations']) : null,
  7134.             'trafficSource' => isset($data['traffic_source']) ? $data['traffic_source'] : null,
  7135.             'articleName' => isset($data['article_name']) ? $data['article_name'] : null,
  7136.             'lpVersion' => isset($data['lp_version']) ? $data['lp_version'] : null,
  7137.         ];
  7138.         $templateEmailMyAudio 223;
  7139.         if (!empty($data['centre'])) {
  7140.             $centre $data['centre'];
  7141.             $audio $centre['audio'][0];
  7142.             $params['centerName'] = $centre['name'] ?? null;
  7143.             $params['centerPostal'] = $centre['postale'] ?? null;
  7144.             $params['centerCity'] = $centre['city'] ?? null;
  7145.             $params['centerAddress'] = $centre['address'] ?? null;
  7146.             $params['centerPhone'] = $centre['phone'] ?? null;
  7147.             $params['audioproName'] = $audio['civilite'] . ' ' $audio['lastname'] . ' ' $audio['name'] ?? null;
  7148.             $templateEmailMyAudio 222;
  7149.         }
  7150.         // Email to My Audio
  7151.         $email "lead.myaudio@gmail.com";
  7152.         $subject "Demande de contact -  Nouveau Lead À Contacter Hors Zone";
  7153.         $publicFunction->sendEmail($params$email$data['name'], $subject$templateEmailMyAudio);
  7154.         $publicFunction->sendEmail($params'contact@myaudio.fr'$data['name'], $subject$templateEmailMyAudio);
  7155.         $coordinates $this->getCoordinatesFromPostalCode($data['postalCode']);
  7156.         $latitude $coordinates['latitude'];
  7157.         $longitude $coordinates['longitude'];
  7158.         $params = [
  7159.             'email' => isset($data['email']) ? $data['email'] : null,
  7160.             'password' => isset($data['clientSecretCookie']) ? $data['clientSecretCookie'] : null,
  7161.             "lienRdv" => "{$_ENV['BASE_client']}search?latitude={$latitude}&longitude={$longitude}&ville={$data['postalCode']}",
  7162.         ];
  7163.         // Email to Client
  7164.         $subject "My Audio - Confirmation de demande de contact";
  7165.         $publicFunction->sendEmail($params$data['email'], $data['name'], $subject221);
  7166.         $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";
  7167.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$data['phone']);
  7168.         if (isset($data['clientRdvLp'])) {
  7169.             $rdvLead $this->entityManager->getRepository(LeadRdv::class)->find($data['clientRdvLp']);
  7170.             if ($rdvLead) {
  7171.                 $rdvLead->setSendAskToContact(1);
  7172.                 $rdvLead->setCountAskToContact(($rdvLead->getCountAskToContact() ?? 0) + 1);
  7173.                 $this->entityManager->flush();
  7174.                 $this->sendWhatsApp($data$rdvLead);
  7175.             }
  7176.         }
  7177.         return new Response(json_encode([
  7178.             "message" => "Email ask for contact send with success",
  7179.             "status" => 200,
  7180.         ]));
  7181.     }
  7182.     private function sendWhatsApp($data$lead): void
  7183.     {
  7184.         $adminUrl $this->adminUrlGenerator
  7185.             ->setDashboard(DashboardController::class)
  7186.             ->setController(LeadRdvCrudController::class)
  7187.             ->setAction('detail')
  7188.             ->setEntityId($lead->getId())
  7189.             ->generateUrl();
  7190.         $relativeUrl parse_url($adminUrlPHP_URL_PATH) . '?' parse_url($adminUrlPHP_URL_QUERY);
  7191.         // Supprimer le slash en trop s’il y en a un au début
  7192.         $relativeUrl ltrim($relativeUrl'/');
  7193.         // 🧑‍🤝‍🧑 Tableau des destinataires
  7194.         $destinataires = [
  7195.             '33611879183'// Numéro 1
  7196.             '33667597626'// Numéro 2
  7197.             '447884128220'// Numéro 3
  7198.         ];
  7199.         foreach ($destinataires as $numero) {
  7200.             $this->whatsapp->sendTemplateMessage(
  7201.                 $numero,  // Numéro de téléphone du destinataire
  7202.                 'lead_notif_myaudio',  // Nom du template WhatsApp
  7203.                 [
  7204.                     'body' => [
  7205.                         ['parameter_name' => 'nom_client''text' => $data['firstname'] . ' ' $data['lastname']],  // {{nom_client}}
  7206.                         ['parameter_name' => 'email_client''text' => $data['email'] ?? ' '],  // {{email_client}}
  7207.                         ['parameter_name' => 'telephone_client''text' => $data['phone'] ?? ' '],  // {{telephone_client}}
  7208.                         ['parameter_name' => 'date_lead''text' => $lead->getDate()->format('d/m/Y H:i')],  // {{date_lead}}
  7209.                         ['parameter_name' => 'code_postal''text' => $data['postalCode'] ?? ' '],  // {{code_postal}}
  7210.                         ['parameter_name' => 'nombre_centres''text' => $lead->getCentersCount() ?? '0'],  // {{nombre_centres}}
  7211.                     ],
  7212.                     'button' => $relativeUrl,  // <--- seulement le chemin dynamique
  7213.                 ]
  7214.             );
  7215.         }
  7216.     }
  7217.     /**
  7218.      * Get coordinates from the postal code using the database.
  7219.      */
  7220.     private function getCoordinatesFromPostalCode(string $postalCode): array
  7221.     {
  7222.         $region $this->entityManager
  7223.             ->getRepository(RegionDepartment::class)
  7224.             ->findOneBy(['codePostal' => $postalCode]);
  7225.         if ($region) {
  7226.             return [
  7227.                 'latitude' => $region->getLatitude(),
  7228.                 'longitude' => $region->getLongitude(),
  7229.             ];
  7230.         }
  7231.         return [
  7232.             'latitude' => null,
  7233.             'longitude' => null,
  7234.         ];
  7235.     }
  7236.     /**
  7237.      * Get the department code from the code postal
  7238.      */
  7239.     private function getDepartmentFromPostalCode(string $postalCode): ?array
  7240.     {
  7241.         $region $this->entityManager
  7242.             ->getRepository(RegionDepartment::class)
  7243.             ->findOneBy(['codePostal' => $postalCode]);
  7244.         if ($region) {
  7245.             return [
  7246.                 'departmentCode' => $region->getCodeDepartement(),
  7247.                 'departmentName' => $region->getNomDepartement(),
  7248.                 'regionCode' => $region->getCodeRegion(),
  7249.                 'regionName' => $region->getNomRegion(),
  7250.                 'city' => $region->getNomCommunePostal(),
  7251.             ];
  7252.         }
  7253.         return null;
  7254.     }
  7255.     /**
  7256.      * 
  7257.      * @Route("/giuili-admin/lead/{leadId}/centre/{centreId}", name="showLeadCentre", methods={"GET"})
  7258.      */
  7259.     public function showLeadCentre(int $leadIdCentre $centreId): Response
  7260.     {
  7261.         // dd("tets");
  7262.         $center $centres $this->getDoctrine()
  7263.             ->getRepository(AudioCentre::class)
  7264.             ->findOneBy(['id_centre' => $centreId->getId()]);
  7265.         $audio $center->getIdAudio();
  7266.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  7267.             ->findBy(['id_audio' => $audio'isDeleted' => 0]);
  7268.         return $this->render('easyadmin/leadRdv/centre_show.html.twig', [
  7269.             'audio' => $audio,
  7270.             'leadId' => $leadId,
  7271.             'centreId' => $centreId,
  7272.             'motifs' => $motifs,
  7273.         ]);
  7274.     }
  7275.     /**
  7276.      * @Route("/rdv-easyadmin", name="postRdvEasyAdmin", methods={"POST"})
  7277.      */
  7278.     public function postRdvEasyAdmin(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSmsAppointmentCallService $Callservice): Response
  7279.     {
  7280.         $data json_decode($request->getContent(), true);
  7281.         $entityManager $this->getDoctrine()->getManager();
  7282.         $audio $this->getDoctrine()
  7283.             ->getRepository(Audio::class)
  7284.             ->findOneBy(['id' => $data["audio_id"]]);
  7285.         $leadRdv =   $this->getDoctrine()->getRepository(LeadRdv::class)
  7286.             ->find($data["lead_id"]);
  7287.         $client $this->getDoctrine()->getRepository(Client::class)
  7288.             ->find($leadRdv->getClient());
  7289.         $responses = [
  7290.             'rangeAge' => $leadRdv->getRangeAge(),
  7291.             'situations' =>  implode(", "$leadRdv->getSituationsGene()),
  7292.             'equipeAppareil' => $leadRdv->getEquipeAppareil(),
  7293.             'durationEquipe' => $leadRdv->getDurationEquipeAppareil(),
  7294.             'bilanAuditif' => $leadRdv->getBilanAuditif(),
  7295.             'ordonance' => $leadRdv->getOrdonance(),
  7296.             'dateOrdonance' => $leadRdv->getDateOrdonance(),
  7297.             'canMove' => $leadRdv->getCanMove(),
  7298.         ];
  7299.         // makes the rdv
  7300.         $rdv = new Rdv();
  7301.         $rdv->setIdAudio($audio);
  7302.         if (isset($proche)) {
  7303.             $rdv->setIdProche($proche);
  7304.         }
  7305.         if (isset($data["client_id_temp"])) {
  7306.             $rdv->setIdClientTemp($client);
  7307.         } else {
  7308.             $rdv->setIdClient($client);
  7309.         }
  7310.         $rdv->setIsMyaudio(true);
  7311.         if (isset($data["isRdvLead"])) {
  7312.             $rdv->setIsRdvLp(true);
  7313.         }
  7314.         if (isset($data["isRdvRapide"])) {
  7315.             $rdv->setIsRdvRapide(true);
  7316.         }
  7317.         if (isset($data["duree"])) {
  7318.             $rdv->setDuration($data["duree"]);
  7319.         }
  7320.         if (isset($data["color"])) {
  7321.             $rdv->setColor($data["color"]);
  7322.         }
  7323.         /** @var Centre */
  7324.         if (isset($data["centre_id"])) {
  7325.             $centre $this->getDoctrine()
  7326.                 ->getRepository(Centre::class)
  7327.                 ->findOneBy(['id' => $data["centre_id"]]);
  7328.             if ($centre == null) {
  7329.                 return new Response(json_encode(([
  7330.                     'message' => 'Error, no centre found at this id',
  7331.                     'path' => 'src/Controller/RdvController.php',
  7332.                     "status" => 400,
  7333.                 ])), 400);
  7334.             }
  7335.             /** @var AudioCentre */
  7336.             $liaison $this->getDoctrine()
  7337.                 ->getRepository(AudioCentre::class)
  7338.                 ->findOneBy(['id_centre' => $centre->getId(), 'id_audio' => $audio->getId()]);
  7339.             if ($liaison == null) {
  7340.                 return new Response(json_encode(([
  7341.                     'message' => 'Error, audio isnt part of the centre',
  7342.                     'path' => 'src/Controller/RdvController.php',
  7343.                     "status" => 400,
  7344.                 ])), 400);
  7345.             }
  7346.             $rdv->setIdCentre($centre);
  7347.         } elseif (isset($data["lieu_id"]) && $audio->getIsIndie()) {
  7348.             // tries to set the lieu if it's an audio indie
  7349.             $lieu $this->getDoctrine()
  7350.                 ->getRepository(Lieu::class)
  7351.                 ->findOneBy(['id' => $data["lieu_id"], 'id_gerant' => $data["audio_id"]]);
  7352.             if ($lieu == null) {
  7353.                 return new Response(json_encode(([
  7354.                     'message' => 'Error, no lieu found at this id',
  7355.                     'path' => 'src/Controller/RdvController.php',
  7356.                     "status" => 400,
  7357.                 ])), 400);
  7358.             }
  7359.             $rdv->setIdLieu($lieu);
  7360.         } else {
  7361.             return new Response(json_encode(([
  7362.                 'message' => 'Error, no lieu/centre id',
  7363.                 'path' => 'src/Controller/RdvController.php',
  7364.                 "status" => 400,
  7365.             ])), 400);
  7366.         }
  7367.         /** @var Motif */
  7368.         $motif $this->getDoctrine()
  7369.             ->getRepository(Motif::class)
  7370.             ->find($data["motif_id"]);
  7371.         if ($motif == null) {
  7372.             return new Response(json_encode(([
  7373.                 'message' => 'Error, no motif found at this id',
  7374.                 'path' => 'src/Controller/RdvController.php',
  7375.                 "status" => 400,
  7376.             ])), 400);
  7377.         }
  7378.         /** @var AudioMotif */
  7379.         $audioMotif $this->getDoctrine()
  7380.             ->getRepository(AudioMotif::class)
  7381.             ->findOneBy(["id_audio" => $audio->getId(), "id_motif" => $data["motif_id"]]);
  7382.         if ($audioMotif == null) {
  7383.             return new Response(json_encode(([
  7384.                 'message' => 'Error, no motif of this id found at this audio',
  7385.                 'path' => 'src/Controller/RdvController.php',
  7386.                 "status" => 400,
  7387.             ])), 400);
  7388.         }
  7389.         // remove the taken schedule by rdv to make sure there is no overlap
  7390.         $data["date"] = str_replace("h"":"$data["date"]);
  7391.         $date \DateTime::createFromFormat("Y-m-d\TH:i"$data["date"]);
  7392.         if (isset($data["note"])) {
  7393.             $rdv->setNote($data["note"]);
  7394.         }
  7395.         $date \DateTime::createFromFormat("Y-m-d\TH:i"$data["date"]);
  7396.         $rdv->setDate($date);
  7397.         $rdv->setDateCreation(\DateTime::createFromFormat("d/m/Y H:i"date('d/m/Y H:i')));
  7398.         /** @var EtatRdv */
  7399.         $etat $this->getDoctrine()
  7400.             ->getRepository(EtatRdv::class)
  7401.             ->findOneBy(['id' => $data["etat_id"]]);
  7402.         if ($etat == null) {
  7403.             return new Response(json_encode(([
  7404.                 'message' => 'Error, no etat found at this id',
  7405.                 'path' => 'src/Controller/RdvController.php',
  7406.                 "status" => 400,
  7407.             ])), 400);
  7408.         }
  7409.         $rdv->setIdEtat($etat);
  7410.         $rdv->setIdMotif($motif);
  7411.         $rdv->setIsAbsence(0);
  7412.         $rdv->setCacher(0);
  7413.         $entityManager $this->getDoctrine()->getManager();
  7414.         $entityManager->persist($rdv);
  7415.         $leadRdv->setRdv($rdv);
  7416.         $leadStatus $this->entityManager->getRepository(LeadStatus::class)->findOneBy(['slug' => 'rdv_valider']);
  7417.         $leadRdv->setLeadStatus($leadStatus);
  7418.         $entityManager->flush();
  7419.         /// SMSEMAIL A décommenter pour autoriser l'envoi de sms / email à la création de rdv par l'audio / le client SMSEMAIL ///
  7420.         $date $rdv->getDate();
  7421.         $smsDate $date->format('d-m-Y H:i');
  7422.         $locale 'fr_FR';
  7423.         $formatter = new IntlDateFormatter(
  7424.             $locale,
  7425.             IntlDateFormatter::FULL,
  7426.             IntlDateFormatter::SHORT,
  7427.             null,
  7428.             IntlDateFormatter::GREGORIAN,
  7429.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  7430.         );
  7431.         $smsDateLongFormat $formatter->format($date);
  7432.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  7433.         $client->setIdCentre($rdv->getIdCentre());
  7434.         $client->setIdAudio($rdv->getIdAudio());
  7435.         $entityManager->persist($client);
  7436.         $entityManager->flush();
  7437.         // client notif mail Sms
  7438.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  7439.         $frenchDate ucfirst($frenchDate);
  7440.         $params = array(
  7441.             "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  7442.             "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  7443.             "date" => $smsDateLongFormat,
  7444.             "RdvDate" => $smsDateLongFormat,
  7445.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  7446.             "centerName" => $rdv->getIdCentre()->getName(),
  7447.             "prenom" => $client->getName(),
  7448.             "centerAddress" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  7449.             "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  7450.             'motif' => $rdv->getIdMotif()->getTitre(),
  7451.             "centerCity" => $rdv->getIdCentre()->getCity(),
  7452.             "audioName" => $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  7453.             'titre' => "Votre rendez-vous est validé le " substr($smsDate010) . " à "  substr($smsDate1115),
  7454.             "position" => $rdv->getIdCentre()->getAddress() . ' ' $rdv->getIdCentre()->getPostale() . ' ' $rdv->getIdCentre()->getCity(),
  7455.             "address" => $rdv->getIdCentre()->getAddress(),
  7456.             "postal" => $rdv->getIdCentre()->getPostale(),
  7457.             "city" => $rdv->getIdCentre()->getCity(),
  7458.             "clientEmail" => $client->getMail(),
  7459.             "clientPassword" => isset($data["passwordGenerated"]) ? $data["passwordGenerated"] : null,
  7460.             "clientAddress" => $client->getAddress(),
  7461.             "clientPostal" => $client->getPostal(),
  7462.             "clientCity" => $client->getCity(),
  7463.             "audioName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  7464.             "frenchDate" => $frenchDate,
  7465.             "heure" => substr($smsDate1115),
  7466.             "centerName" => $rdv->getIdCentre()->getName(),
  7467.             "audioMail" => $rdv->getIdAudio()->getMail(),
  7468.             "modifUrl" => "{$_ENV['BASE_client']}mes-rendez-vous",
  7469.         );
  7470.         $paramsPatient $params;
  7471.         $isNew false;
  7472.         if (isset($data["isLead"]) && isset($data["passwordGenerated"]) != null) {
  7473.             $subject "✅Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  7474.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject189);
  7475.             $isNew true;
  7476.         } else {
  7477.             $subject "Rendez-vous My Audio confirmé le " $smsDateLongFormat;
  7478.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject181);
  7479.         }
  7480.         $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.";
  7481.         $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  7482.         // audio Notif mail SMS
  7483.         $birthday $rdv->getIdClient()->getBirthdate();
  7484.         $params = array(
  7485.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  7486.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  7487.             "date" => substr($smsDate010),
  7488.             "heure" => substr($smsDate1115),
  7489.             "mail" => $client->getMail(),
  7490.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  7491.             'telClient' => $client->getPhone(),
  7492.             'phone' => $client->getPhone(),
  7493.             'clientCivilite' => $client->getCivilite(),
  7494.             'clientNom' => $client->getLastname(),
  7495.             'clientPrenom' => $client->getName(),
  7496.             'clientPostal' => $client->getPostal(),
  7497.             'clientMail' => $client->getMail(),
  7498.             'clientPhone' => $client->getPhone(),
  7499.             'motif' => $rdv->getIdMotif()->getTitre(),
  7500.             'birthdate' => $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  7501.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  7502.             'centerName' => $rdv->getIdCentre()->getName(),
  7503.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  7504.             'centerCity' => $rdv->getIdCentre()->getCity(),
  7505.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  7506.             'idPatient' => $client->getId(),
  7507.             'proUrl' => "{$_ENV['BASE_logiciel']}",
  7508.             'frenchDate' => $frenchDate,
  7509.             'responses' => $responses,
  7510.         );
  7511.         $templateEmail 182;
  7512.         if (!empty($data['canMove'])) {
  7513.             $templateEmail 197;
  7514.         }
  7515.         $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  7516.         $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  7517.         if ($rdv->getIdAudio()->getConfirmRdvMail()) {
  7518.             $subject "✅ Nouveau Rendez-vous My Audio le " $frenchDate " à " substr($smsDate1115);
  7519.             $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject$templateEmail);
  7520.         }
  7521.         if ($rdv->getIdAudio()->getConfirmRdvSms()) {
  7522.             $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.";
  7523.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  7524.         }
  7525.         $age null;
  7526.         if ($client->getBirthdate()) {
  7527.             $age $client->getBirthdate()->diff(new \DateTime())->y;
  7528.         }
  7529.         // Génère le PDF à partir d’un template
  7530.         $pdfContent $this->generatePdf(
  7531.             'pdf/rdv_recap.html.twig',
  7532.             [
  7533.                 'id' => $client->getId() ?? '',
  7534.                 'nom' => $client->getName() ?? '',
  7535.                 'prenom' => $client->getLastname() ?? '',
  7536.                 'birthday' =>  $client->getBirthdate() ? $client->getBirthdate()->format("d/m/Y") : null,
  7537.                 'age' => $age,
  7538.                 'adresse' => $client->getAddress() ?? '',
  7539.                 'postal' => $client->getPostal() ?? '',
  7540.                 'city' => $client->getCity() ?? '',
  7541.                 'phone' => $client->getPhone() ?? '',
  7542.                 'mail' => $client->getMail() ?? '',
  7543.                 'centerName' => $rdv->getIdCentre()->getName() ?? '',
  7544.                 "date" => substr($smsDate010) ?? '',
  7545.                 "heure" => substr($smsDate1115) ?? '',
  7546.                 'duration' => $rdv->getDuration(),
  7547.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  7548.                 'motif' => $rdv->getIdMotif() ? $rdv->getIdMotif()->getTitre() : '',
  7549.                 'situations' => $this->formatImploded($leadRdv->getSituationsGene()),
  7550.                 'IntensiteGen' => $leadRdv->getIntensiteGene() ?? '',
  7551.                 'devicePref' => $this->formatImploded($leadRdv->getPreferenceDevice()),
  7552.                 'deviceModelPref' =>  implode(", "$leadRdv->getDeviceModelPreference()),
  7553.                 'criterePrincipal' => $this->formatImploded($leadRdv->getCriterePrincipal()),
  7554.                 'accoupheneCote' =>  $leadRdv->getAcoupheneCote() ?? '',
  7555.                 'originePerte' => $this->formatImploded($leadRdv->getOriginePerte()),
  7556.                 'diabete' =>  $leadRdv->getDiabete() ?? '',
  7557.                 'hypertension' =>  $leadRdv->getHypertension() ?? '',
  7558.                 'mutuelle' =>  $leadRdv->getMutuelle() ?? '',
  7559.                 'nameMutuelle' =>  $leadRdv->getNameMutuelle() ?? '',
  7560.                 'priseEnCharge' => $leadRdv->getPriseEnCharge() ?? '',
  7561.                 'budget' => $leadRdv->getBudget() ?? '',
  7562.                 'equipeAppareil' => $leadRdv->getEquipeAppareil() ?? '',
  7563.                 'durationEquipe' => $leadRdv->getDurationEquipeAppareil() ?? '',
  7564.                 'bilanAuditif' => $leadRdv->getBilanAuditif() ?? '',
  7565.                 'ordonance' => $leadRdv->getOrdonance() ?? '',
  7566.                 'dateOrdonance' => $leadRdv->getDateOrdonance() ?? '',
  7567.                 'canMove' => $leadRdv->getCanMove() ?? '',
  7568.                 'comment' => $leadRdv->getComment() ?? '',
  7569.             ],
  7570.             $this->getParameter('kernel.project_dir') . '/public/assets/pdf/recap-rdv-myaudio.pdf'
  7571.         );
  7572.         $this->sendEmailWithPdfAttachmentThenDelete(
  7573.             $params,
  7574.             $mailAudio,
  7575.             $client->getName(),
  7576.             $subject,
  7577.             $templateEmail// ID du template Sendinblue
  7578.             $pdfContent
  7579.         );
  7580.         // send notif to admin
  7581.         $paramsSourceLead = [
  7582.             'trafficSource' => "EasyAdmin",
  7583.         ];
  7584.         $paramsAdmin = array(
  7585.             "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  7586.             "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  7587.             "RdvDate" => substr($smsDate010),
  7588.             "heure" => substr($smsDate1115),
  7589.             "clientMail" => $client->getMail(),
  7590.             "audioproName" => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  7591.             'telClient' => $client->getPhone(),
  7592.             'clientNom' => $client->getLastname(),
  7593.             'clientPrenom' => $client->getName(),
  7594.             'clientCivilite' => $client->getCivilite(),
  7595.             'clientPostal' => $client->getPostal(),
  7596.             'clientPhone' => $client->getPhone(),
  7597.             'motif' => $rdv->getIdMotif()->getTitre(),
  7598.             'centerAddress' => $rdv->getIdCentre()->getAddress(),
  7599.             'centerName' => $rdv->getIdCentre()->getName(),
  7600.             'centerPostal' => $rdv->getIdCentre()->getPostale(),
  7601.             'centerCity' => $rdv->getIdCentre()->getCity(),
  7602.             'telCentre' => $rdv->getIdCentre()->getPhone(),
  7603.             'titre' => 'Vous avez un nouveau RDV le : ' substr($smsDate010) . ' à ' substr($smsDate1115),
  7604.             'date' => substr($smsDate010),
  7605.             'urlApi' => "{$_ENV['BASE_API']}",
  7606.             'clientId' => $client->getId(),
  7607.             'centerId' => $rdv->getIdCentre()->getId(),
  7608.             'frenchDate' => $frenchDate,
  7609.             'responses' => $responses,
  7610.             'paramsSourceLead' => $paramsSourceLead
  7611.         );
  7612.         $subject "Nouveau RDV MA | RR - " $rdv->getIdCentre()->getName();
  7613.         $templateEmail 183;
  7614.         if (!empty($data['canMove'])) {
  7615.             $templateEmail 190;
  7616.         }
  7617.         $publicFunction->sendEmail($paramsAdmin"contact@myaudio.fr""my audio"$subject$templateEmail);
  7618.         $publicFunction->sendEmail($paramsAdmin"lead.myaudio@gmail.com""my audio"$subject$templateEmail);
  7619.         $specificSubscription $this->getDoctrine()
  7620.              ->getRepository(SpecificSubscription::class)
  7621.              ->findOneBy(['audio' => $audio]);
  7622.       if ($specificSubscription && $specificSubscription->getContractCategory()) {
  7623.         $contractCategory $specificSubscription->getContractCategory();
  7624.       if ($contractCategory->getName() === "OPTICAL CENTER SUCCURSALE") {
  7625.         $publicFunction->sendEmail($paramsAdmin"christel.montagne@optical-center.com""my audio"$subject246);
  7626.          }
  7627.        }
  7628.         try {
  7629.             $Callservice->handleCallCenterAfterRdv(
  7630.                 $rdv
  7631.             );
  7632.             $rdv->setIsNotificationRdvCallSent(1);
  7633.             $this->entityManager->flush();
  7634.         } catch (\Exception $e) {
  7635.             $this->logger->error("Erreur lors de l'appel de notification pour le RDV #{$rdv->getId()}: " $e->getMessage());
  7636.         }
  7637.         // google calendar post
  7638.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  7639.             ->findBy(array('audio' => $audio->getId()));
  7640.         $data['rdv'] = $rdv->getId();
  7641.         foreach ($synchronisations as $synchronisation) {
  7642.             if (!$synchronisation->getIsDeleted()) {
  7643.                 $googleCalendar->checkAndRefreshAccessToken($synchronisation);
  7644.                 $googleCalendar->createEvent($synchronisation$data);
  7645.             }
  7646.         }
  7647.         return new Response(json_encode(([
  7648.             "id" => $rdv->getId(),
  7649.             "motif_id" => $rdv->getIdMotif()->getId(),
  7650.             "audio_id" => $rdv->getIdAudio()->getId(),
  7651.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  7652.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  7653.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdProche()->getId() : null,
  7654.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  7655.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  7656.             "testclient" => $rdv->getTestClient() ? [
  7657.                 "result" => $rdv->getTestClient()->getResultTonal(),
  7658.                 "date" => $rdv->getTestClient()->getDate(),
  7659.                 "device" => $rdv->getTestClient()->getIdAppareil()->getLibelle(),
  7660.             ] : null,
  7661.             "duration" => $audioMotif->getDuration(),
  7662.             "consigne" => $audioMotif->getConsigne(),
  7663.             "etat_id" => $rdv->getIdEtat()->getId(),
  7664.             "date" => $rdv->getDate(),
  7665.             "comment" => $rdv->getComment(),
  7666.             "centerName" => $rdv->getIdCentre()->getName(),
  7667.             "review" => $rdv->getReview(),
  7668.             "note" => $rdv->getNote(),
  7669.             "status" => 200,
  7670.             "paramsPatient" => $paramsPatient,
  7671.             "isNew" => $isNew,
  7672.         ])));
  7673.     }
  7674.     private function generatePdf(string $template, array $data = [], string $outputPath): string
  7675.     {
  7676.         // Render le contenu HTML avec Twig
  7677.         $html $this->twig->render($template$data);
  7678.         // Configurer Dompdf
  7679.         $options = new Options();
  7680.         $options->set('defaultFont''Arial');
  7681.         $dompdf = new Dompdf($options);
  7682.         $dompdf->loadHtml($html);
  7683.         $dompdf->setPaper('A4''portrait');
  7684.         $dompdf->render();
  7685.         // Sauvegarder le PDF
  7686.         file_put_contents($outputPath$dompdf->output());
  7687.         return $outputPath// Renvoie le chemin du fichier PDF généré
  7688.     }
  7689.     private function sendEmailWithPdfAttachmentThenDelete(
  7690.         array $params,
  7691.         string $mail,
  7692.         string $name,
  7693.         string $subject,
  7694.         int $templateId,
  7695.         string $pdfFilePath
  7696.     ): void {
  7697.         // Lire et encoder le contenu du PDF
  7698.         $attachment = [
  7699.             "name" => basename($pdfFilePath),
  7700.             "content" => base64_encode(file_get_contents($pdfFilePath)),
  7701.         ];
  7702.         // Construire les données pour l’API Sendinblue
  7703.         $data = [
  7704.             "sender" => [
  7705.                 "email" => 'noreply@myaudio.fr',
  7706.                 "name" => 'My Audio',
  7707.             ],
  7708.             "to" => [
  7709.                 [
  7710.                     "email" => $mail,
  7711.                     "name" => $name,
  7712.                 ],
  7713.             ],
  7714.             "subject" => $subject,
  7715.             "templateId" => $templateId,
  7716.             "params" => $params,
  7717.             "attachment" => [$attachment],
  7718.         ];
  7719.         // Envoi via cURL
  7720.         $ch curl_init();
  7721.         curl_setopt($chCURLOPT_URL'https://api.sendinblue.com/v3/smtp/email');
  7722.         curl_setopt($chCURLOPT_RETURNTRANSFER1);
  7723.         curl_setopt($chCURLOPT_POST1);
  7724.         curl_setopt($chCURLOPT_POSTFIELDSjson_encode($data));
  7725.         $headers = [
  7726.             'Accept: application/json',
  7727.             'Api-Key: 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',
  7728.             'Content-Type: application/json',
  7729.         ];
  7730.         curl_setopt($chCURLOPT_HTTPHEADER$headers);
  7731.         $result curl_exec($ch);
  7732.         if (curl_errno($ch)) {
  7733.             echo 'Erreur email : ' curl_error($ch);
  7734.         }
  7735.         curl_close($ch);
  7736.         // Supprimer le PDF après envoi
  7737.         if (file_exists($pdfFilePath)) {
  7738.             unlink($pdfFilePath);
  7739.         }
  7740.     }
  7741.     private function formatImploded(array $data): string
  7742.     {
  7743.         return implode(', 'array_map(function ($item) {
  7744.             return str_replace('_'' '$item);
  7745.         }, $data));
  7746.     }
  7747.     /**
  7748.      * 
  7749.      * @Route("/admin/rdv/export-pdf-form", name="admin_rdv_export_pdf_form", methods={"GET", "POST"})
  7750.      */
  7751.     public function exportPdfForm(Request $request): Response
  7752.     {
  7753.         $form $this->createFormBuilder()
  7754.             ->add('startDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  7755.                 'label' => 'Date de début',
  7756.                 'widget' => 'single_text',
  7757.                 'html5' => true,
  7758.                 'required' => true,
  7759.             ])
  7760.             ->add('endDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  7761.                 'label' => 'Date de fin',
  7762.                 'widget' => 'single_text',
  7763.                 'html5' => true,
  7764.                 'required' => true,
  7765.             ])
  7766.             ->add('format'\Symfony\Component\Form\Extension\Core\Type\ChoiceType::class, [
  7767.                 'label' => 'Format d\'export',
  7768.                 'choices' => [
  7769.                     'PDF' => 'pdf',
  7770.                     'Excel' => 'excel',
  7771.                 ],
  7772.                 'expanded' => false,
  7773.                 'multiple' => false,
  7774.                 'required' => true,
  7775.             ])
  7776.             ->getForm();
  7777.         //dd($request);
  7778.         $form->handleRequest($request);
  7779.         if ($form->isSubmitted() && $form->isValid()) {
  7780.             $data $form->getData();
  7781.             $start $data['startDate']->format('Y-m-d');
  7782.             $end $data['endDate']->format('Y-m-d');
  7783.             if ($data['format'] === 'pdf') {
  7784.                 return $this->redirectToRoute('admin_rdv_export_pdf', [
  7785.                     'startDate' => $start,
  7786.                     'endDate' => $end,
  7787.                 ]);
  7788.             } else {
  7789.                 return $this->redirectToRoute('admin_rdv_export_excel', [
  7790.                     'startDate' => $start,
  7791.                     'endDate' => $end,
  7792.                 ]);
  7793.             }
  7794.         }
  7795.         return $this->render('easyadmin/rdv/export_pdf_form.html.twig', [
  7796.             'form' => $form->createView(),
  7797.         ]);
  7798.     }
  7799.     /**
  7800.      * 
  7801.      * @Route("/optical/rdv/export-pdf-form", name="optical_rdv_export_pdf_form", methods={"GET", "POST"})
  7802.      */
  7803.     public function exportOpticalPdfForm(Request $request): Response
  7804.     {
  7805.         $form $this->createFormBuilder()
  7806.             ->add('startDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  7807.                 'label' => 'Date de début',
  7808.                 'widget' => 'single_text',
  7809.                 'html5' => true,
  7810.                 'required' => true,
  7811.             ])
  7812.             ->add('endDate'\Symfony\Component\Form\Extension\Core\Type\DateType::class, [
  7813.                 'label' => 'Date de fin',
  7814.                 'widget' => 'single_text',
  7815.                 'html5' => true,
  7816.                 'required' => true,
  7817.             ])
  7818.             ->add('format'\Symfony\Component\Form\Extension\Core\Type\ChoiceType::class, [
  7819.                 'label' => 'Format d\'export',
  7820.                 'choices' => [
  7821.                     'PDF' => 'pdf',
  7822.                     'Excel' => 'excel',
  7823.                 ],
  7824.                 'expanded' => false,
  7825.                 'multiple' => false,
  7826.                 'required' => true,
  7827.             ])
  7828.             ->getForm();
  7829.         //dd($request);
  7830.         $form->handleRequest($request);
  7831.         if ($form->isSubmitted() && $form->isValid()) {
  7832.             $data $form->getData();
  7833.             $start $data['startDate']->format('Y-m-d');
  7834.             $end $data['endDate']->format('Y-m-d');
  7835.             if ($data['format'] === 'pdf') {
  7836.                 return $this->redirectToRoute('optical_rdv_export_pdf', [
  7837.                     'startDate' => $start,
  7838.                     'endDate' => $end,
  7839.                 ]);
  7840.             } else {
  7841.                 return $this->redirectToRoute('optical_rdv_export_excel', [
  7842.                     'startDate' => $start,
  7843.                     'endDate' => $end,
  7844.                 ]);
  7845.             }
  7846.         }
  7847.         return $this->render('easyadmin/rdv/export_pdf_form.html.twig', [
  7848.             'form' => $form->createView(),
  7849.         ]);
  7850.     }
  7851.     /**
  7852.      * @Route("/admin/lead-rdv/update-status", name="admin_lead_rdv_update_status", methods={"POST"})
  7853.      */
  7854.     public function updateStatus(Request $request): JsonResponse
  7855.     {
  7856.         // Récupérer les données envoyées en AJAX
  7857.         $data json_decode($request->getContent(), true);
  7858.         $leadId $data['leadId'] ?? null;
  7859.         $statusId $data['statusId'] ?? null;
  7860.         if (!$leadId || !$statusId) {
  7861.             return new JsonResponse(['success' => false'message' => 'Données manquantes'], 400);
  7862.         }
  7863.         // Récupérer le lead et le statut
  7864.         $lead $this->entityManager->getRepository(LeadRdv::class)->find($leadId);
  7865.         $status $this->entityManager->getRepository(LeadStatus::class)->find($statusId);
  7866.         if (!$lead || !$status) {
  7867.             return new JsonResponse(['success' => false'message' => 'Lead ou statut introuvable'], 404);
  7868.         }
  7869.         // Mettre à jour le statut du lead
  7870.         $lead->setLeadStatus($status);
  7871.         $this->entityManager->flush();
  7872.         return new JsonResponse(['success' => true]);
  7873.     }
  7874.     /**
  7875.      * @Route("/admin/rdv/update-client-status", name="admin_rdv_update_client_status", methods={"POST"})
  7876.      */
  7877.     public function updateClientStatus(Request $request): JsonResponse
  7878.     {
  7879.         $data json_decode($request->getContent(), true);
  7880.         $rdvId $data['rdvId'] ?? null;
  7881.         $statusId $data['statusId'] ?? null;
  7882.         if (!$rdvId || !$statusId) {
  7883.             return new JsonResponse(['success' => false'message' => 'Données manquantes'], 400);
  7884.         }
  7885.         // Récupérer le RDV
  7886.         $rdv $this->entityManager->getRepository(Rdv::class)->find($rdvId);
  7887.         if (!$rdv) {
  7888.             return new JsonResponse(['success' => false'message' => 'RDV non trouvé'], 404);
  7889.         }
  7890.         // Récupérer le statut
  7891.         $clientStatus $this->entityManager->getRepository(ClientStatus::class)->find($statusId);
  7892.         if (!$clientStatus) {
  7893.             return new JsonResponse(['success' => false'message' => 'Statut non trouvé'], 404);
  7894.         }
  7895.         // Mettre à jour le client
  7896.         $client $rdv->getIdClient();
  7897.         if ($client) {
  7898.             $client->setClientStatus($clientStatus);
  7899.             $this->entityManager->flush();
  7900.             // Si le statut est "Facturé", lancer la facturation
  7901.             if ((int)$statusId === 2) {
  7902.                 // Réutiliser la méthode de facturation existante
  7903.                 $crudController $this->container->get(RdvMyAudioCrudController::class);
  7904.                 $crudController->billing($rdv);
  7905.             }
  7906.             return new JsonResponse(['success' => true]);
  7907.         }
  7908.         return new JsonResponse(['success' => false'message' => 'Client non trouvé'], 404);
  7909.     }
  7910.     /**
  7911.      * @Route("/admin/rdv/update-rdv-status", name="admin_rdv_update_status", methods={"POST"})
  7912.      */
  7913.     public function updateRdvStatus(Request $requestEntityManagerInterface $entityManager): JsonResponse
  7914.     {
  7915.         $data json_decode($request->getContent(), true);
  7916.         $rdvId $data['rdvId'] ?? null;
  7917.         $statusId $data['statusId'] ?? null;
  7918.         if (!$rdvId || !$statusId) {
  7919.             return new JsonResponse(['success' => false'message' => 'Données manquantes'], 400);
  7920.         }
  7921.         // Récupérer le RDV
  7922.         $rdv $entityManager->getRepository(Rdv::class)->find($rdvId);
  7923.         if (!$rdv) {
  7924.             return new JsonResponse(['success' => false'message' => 'RDV non trouvé'], 404);
  7925.         }
  7926.         // Récupérer le statut
  7927.         $etatRdv $entityManager->getRepository(EtatRdv::class)->find($statusId);
  7928.         if (!$etatRdv) {
  7929.             return new JsonResponse(['success' => false'message' => 'Statut non trouvé'], 404);
  7930.         }
  7931.         // Mettre à jour le statut du RDV
  7932.         $rdv->setIdEtat($etatRdv);
  7933.         $entityManager->flush();
  7934.         return new JsonResponse(['success' => true]);
  7935.     }
  7936.     /**
  7937.      * @Route("/admin/rdv/export-pdf/{startDate}/{endDate}", name="admin_rdv_export_pdf", methods={"GET"})
  7938.      */
  7939.     public function exportPdfFromDate(string $startDatestring $endDateKernelInterface $kernel): Response
  7940.     {
  7941.         $start = new \DateTimeImmutable($startDate);
  7942.         $end = new \DateTimeImmutable($endDate);
  7943.         $today = new \DateTimeImmutable();
  7944.         $rdvs $this->rdvRepository->findBySinceDateAndMyAudio($start$end);
  7945.         $html "
  7946.     <html>
  7947.     <head>
  7948.         <style>
  7949.             body { font-family: Arial, sans-serif; font-size: 13px; }
  7950.             table { width: 100%; border-collapse: collapse; font-size: 11px; }
  7951.             th, td { border: 1px solid #000; padding: 5px; text-align: left; }
  7952.             th { font-weight: bold; }
  7953.             h1 { font-size: 14px; }
  7954.         </style>
  7955.     </head>
  7956.     <body>
  7957.         <h1>Rendez-vous My Audio du " $start->format('d/m/Y') . " au " $end->format('d/m/Y') . "</h1>
  7958.         <table cellspacing='0' cellpadding='5'>
  7959.             <thead>
  7960.                 <tr>
  7961.                     <th>ID du RDV</th>
  7962.                     <th>Date du RDV</th>
  7963.                     <th>Jours écoulés</th>
  7964.                     <th>Statut RDV</th>
  7965.                     <th>Nom patient</th>
  7966.                     <th>Téléphone patient</th>
  7967.                     <th>Statut patient</th>
  7968.                     <th>Centre</th>
  7969.                     <th>Téléphone Centre</th>
  7970.                     <th>Adresse</th>
  7971.                     <th>Nom Audio</th>
  7972.                 </tr>
  7973.             </thead>
  7974.             <tbody>";
  7975.         foreach ($rdvs as $rdv) {
  7976.             $dateRdv $rdv->getDate();
  7977.             $joursEcoules $dateRdv->diff($today)->days;
  7978.             $client $rdv->getIdClient();
  7979.             $centre $rdv->getIdCentre();
  7980.             $etat $rdv->getIdEtat();
  7981.             $audio $rdv->getIdAudio();
  7982.             $html .= "<tr>
  7983.             <td>" $rdv->getId() . "</td>
  7984.             <td>" $dateRdv->format('d/m/Y H:i') . "</td>
  7985.             <td>" $joursEcoules " jours</td>
  7986.             <td>" . ($etat htmlspecialchars($etat->getLibelle()) : 'Non défini') . "</td>
  7987.             <td>" . ($client htmlspecialchars($client->getName() . ' ' $client->getLastname()) : '') . "</td>
  7988.             <td>" . ($client htmlspecialchars($client->getPhone()) : '') . "</td>
  7989.             <td>" . ($client && $client->getClientStatus() ? htmlspecialchars($client->getClientStatus()->getLibelle()) : 'Non défini') . "</td>
  7990.             <td>" . ($centre htmlspecialchars($centre->getName()) : '') . "</td>
  7991.             <td>" . ($centre htmlspecialchars($centre->getPhone()) : '') . "</td>
  7992.             <td>" . ($centre htmlspecialchars($centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity()) : '') . "</td>
  7993.             <td>" . ($audio htmlspecialchars($audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastname()) : '') . "</td>
  7994.         </tr>";
  7995.         }
  7996.         $html .= "</tbody></table></body></html>";
  7997.         // Configuration et rendu du PDF
  7998.         $options = new Options();
  7999.         $options->set('defaultFont''Arial');
  8000.         $dompdf = new Dompdf($options);
  8001.         $dompdf->loadHtml($html);
  8002.         $dompdf->setPaper('A4''landscape');
  8003.         $dompdf->render();
  8004.         // Création du dossier s'il n'existe pas
  8005.         $projectDir $kernel->getProjectDir();
  8006.         $outputDir $projectDir '/public/assets/pdf/rdv';
  8007.         $filesystem = new Filesystem();
  8008.         if (!$filesystem->exists($outputDir)) {
  8009.             $filesystem->mkdir($outputDir0775);
  8010.         }
  8011.         $filenameDate $start->format('Y-m-d') . '_to_' $end->format('Y-m-d');
  8012.         $outputPath "$outputDir/rdvs-$filenameDate.pdf";
  8013.         file_put_contents($outputPath$dompdf->output());
  8014.         return new Response($dompdf->output(), 200, [
  8015.             'Content-Type' => 'application/pdf',
  8016.             'Content-Disposition' => 'attachment; filename="rdvs-' $filenameDate '.pdf"',
  8017.         ]);
  8018.     }
  8019.     /**
  8020.      * @Route("/optical/rdv/export-pdf/{startDate}/{endDate}", name="optical_rdv_export_pdf", methods={"GET"})
  8021.      */
  8022.     public function exportOpticalPdfFromDate(string $startDatestring $endDateKernelInterface $kernel): Response
  8023.     {
  8024.         $start = new \DateTimeImmutable($startDate);
  8025.         $end = new \DateTimeImmutable($endDate);
  8026.         $today = new \DateTimeImmutable();
  8027.         $rdvs $this->rdvRepository->findOpticalBySinceDateAndMyAudio($start$end);
  8028.         $html "
  8029.     <html>
  8030.     <head>
  8031.         <style>
  8032.             body { font-family: Arial, sans-serif; font-size: 13px; }
  8033.             table { width: 100%; border-collapse: collapse; font-size: 11px; }
  8034.             th, td { border: 1px solid #000; padding: 5px; text-align: left; }
  8035.             th { font-weight: bold; }
  8036.             h1 { font-size: 14px; }
  8037.         </style>
  8038.     </head>
  8039.     <body>
  8040.         <h1>Rendez-vous My Audio du " $start->format('d/m/Y') . " au " $end->format('d/m/Y') . "</h1>
  8041.         <table cellspacing='0' cellpadding='5'>
  8042.             <thead>
  8043.                 <tr>
  8044.                     <th>ID du RDV</th>
  8045.                     <th>Date du RDV</th>
  8046.                     <th>Jours écoulés</th>
  8047.                     <th>Statut RDV</th>
  8048.                     <th>Nom patient</th>
  8049.                     <th>Téléphone patient</th>
  8050.                     <th>Statut patient</th>
  8051.                     <th>Centre</th>
  8052.                     <th>Téléphone Centre</th>
  8053.                     <th>Adresse</th>
  8054.                     <th>Nom Audio</th>
  8055.                 </tr>
  8056.             </thead>
  8057.             <tbody>";
  8058.         foreach ($rdvs as $rdv) {
  8059.             $dateRdv $rdv->getDate();
  8060.             $joursEcoules $dateRdv->diff($today)->days;
  8061.             $client $rdv->getIdClient();
  8062.             $centre $rdv->getIdCentre();
  8063.             $etat $rdv->getIdEtat();
  8064.             $audio $rdv->getIdAudio();
  8065.             $html .= "<tr>
  8066.             <td>" $rdv->getId() . "</td>
  8067.             <td>" $dateRdv->format('d/m/Y H:i') . "</td>
  8068.             <td>" $joursEcoules " jours</td>
  8069.             <td>" . ($etat htmlspecialchars($etat->getLibelle()) : 'Non défini') . "</td>
  8070.             <td>" . ($client htmlspecialchars($client->getName() . ' ' $client->getLastname()) : '') . "</td>
  8071.             <td>" . ($client htmlspecialchars($client->getPhone()) : '') . "</td>
  8072.             <td>" . ($client && $client->getClientStatus() ? htmlspecialchars($client->getClientStatus()->getLibelle()) : 'Non défini') . "</td>
  8073.             <td>" . ($centre htmlspecialchars($centre->getName()) : '') . "</td>
  8074.             <td>" . ($centre htmlspecialchars($centre->getPhone()) : '') . "</td>
  8075.             <td>" . ($centre htmlspecialchars($centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity()) : '') . "</td>
  8076.             <td>" . ($audio htmlspecialchars($audio->getCivilite() . ' ' $audio->getName() . ' ' $audio->getLastname()) : '') . "</td>
  8077.         </tr>";
  8078.         }
  8079.         $html .= "</tbody></table></body></html>";
  8080.         // Configuration et rendu du PDF
  8081.         $options = new Options();
  8082.         $options->set('defaultFont''Arial');
  8083.         $dompdf = new Dompdf($options);
  8084.         $dompdf->loadHtml($html);
  8085.         $dompdf->setPaper('A4''landscape');
  8086.         $dompdf->render();
  8087.         // Création du dossier s'il n'existe pas
  8088.         $projectDir $kernel->getProjectDir();
  8089.         $outputDir $projectDir '/public/assets/pdf/rdv';
  8090.         $filesystem = new Filesystem();
  8091.         if (!$filesystem->exists($outputDir)) {
  8092.             $filesystem->mkdir($outputDir0775);
  8093.         }
  8094.         $filenameDate $start->format('Y-m-d') . '_to_' $end->format('Y-m-d');
  8095.         $outputPath "$outputDir/rdvs-$filenameDate.pdf";
  8096.         file_put_contents($outputPath$dompdf->output());
  8097.         return new Response($dompdf->output(), 200, [
  8098.             'Content-Type' => 'application/pdf',
  8099.             'Content-Disposition' => 'attachment; filename="rdvs-' $filenameDate '.pdf"',
  8100.         ]);
  8101.     }
  8102.     /**
  8103.      * 
  8104.      * @Route("/admin/rdv/export/excel/{startDate}/{endDate}", name="admin_rdv_export_excel", methods={"GET"})
  8105.      */
  8106.     public function exportExcelFromDate(string $startDatestring $endDate): Response
  8107.     {
  8108.         $start = new \DateTimeImmutable($startDate);
  8109.         $end = new \DateTimeImmutable($endDate);
  8110.         $rdvs $this->rdvRepository->findBySinceDateAndMyAudio($start$end);
  8111.         $spreadsheet = new Spreadsheet();
  8112.         $sheet $spreadsheet->getActiveSheet();
  8113.         // Headers
  8114.         $sheet->fromArray([
  8115.             'ID du RDV',
  8116.             'Date du RDV',
  8117.             'Jours écoulés',
  8118.             'Statut RDV',
  8119.             'Nom patient',
  8120.             'Téléphone patient',
  8121.             'Statut patient',
  8122.             'Centre',
  8123.             'Téléphone Centre',
  8124.             'Adresse',
  8125.             'Nom Audio'
  8126.         ], null'A1');
  8127.         $today = new \DateTimeImmutable();
  8128.         $row 2;
  8129.         foreach ($rdvs as $rdv) {
  8130.             $dateRdv $rdv->getDate();
  8131.             $joursEcoules $dateRdv->diff($today)->days;
  8132.             $client $rdv->getIdClient();
  8133.             $centre $rdv->getIdCentre();
  8134.             $etat $rdv->getIdEtat();
  8135.             $sheet->fromArray([
  8136.                 $rdv->getId(),
  8137.                 $dateRdv->format('d/m/Y H:i'),
  8138.                 $joursEcoules ' jours',
  8139.                 $etat $etat->getLibelle() : 'Non défini',
  8140.                 $client $client->getName() . ' ' $client->getLastname() : '',
  8141.                 $client $client->getPhone() : '',
  8142.                 $client && $client->getClientStatus() ? $client->getClientStatus()->getLibelle() : 'Non défini',
  8143.                 $centre $centre->getName() : '',
  8144.                 $centre $centre->getPhone() : '',
  8145.                 $centre $centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity() : '',
  8146.                 $rdv->getIdAudio() ? $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastname() : '',
  8147.             ], null'A' $row);
  8148.             $row++;
  8149.         }
  8150.         $writer = new Xlsx($spreadsheet);
  8151.         $filename "rdvs-$startDate-to-$endDate.xlsx";
  8152.         // Stream the file to browser
  8153.         $response = new \Symfony\Component\HttpFoundation\StreamedResponse(function () use ($writer) {
  8154.             $writer->save('php://output');
  8155.         });
  8156.         $dispositionHeader $response->headers->makeDisposition(
  8157.             \Symfony\Component\HttpFoundation\ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  8158.             $filename
  8159.         );
  8160.         $response->headers->set('Content-Type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  8161.         $response->headers->set('Content-Disposition'$dispositionHeader);
  8162.         return $response;
  8163.     }
  8164.     /**
  8165.      * 
  8166.      * @Route("/optical/rdv/export/excel/{startDate}/{endDate}", name="optical_rdv_export_excel", methods={"GET"})
  8167.      */
  8168.     public function exportOpticalExcelFromDate(string $startDatestring $endDate): Response
  8169.     {
  8170.         $start = new \DateTimeImmutable($startDate);
  8171.         $end = new \DateTimeImmutable($endDate);
  8172.         $rdvs $this->rdvRepository->findOpticalBySinceDateAndMyAudio($start$end);
  8173.         $spreadsheet = new Spreadsheet();
  8174.         $sheet $spreadsheet->getActiveSheet();
  8175.         // Headers
  8176.         $sheet->fromArray([
  8177.             'ID du RDV',
  8178.             'Date du RDV',
  8179.             'Jours écoulés',
  8180.             'Statut RDV',
  8181.             'Nom patient',
  8182.             'Téléphone patient',
  8183.             'Statut patient',
  8184.             'Centre',
  8185.             'Téléphone Centre',
  8186.             'Adresse',
  8187.             'Nom Audio'
  8188.         ], null'A1');
  8189.         $today = new \DateTimeImmutable();
  8190.         $row 2;
  8191.         foreach ($rdvs as $rdv) {
  8192.             $dateRdv $rdv->getDate();
  8193.             $joursEcoules $dateRdv->diff($today)->days;
  8194.             $client $rdv->getIdClient();
  8195.             $centre $rdv->getIdCentre();
  8196.             $etat $rdv->getIdEtat();
  8197.             $sheet->fromArray([
  8198.                 $rdv->getId(),
  8199.                 $dateRdv->format('d/m/Y H:i'),
  8200.                 $joursEcoules ' jours',
  8201.                 $etat $etat->getLibelle() : 'Non défini',
  8202.                 $client $client->getName() . ' ' $client->getLastname() : '',
  8203.                 $client $client->getPhone() : '',
  8204.                 $client && $client->getClientStatus() ? $client->getClientStatus()->getLibelle() : 'Non défini',
  8205.                 $centre $centre->getName() : '',
  8206.                 $centre $centre->getPhone() : '',
  8207.                 $centre $centre->getAddress() . ', ' $centre->getPostale() . ' ' $centre->getCity() : '',
  8208.                 $rdv->getIdAudio() ? $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastname() : '',
  8209.             ], null'A' $row);
  8210.             $row++;
  8211.         }
  8212.         $writer = new Xlsx($spreadsheet);
  8213.         $filename "rdvs-$startDate-to-$endDate.xlsx";
  8214.         // Stream the file to browser
  8215.         $response = new \Symfony\Component\HttpFoundation\StreamedResponse(function () use ($writer) {
  8216.             $writer->save('php://output');
  8217.         });
  8218.         $dispositionHeader $response->headers->makeDisposition(
  8219.             \Symfony\Component\HttpFoundation\ResponseHeaderBag::DISPOSITION_ATTACHMENT,
  8220.             $filename
  8221.         );
  8222.         $response->headers->set('Content-Type''application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
  8223.         $response->headers->set('Content-Disposition'$dispositionHeader);
  8224.         return $response;
  8225.     }
  8226.     /**
  8227.      * 
  8228.      * @Route("/admin/update-note", name="update_note", methods={"POST"})
  8229.      */
  8230.     public function updateNote(Request $requestEntityManagerInterface $em): JsonResponse
  8231.     {
  8232.         $data json_decode($request->getContent(), true);
  8233.         $id $data['id'] ?? null;
  8234.         $note $data['note'] ?? null;
  8235.         if (!$id || $note === null) {
  8236.             return new JsonResponse(['status' => 'error''message' => 'Invalid data'], 400);
  8237.         }
  8238.         $entity $em->getRepository(Rdv::class)->find($id);
  8239.         if (!$entity) {
  8240.             return new JsonResponse(['status' => 'error''message' => 'Entity not found'], 404);
  8241.         }
  8242.         $entity->setNote($note);
  8243.         $em->flush();
  8244.         return new JsonResponse(['status' => 'success']);
  8245.     }
  8246.     /**
  8247.      * 
  8248.      * @Route("/giuili-admin/edit-rdv/{rdvId}/centre/{centreId}", name="update_admin_rdv", methods={"GET"})
  8249.      */
  8250.     public function showRdvCentre(int $rdvIdCentre $centreId): Response
  8251.     {
  8252.         // dd("tets");
  8253.         $center $centres $this->getDoctrine()
  8254.             ->getRepository(AudioCentre::class)
  8255.             ->findOneBy(['id_centre' => $centreId->getId()]);
  8256.         $audio $center->getIdAudio();
  8257.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  8258.             ->findBy(['id_audio' => $audio'isDeleted' => 0]);
  8259.         return $this->render('easyadmin/rdv/centre_show.html.twig', [
  8260.             'audio' => $audio,
  8261.             'rdvId' => $rdvId,
  8262.             'centreId' => $centreId,
  8263.             'motifs' => $motifs,
  8264.         ]);
  8265.     }
  8266.     
  8267.     /**
  8268.      * 
  8269.      * @Route("/optical-center/edit-rdv/{rdvId}/centre/{centreId}", name="update_optical_rdv", methods={"GET"})
  8270.      */
  8271.     public function showRdvCentreOptical(int $rdvIdCentre $centreId): Response
  8272.     {
  8273.         // dd("tets");
  8274.         $center $centres $this->getDoctrine()
  8275.             ->getRepository(AudioCentre::class)
  8276.             ->findOneBy(['id_centre' => $centreId->getId()]);
  8277.         $audio $center->getIdAudio();
  8278.         $motifs $this->getDoctrine()->getRepository(AudioMotif::class)
  8279.             ->findBy(['id_audio' => $audio'isDeleted' => 0]);
  8280.         return $this->render('easyadmin/rdv/centre_show.html.twig', [
  8281.             'audio' => $audio,
  8282.             'rdvId' => $rdvId,
  8283.             'centreId' => $centreId,
  8284.             'motifs' => $motifs,
  8285.         ]);
  8286.     }
  8287.     /**
  8288.      * @Route("/update-rdv-easyadmin", name="update_rdv_easyadmin", methods={"POST"})
  8289.      */
  8290.     public function updateRdvEasyadmin(Request $requestPublicFunction $publicFunctionGoogleCalendarService $googleCalendarRdvSmsService $rdvSms): Response
  8291.     {
  8292.         $data json_decode($request->getContent(), true);
  8293.         $rdv $this->getDoctrine()
  8294.             ->getRepository(Rdv::class)
  8295.             ->find($data["rdv_id"]);
  8296.         $pastDate $rdv->getDate();
  8297.         $entityManager $this->getDoctrine()->getManager();
  8298.         if (isset($data["etat_id"])) {
  8299.             $etat $this->getDoctrine()
  8300.                 ->getRepository(EtatRdv::class)
  8301.                 ->findOneBy(['id' => $data["etat_id"]]);
  8302.             if ($etat == null) {
  8303.                 return new Response(json_encode(([
  8304.                     'message' => 'Error, no etat found at this id',
  8305.                     'path' => 'src/Controller/TrustedUserController.php',
  8306.                     "status" => 400,
  8307.                 ])), 400);
  8308.             }
  8309.             $rdv->setIdEtat($etat);
  8310.         }
  8311.         if (isset($data["audio_id"])) {
  8312.             $audio $this->getDoctrine()
  8313.                 ->getRepository(Audio::class)
  8314.                 ->findOneBy(['id' => $data["audio_id"]]);
  8315.             if ($audio == null) {
  8316.                 return new Response(json_encode(([
  8317.                     'message' => 'Error, no audio found at this id',
  8318.                     'path' => 'src/Controller/TrustedUserController.php',
  8319.                     "status" => 400,
  8320.                 ])), 400);
  8321.             }
  8322.             $rdv->setIdAudio($audio);
  8323.         }
  8324.         if (isset($data["motif_id"])) {
  8325.             $motif $this->getDoctrine()
  8326.                 ->getRepository(Motif::class)
  8327.                 ->find($data["motif_id"]);
  8328.             if ($motif == null) {
  8329.                 return new Response(json_encode(([
  8330.                     'message' => 'Error, no motif found at this id',
  8331.                     'path' => 'src/Controller/TrustedUserController.php',
  8332.                     "status" => 400,
  8333.                 ])), 400);
  8334.             }
  8335.             $rdv->setIdMotif($motif);
  8336.         }
  8337.         if (isset($data["client_id"])) {
  8338.             $client $this->getDoctrine()
  8339.                 ->getRepository(Client::class)
  8340.                 ->findOneBy(['id' => $data["client_id"]]);
  8341.             if ($client == null) {
  8342.                 return new Response(json_encode(([
  8343.                     'message' => 'Error, no client found at this id',
  8344.                     'path' => 'src/Controller/TrustedUserController.php',
  8345.                     "status" => 400,
  8346.                 ])), 400);
  8347.             }
  8348.             $rdv->setIdClient($client);
  8349.         }
  8350.         if (isset($data["date"])) {
  8351.             $data["date"] = str_replace("h"":"$data["date"]);
  8352.             $date \DateTime::createFromFormat("Y-m-d\TH:i"$data["date"]);
  8353.             $audioMotif $this->getDoctrine()
  8354.                 ->getRepository(AudioMotif::class)
  8355.                 ->findOneBy(["id_audio" => $rdv->getIdAudio()->getId(), "id_motif" => $rdv->getIdMotif()->getId()]);
  8356.             if ($audioMotif == null) {
  8357.                 return new Response(json_encode(([
  8358.                     'message' => 'Error, no motif of this id found at this audio',
  8359.                     'path' => 'src/Controller/RdvController.php',
  8360.                     "status" => 400,
  8361.                 ])), 400);
  8362.             }
  8363.             if ($rdv->getIdAudio()->getIsIndie()) {
  8364.                 if ($rdv->getIdCentre()) {
  8365.                     // regular centre audio indie
  8366.                     /** @var AudioCentre */
  8367.                     $liaison $this->getDoctrine()
  8368.                         ->getRepository(AudioCentre::class)
  8369.                         ->findOneBy(['id_centre' => $rdv->getIdCentre()->getId(), 'id_audio' => $rdv->getIdAudio()->getId()]);
  8370.                     if ($liaison == null) {
  8371.                         return new Response(json_encode(([
  8372.                             'message' => 'Error, audio isnt part of the centre',
  8373.                             'path' => 'src/Controller/RdvController.php',
  8374.                             "status" => 400,
  8375.                         ])), 400);
  8376.                     }
  8377.                     if ($liaison->getHoraire() == null || $liaison->getHoraire() == []) {
  8378.                         return new Response(json_encode(([
  8379.                             'message' => 'Error, no horaire found for this audio',
  8380.                             'path' => 'src/Controller/RdvController.php',
  8381.                             "status" => 400,
  8382.                         ])), 400);
  8383.                     }
  8384.                 } else {
  8385.                     // lieu audio indie
  8386.                     if ($rdv->getIdLieu()->getHoraire() == null || $rdv->getIdLieu()->getHoraire() == []) {
  8387.                         return new Response(json_encode(([
  8388.                             'message' => 'Error, no horaire found for this audio',
  8389.                             'path' => 'src/Controller/RdvController.php',
  8390.                             "status" => 400,
  8391.                         ])), 400);
  8392.                     }
  8393.                 }
  8394.             } else {
  8395.                 // regular centre
  8396.                 if ($rdv->getIdCentre()->getHoraire() == null || $rdv->getIdCentre()->getHoraire() == []) {
  8397.                     return new Response(json_encode(([
  8398.                         'message' => 'Error, no horaire found for this audio',
  8399.                         'path' => 'src/Controller/RdvController.php',
  8400.                         "status" => 400,
  8401.                     ])), 400);
  8402.                 }
  8403.             }
  8404.             $rdv->setDate($date);
  8405.         }
  8406.         if (isset($data["comment"]) && $token->getIdClient()) {
  8407.             $rdv->setComment($data["comment"]);
  8408.         }
  8409.         if (isset($data["review"]) && $token->getIdClient()) {
  8410.             $rdv->setReview($data["review"]);
  8411.         }
  8412.         if (isset($data["note"])) {
  8413.             $rdv->setNote($data["note"]);
  8414.         }
  8415.         $entityManager->flush();
  8416.         $date $rdv->getDate();
  8417.         $smsDate $date->format('d-m-Y H:i');
  8418.         $oldDate $pastDate->format('d-m-Y H:i');
  8419.         $locale 'fr_FR';
  8420.         $formatter = new IntlDateFormatter(
  8421.             $locale,
  8422.             IntlDateFormatter::FULL,
  8423.             IntlDateFormatter::SHORT,
  8424.             null,
  8425.             IntlDateFormatter::GREGORIAN,
  8426.             'EEEE dd MMMM yyyy \'à\' HH\'h\'mm'
  8427.         );
  8428.         $smsDateLongFormat $formatter->format($date);
  8429.         $frenchDate preg_replace('/^(\w+\s\d+\s\w+).+$/u''$1'$smsDateLongFormat);
  8430.         $frenchDate ucfirst($frenchDate);
  8431.         $client $rdv->getIdClientTemp() ? $rdv->getIdClientTemp() : $rdv->getIdClient();
  8432.         // notif client
  8433.         if ($rdv->getIdEtat()->getId() != 2) {
  8434.             $params = array(
  8435.                 "lienModifer" => "{$_ENV['BASE_client']}mes-rendez-vous",
  8436.                 "lienAnnule" => "{$_ENV['BASE_client']}mes-rendez-vous",
  8437.                 "date" => $smsDateLongFormat,
  8438.                 "heure" => substr($smsDate1115),
  8439.                 "motif" => $rdv->getIdMotif()->getTitre(),
  8440.                 "centerName" => $rdv->getIdCentre()->getName(),
  8441.                 "centerAddress" => $rdv->getIdCentre()->getAddress(),
  8442.                 "centerPostalCode" => $rdv->getIdCentre()->getPostale(),
  8443.                 "audioMail" => $rdv->getIdAudio()->getMail(),
  8444.                 "centerPhone" => $rdv->getIdCentre()->getPhone(),
  8445.                 "centerCity" => $rdv->getIdCentre()->getCity(),
  8446.                 "audioproName" => $rdv->getIdAudio()->getCivilite() . " " $rdv->getIdAudio()->getName() . " " $rdv->getIdAudio()->getLastName(),
  8447.                 'titre' => 'Votre rendez-vous est modifié pour le',
  8448.                 'frenchDate' => $frenchDate,
  8449.             );
  8450.             $subject "Rendez-vous My Audio modifié pour " $frenchDate " à " substr($smsDate1115);
  8451.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject184);
  8452.             $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.";
  8453.             $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  8454.         }
  8455.         //     //// == suppression
  8456.         else if ($rdv->getIdEtat()->getId() == 2) {
  8457.             $params = array(
  8458.                 "date" => substr($smsDate010),
  8459.                 "lien" => "{$_ENV['BASE_client']}search",
  8460.                 "heure" => substr($smsDate1115),
  8461.                 "patientName" => $client->getLastName(),
  8462.                 'titre' => 'Votre rendez-vous est annulé :',
  8463.                 'centerName' => $rdv->getIdCentre()->getName(),
  8464.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  8465.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  8466.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  8467.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  8468.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  8469.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  8470.                 'motif' => $rdv->getIdMotif()->getTitre(),
  8471.             );
  8472.             $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  8473.             $publicFunction->sendEmail($params$client->getMail(), $client->getName() . ' ' $client->getLastName(), $subject188);
  8474.             if ($data["sms"]) {
  8475.                 $sms "Votre RDV a été annulé, contacter votre centre " $rdv->getIdCentre()->getPhone() . " pour prendre un autre RDV.\nNe pas répondre.";
  8476.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$client->getPhone());
  8477.             }
  8478.         }
  8479.         //notif Audio
  8480.         if ($rdv->getIdEtat()->getId() != 2) {
  8481.             $params = array(
  8482.                 "lienModifer" => "{$_ENV['BASE_logiciel']}rdv",
  8483.                 "lienAnnule" => "{$_ENV['BASE_logiciel']}rdv",
  8484.                 "date" => substr($smsDate010),
  8485.                 "frenchDate" => $frenchDate,
  8486.                 "heure" => substr($smsDate1115),
  8487.                 'motif' => $rdv->getIdMotif()->getTitre(),
  8488.                 'clientPhone' => $client->getPhone(),
  8489.                 'clientNom' => $client->getLastname(),
  8490.                 'clientPrenom' => $client->getName(),
  8491.                 'clientCivilite' => $client->getCivilite(),
  8492.                 'clientPostal' => $client->getPostal(),
  8493.                 'clientMail' => $client->getMail(),
  8494.                 'centerName' => $rdv->getIdCentre()->getName(),
  8495.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  8496.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  8497.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  8498.                 'idPatient' => $client->getId(),
  8499.                 'proUrl' => "{$_ENV['BASE_logiciel']}",
  8500.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  8501.                 'titre' => 'Votre rendez-vous est modifié pour le :'
  8502.             );
  8503.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  8504.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  8505.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  8506.                 $subject "🔀 Rendez-vous My Audio modifié du " $frenchDate " à " substr($smsDate1115);
  8507.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject186);
  8508.             }
  8509.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  8510.                 $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.";
  8511.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  8512.             }
  8513.         } else if ($rdv->getIdEtat()->getId() == 2) {
  8514.             $params = array(
  8515.                 "date" => substr($smsDate010),
  8516.                 "lien" => "{$_ENV['BASE_client']}search",
  8517.                 "heure" => substr($smsDate1115),
  8518.                 "patientName" => $client->getLastName(),
  8519.                 'titre' => 'Votre rendez-vous est annulé :',
  8520.                 'centerName' => $rdv->getIdCentre()->getName(),
  8521.                 'centerPostal' => $rdv->getIdCentre()->getPostale(),
  8522.                 'centerCity' => $rdv->getIdCentre()->getCity(),
  8523.                 'centerAddress' => $rdv->getIdCentre()->getAddress(),
  8524.                 'centerPhone' => $rdv->getIdCentre()->getPhone(),
  8525.                 'audioproName' => $rdv->getIdAudio()->getCivilite() . ' ' $rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(),
  8526.                 'audioMail' => $rdv->getIdAudio()->getMail(),
  8527.                 'motif' => $rdv->getIdMotif()->getTitre(),
  8528.             );
  8529.             $mailAudio $rdv->getIdAudio()->getMailNotif() ?? $rdv->getIdAudio()->getMail();
  8530.             $phoneAudio =  $rdv->getIdAudio()->getPhoneNotif() ?? $rdv->getIdAudio()->getPhone();
  8531.             if ($rdv->getIdAudio()->getModifRdvMail()) {
  8532.                 $subject "Rendez-vous My Audio annulé avec " $rdv->getIdCentre()->getName();
  8533.                 $publicFunction->sendEmail($params$mailAudio$rdv->getIdAudio()->getName() . ' ' $rdv->getIdAudio()->getLastName(), $subject188);
  8534.             }
  8535.             if ($rdv->getIdAudio()->getModifRdvSms()) {
  8536.                 $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.";
  8537.                 $publicFunction->sendSmsToOne("Gdv2LasZIr89Uhpe40U195YFXSvh4ynb"$sms$phoneAudio);
  8538.             }
  8539.         }
  8540.         /* generate sms notif on update */
  8541.         // update sms notification     
  8542.         $rdvSms->updateRdvSms($rdv);
  8543.         // google calendar update
  8544.         $synchronisations $this->getDoctrine()->getRepository(SynchronisationSetting::class)
  8545.             ->findBy(array('audio' => $rdv->getIdAudio()));
  8546.         $data['rdv'] = $rdv->getId();
  8547.         $data['motif_id'] = $rdv->getIdMotif();
  8548.         $data['note'] = $rdv->getNote();
  8549.         if ($rdv->getIdClient() !== null) {
  8550.             $data["client_id"] = $rdv->getIdClient()->getId();
  8551.         }
  8552.         if ($rdv->getIdClientTemp() !== null) {
  8553.             $data["client_id_temp"] = $rdv->getIdClientTemp()->getId();
  8554.         }
  8555.         $rdvEvents $this->getDoctrine()->getRepository(RdvEvent::class)
  8556.             ->findBy(array('rdv' => $rdv));
  8557.         foreach ($rdvEvents as $rdvEvent) {
  8558.             $googleCalendar->checkAndRefreshAccessToken($rdvEvent->getSynchronisation());
  8559.             $googleCalendar->updateEvent($rdvEvent->getSynchronisation(), $rdvEvent->getGoogleEventId(), $data);
  8560.         }
  8561.         return new Response(json_encode(([
  8562.             "id" => $rdv->getId(),
  8563.             "motif_id" => $rdv->getIdMotif()->getId(),
  8564.             "audio_id" => $rdv->getIdAudio()->getId(),
  8565.             "remplacant_id" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getId() : null,
  8566.             "imgUrl" => $rdv->getRemplacant() ? $rdv->getRemplacant()->getImgUrl() : $rdv->getIdAudio()->getImgUrl(),
  8567.             "fullName" => $rdv->getRemplacant() ? "{$rdv->getRemplacant()->getName()} {$rdv->getRemplacant()->getLastname()}"{$rdv->getIdAudio()->getName()} {$rdv->getIdAudio()->getLastname()}",
  8568.             "client_id" => $rdv->getIdClient() ? $rdv->getIdClient()->getId() : null,
  8569.             "client_id_temp" => $rdv->getIdClientTemp() ? $rdv->getIdClientTemp()->getId() : null,
  8570.             "proche_id" => $rdv->getIdProche() ? $rdv->getIdClient()->getId() : null,
  8571.             "centre_id" => $rdv->getIdCentre() ? $rdv->getIdCentre()->getId() : null,
  8572.             "lieu_id" => $rdv->getIdLieu() ? $rdv->getIdLieu()->getId() : null,
  8573.             "centre_id" => $rdv->getIdCentre()->getId(),
  8574.             "centerName" => $rdv->getIdCentre()->getName(),
  8575.             "etat_id" => $rdv->getIdEtat()->getId(),
  8576.             "date" => $rdv->getDate(),
  8577.             "comment" => $rdv->getComment(),
  8578.             "note" => $rdv->getNote(),
  8579.             "review" => $rdv->getReview(),
  8580.             "status" => 200,
  8581.         ])));
  8582.     }
  8583.     private function checkRdvReminder($rdv): ?array
  8584.     {
  8585.         $dateRdv $rdv->getDate();
  8586.         $today = new \DateTime();
  8587.         $today->setTime(000);
  8588.         $dateRdv->setTime(000);
  8589.         $intervalDays $today->diff($dateRdv)->days;
  8590.         if ($intervalDays === 1) {
  8591.             $interval "24";
  8592.         } elseif ($intervalDays === 2) {
  8593.             $interval "48";
  8594.         } elseif ($intervalDays === 3) {
  8595.             $interval "72";
  8596.         } elseif ($intervalDays === 4) {
  8597.             $interval "96";
  8598.         } else { // >= 4 jours
  8599.             $interval "92";
  8600.         }
  8601.         $client $rdv->getIdClientTemp() ?: $rdv->getIdClient();
  8602.         $clientId $client $client->getId() : null;
  8603.         $clientName null;
  8604.         if ($client) {
  8605.             $clientName $client->getName() . ' ' $client->getLastName();
  8606.         }
  8607.         $motif $rdv->getIdMotif();
  8608.         $motifTitle $motif $motif->getTitre() : null;
  8609.         $centre $rdv->getIdCentre();
  8610.         $centreName null;
  8611.         if ($centre) {
  8612.             $centreName $centre->getName();
  8613.         }
  8614.         return [
  8615.             'rdvId' => $rdv->getId(),
  8616.             'clientId' => $clientId,
  8617.             'clientName' => $clientName ?? 'N/A',
  8618.             'interval' => $interval,
  8619.             'date' => $rdv->getDate() ? $rdv->getDate()->format('d-m-Y H:i') : null,
  8620.             'motif' => $motifTitle ?? 'N/A',
  8621.             'centreName' => $centreName ?? 'N/A',
  8622.         ];
  8623.     }
  8624. }